Datasets:
AI4M
/

text
stringlengths
0
3.34M
\section{Introduction} \begin{theorem} Let $F,f:[a,b]\to\mathbb R$ are continuous and $F$ differentiable with $F^\prime=f$, we have $$\int_a^bf(t)\,\mathrm dt=F(b)-F(a)$$ \end{theorem} There is a reason why this theorem takes so long to prove. First of all obvious we need to actually define what we meant by all those terms in there and link them together. More subtlely, this is a theorem about the real numbers. Suppose $F^\prime=f=G^\prime$, then $F$ and $G$ can be differed by a constant. So if we set $$F(x)=\begin{cases} 1\text{, if $x^2>2$}\\ 0\text{, otherwise} \end{cases}$$ and $G\equiv 0$. So $F$ is differentiable at every rational number and those derivatives are $0$, and so is $G$, but $F$ is not constant. Hence the theorem is simply not true for rational numbers, so we must use properties of real numbers.\\ These are what real analysis (in a beginner's level) is going to be about.
lemma not_irreducible_one [simp]: "\<not>irreducible 1"
module Adjunctions where open import Library open import Categories open import Functors open Cat open Fun record Adj {a b c d}(C : Cat {a}{b})(D : Cat {c}{d}) : Set (a βŠ” b βŠ” c βŠ” d) where constructor adjunction field L : Fun C D R : Fun D C left : {X : Obj C}{Y : Obj D} β†’ Hom D (OMap L X) Y β†’ Hom C X (OMap R Y) right : {X : Obj C}{Y : Obj D} β†’ Hom C X (OMap R Y) β†’ Hom D (OMap L X) Y lawa : {X : Obj C}{Y : Obj D}(f : Hom D (OMap L X) Y) β†’ right (left f) β‰… f lawb : {X : Obj C}{Y : Obj D}(f : Hom C X (OMap R Y)) β†’ left (right f) β‰… f natleft : {X X' : Obj C}{Y Y' : Obj D} (f : Hom C X' X)(g : Hom D Y Y') (h : Hom D (OMap L X) Y) β†’ comp C (HMap R g) (comp C (left h) f) β‰… left (comp D g (comp D h (HMap L f))) natright : {X X' : Obj C}{Y Y' : Obj D} (f : Hom C X' X)(g : Hom D Y Y') (h : Hom C X (OMap R Y)) β†’ right (comp C (HMap R g) (comp C h f)) β‰… comp D g (comp D (right h) (HMap L f))
DSBGVX Example Program Results Number of eigenvalues found = 1 Eigenvalues 0.0992 Selected eigenvectors 1 1 0.6729 2 -0.1009 3 0.0155 4 -0.3806
[STATEMENT] lemma Lp_I: assumes "p > (0::real)" "f \<in> borel_measurable M" "integrable M (\<lambda>x. \<bar>f x\<bar> powr p)" shows "f \<in> space\<^sub>N (\<LL> p M)" "Norm (\<LL> p M) f = (\<integral>x. \<bar>f x\<bar> powr p \<partial>M) powr (1/p)" "eNorm (\<LL> p M) f = (\<integral>x. \<bar>f x\<bar> powr p \<partial>M) powr (1/p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f \<in> space\<^sub>N (\<LL> (ennreal p) M) &&& Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) &&& eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (3 subgoals): 1. f \<in> space\<^sub>N (\<LL> (ennreal p) M) 2. Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) 3. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] have *: "eNorm (\<LL> p M) f = (\<integral>x. \<bar>f x\<bar> powr p \<partial>M) powr (1/p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] by (cases "p \<le> 1", insert assms, auto simp add: Lp_le_1(1) Lp(1)) [PROOF STATE] proof (state) this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal (3 subgoals): 1. f \<in> space\<^sub>N (\<LL> (ennreal p) M) 2. Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) 3. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] show **: "f \<in> space\<^sub>N (\<LL> p M)" [PROOF STATE] proof (prove) using this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal (1 subgoal): 1. f \<in> space\<^sub>N (\<LL> (ennreal p) M) [PROOF STEP] unfolding space\<^sub>N_def [PROOF STATE] proof (prove) using this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal (1 subgoal): 1. f \<in> {f. eNorm (\<LL> (ennreal p) M) f < \<infinity>} [PROOF STEP] by auto [PROOF STATE] proof (state) this: f \<in> space\<^sub>N (\<LL> (ennreal p) M) goal (2 subgoals): 1. Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) 2. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] show "Norm (\<LL> p M) f = (\<integral>x. \<bar>f x\<bar> powr p \<partial>M) powr (1/p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) [PROOF STEP] using * [PROOF STATE] proof (prove) using this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal (1 subgoal): 1. Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) [PROOF STEP] unfolding Norm_def [PROOF STATE] proof (prove) using this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal (1 subgoal): 1. enn2real (eNorm (\<LL> (ennreal p) M) f) = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) goal (1 subgoal): 1. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) [PROOF STEP] show "eNorm (\<LL> p M) f = (\<integral>x. \<bar>f x\<bar> powr p \<partial>M) powr (1/p)" [PROOF STATE] proof (prove) using this: Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) goal (1 subgoal): 1. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] using eNorm_Norm[OF **] [PROOF STATE] proof (prove) using this: Norm (\<LL> (ennreal p) M) f = (LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p) eNorm (\<LL> (ennreal p) M) f = ennreal (Norm (\<LL> (ennreal p) M) f) goal (1 subgoal): 1. eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: eNorm (\<LL> (ennreal p) M) f = ennreal ((LINT x|M. \<bar>f x\<bar> powr p) powr (1 / p)) goal: No subgoals! [PROOF STEP] qed
const MKLFloats = Union{Float32,Float64,ComplexF32,ComplexF64} struct mklsparsecsr{T} where {T<:MKLFloats} r::Ref{Ptr{Cvoid}} desc::matrix_descr end const createcsr = Dict( Float32 => :mkl_sparse_s_create_csr, Float64 => :mkl_sparse_d_create_csr, ComplexF32 => :mkl_sparse_c_create_csr, ComplexF64 => :mkl_sparse_z_create_csr, ) function mklsparsecsr(a::SparseMatrixCSC{T,BlasInt}) where {T<:MKLFloats} p = Ref(Ptr{Cvoid}(0)) ret = ccall( (createcsr[T], libmkl_rt), sparse_status_t, (Ref{Ptr{Cvoid}}, sparse_index_base_t, BlasInt, BlasInt, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{T}), p, SPARSE_INDEX_BASE_ONE, m.m, m.n, m.colptr, pointer(m.colptr, 2), m.rowval, m.nzval) ret == SPARSE_STATUS_SUCCESS || throw(ArgumentError(string(ret))) mklsparsecsr{T}( p, matrix_descr(SPARSE_MATRIX_TYPE_GENERAL, SPARSE_FILL_MODE_FULL, SPARSE_DIAG_NON_UNIT), ) end
[STATEMENT] lemma append_fusion [code]: "append_fusion g1 g2 s1 s2 = (if list.has_next g1 s1 then let (x, s1') = list.next g1 s1 in x # append_fusion g1 g2 s1' s2 else list.unfoldr g2 s2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. append_fusion g1 g2 s1 s2 = (if list.has_next g1 s1 then let (x, s1') = list.next g1 s1 in x # append_fusion g1 g2 s1' s2 else list.unfoldr g2 s2) [PROOF STEP] unfolding append_fusion_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. list.unfoldr g1 s1 @ list.unfoldr g2 s2 = (if list.has_next g1 s1 then let (x, s1') = list.next g1 s1 in x # list.unfoldr g1 s1' @ list.unfoldr g2 s2 else list.unfoldr g2 s2) [PROOF STEP] by(subst list.unfoldr.simps)(simp add: split_beta)
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_exploration.ipynb (unless otherwise specified). __all__ = ['read_tsv', 'gzip_reading'] # Cell # Library import pandas as pd from zipfile import ZipFile from scipy import spatial import os # Cell # Functions def read_tsv(file): return pd.read_csv(file, compression='gzip', sep='\t') def gzip_reading(gzip_file): archive = ZipFile(gzip_file, 'r') files = {name: archive.open(name) for name in archive.namelist() if (name.endswith('.gz') and not name.startswith('_'))} files_names = [i.split('.')[0] for i in files.keys()] dt={} for name, key in zip(files_names, files.keys()): dt[name]=read_tsv(files[key]) return dt
If two holomorphic functions agree on all derivatives at a point in a connected open set, then they are equal on the whole set.
(** Catalan number via generating functions *) (******************************************************************************) (* Copyright (C) 2019 Florent Hivert <[email protected]> *) (* *) (* Distributed under the terms of the GNU General Public License (GPL) *) (* *) (* This code is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* General Public License for more details. *) (* *) (* The full text of the GPL is available at: *) (* *) (* http://www.gnu.org/licenses/ *) (******************************************************************************) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq. From mathcomp Require Import fintype div bigop ssralg binomial rat ssrnum. Require tfps. Require Import auxresults fps. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Catalan. Variable (C : nat -> nat). Hypothesis C0 : C 0 = 1%N. Hypothesis CS : forall n : nat, C n.+1 = \sum_(i < n.+1) C i * C (n - i). Local Definition Csimpl := (C0, CS, big_ord0, big_ord_recl). Example C1 : C 1 = 1. Proof. by rewrite !Csimpl. Qed. Example C2 : C 2 = 2. Proof. by rewrite !Csimpl. Qed. Example C3 : C 3 = 5. Proof. by rewrite !Csimpl. Qed. Example C4 : C 4 = 14. Proof. by rewrite !Csimpl. Qed. Example C5 : C 5 = 42. Proof. by rewrite !Csimpl. Qed. Import GRing.Theory. Local Definition Rat := [fieldType of rat]. Local Definition char_Rat := Num.Theory.char_num [numDomainType of Rat]. Local Definition nat_unit := tfps.TFPSField.nat_unit_field char_Rat. Local Definition fact_unit := tfps.TFPSField.fact_unit char_Rat. Hint Resolve char_Rat nat_unit : core. Section GenSeries. Local Open Scope ring_scope. Local Open Scope fps_scope. Definition FC : {fps Rat} := \fps (C i)%:R .X^i. Lemma FC_in_coef0_eq1 : FC \in coefs0_eq1. Proof. by rewrite coefs0_eq1E coefs_FPSeries C0. Qed. Proposition FC_algebraic_eq : FC = 1 + ''X * FC ^+ 2. Proof. rewrite /FC; apply/fpsP => i. rewrite !(coefs_FPSeries, coefs_simpl, coef_fpsXM). case: i => [|i]; first by rewrite C0 addr0. rewrite add0r CS /= expr2 coefsM natr_sum. apply eq_bigr => [[j /= _]] _. by rewrite !coefs_FPSeries natrM. Qed. End GenSeries. (** Extraction of the coefficient using square root and Newton's formula *) Section AlgebraicSolution. Local Open Scope ring_scope. Local Open Scope fps_scope. Lemma mulr_nat i (f : {fps Rat}) : i%:R *: f = i%:R * f. Proof. by rewrite scaler_nat -[f *+ i]mulr_natr mulrC. Qed. Theorem FC_algebraic_solution : ''X * FC = 2%:R^-1 *: (1 - \sqrt (1 - 4%:R *: ''X)). Proof. have co1 : 1 - 4%:R *: ''X \in @coefs0_eq1 Rat. by rewrite mulr_nat coefs0_eq1E !coefs_simpl mulrC coef_fpsXM subr0. have: (2%:R *: ''X * FC - 1) ^+ 2 = 1 - 4%:R *: ''X. apply/eqP; rewrite !mulr_nat sqrrB1 !exprMn 2!expr2 -natrM. rewrite mulrA -subr_eq0 opprB [_ - 1]addrC addrA addrK addrC addrA. rewrite -{1}(mulr1 (4%:R * _)) -[X in _ + X + _]mulrA -mulrDr. rewrite -FC_algebraic_eq. by rewrite -[_ *+ 2]mulr_natl !mulrA -natrM subrr. move/(sqrtE nat_unit) => /(_ co1) [HeqP | HeqN]. exfalso; move: HeqP => /(congr1 (fun x => x``_0)). rewrite mulr_nat coefsB -mulrA mulrC -mulrA coef_fpsXM coefs1. rewrite (eqP (coefs0_eq1_expr _ _)) /= => /eqP. rewrite -subr_eq0 add0r -oppr_eq0 opprD opprK -mulr2n => /eqP Habs. by have:= char_Rat 2; rewrite !inE Habs /= eq_refl. have neq20 : 2%:R != 0 :> Rat by rewrite Num.Theory.pnatr_eq0. apply (scalerI neq20); rewrite scalerA divff // scale1r -HeqN. by rewrite addrC subrK scalerAl. Qed. Theorem coefFC i : FC``_i = i.*2`!%:R / i`!%:R /i.+1`!%:R. Proof. have:= congr1 (fun x => x``_i.+1) FC_algebraic_solution. rewrite coef_fpsXM ![X in (X = _)]/= => ->. rewrite coefsZ coefsB coefs1 sub0r -scaleNr coef_expr1cX ?{}Hi //. rewrite mulrN mulrA -mulNr; congr (_ / (i.+1)`!%:R). rewrite -[4]/(2 * 2)%N mulrnA -mulNrn -[(1 *- 2 *+ 2)]mulr_natl. rewrite exprMn -mulrA. have -> : (1 *- 2)^+ i.+1 = \prod_(i0 < i.+1) (1 *- 2) :> rat. by rewrite prodr_const /= card_ord. rewrite -big_split /= big_ord_recl /=. rewrite subr0 mulNr divrr // mulN1r 2!mulrN [LHS]opprK. rewrite exprS !mulrA [2%:R^-1 * 2%:R]mulVf // mul1r. rewrite (eq_bigr (fun j : 'I_i => (2 * j + 1)%:R)) /=; last first. move=> j _; rewrite /bump /=. rewrite mulNr -mulrN opprD addrC opprK addnC natrD 2!mulrDr. rewrite mulrN divff // mulr1 -{2}addn1 {2}natrD addrA addrK. by rewrite natrD natrM. elim: i => [|i IHi]; first by rewrite expr0 big_ord0 double0 fact0 mulr1. rewrite big_ord_recr /= exprS -mulrA mulrC mulrA {}IHi. rewrite doubleS !factS 3!natrM. set F := (i.*2)`!%:R; rewrite [_ * F]mulrC mulrA [_ * F]mulrC -!mulrA. congr (_ * _); rewrite {F} mulrC invfM // !mulrA; congr (_ * _). rewrite mul2n -{2}[i.*2.+1]addn1 [X in X / _]mulrC -mulrA; congr (_ * _). rewrite -[i.*2.+2]addn1 addSnnS -mul2n -[X in (_ + X)%N]muln1. rewrite -mulnDr addn1 natrM mulfK //. by have /charf0P -> := char_Rat. Qed. Theorem Cat_rat i : (C i)%:R = i.*2`!%:R / i`!%:R /i.+1`!%:R :> Rat. Proof. by rewrite -coefFC coefs_FPSeries. Qed. Local Close Scope ring_scope. Theorem CatM i : C i * i`! * i.+1`! = i.*2`!. Proof. have:= Cat_rat i. move/(congr1 (fun x => x * (i.+1)`!%:R * i`!%:R)%R). rewrite (divrK (fact_unit i.+1)) (divrK (fact_unit i)) // -!natrM => /eqP. rewrite Num.Theory.eqr_nat => /eqP <-. by rewrite -[RHS]mulnA [_`! * i`!]mulnC mulnA. Qed. Theorem CatV i : C i = i.*2`! %/ (i`! * i.+1`!). Proof. have:= CatM i; rewrite -mulnA => /(congr1 (fun j => j %/ (i`! * (i.+1)`!))). by rewrite mulnK // muln_gt0 !fact_gt0. Qed. Theorem Cat i : C i = 'C(i.*2, i) %/ i.+1. Proof. case: (ltnP 0 i)=> [Hi|]; last first. by rewrite leqn0 => /eqP ->; rewrite C0 bin0 divn1. rewrite (CatV i) factS [i.+1 * _]mulnC mulnA. by rewrite -{3}(addnK i i) addnn divnMA bin_factd // double_gt0. Qed. End AlgebraicSolution. (** Extraction of the coefficient using Lagrange inversion formula *) Section LagrangeSolution. Local Open Scope ring_scope. Local Open Scope tfps_scope. Lemma one_plusX_2_unit : ((1 + ''X) ^+ 2 : {fps Rat}) \is a GRing.unit. Proof. rewrite unit_fpsE coefs0M coefsD coefs1. by rewrite coef_fpsX addr0 mulr1. Qed. Proposition FC_fixpoint_eq : FC - 1 = lagrfix ((1 + ''X) ^+ 2). Proof. apply: (lagrfix_uniq one_plusX_2_unit). rewrite {1}FC_algebraic_eq -addrA addrC subrK. rewrite rmorphX rmorphD /= comp_fps1 comp_fpsX //; first last. rewrite coefs0_eq0E coefsB coefs1. by rewrite coefs_FPSeries /= C0 subrr. by rewrite addrC subrK. Qed. Theorem CatM_Lagrange i : (i.+1 * (C i))%N = 'C(i.*2, i). Proof. case: i => [|i]; first by rewrite C0 mul1n bin0. apply/eqP; rewrite -(Num.Theory.eqr_nat [numDomainType of Rat]); rewrite natrM. have:= (congr1 (fun s => s``_i.+1) FC_fixpoint_eq). rewrite coefsD coefs_FPSeries. rewrite coefsN coefs1 subr0 /= => ->. rewrite (coefs_lagrfix nat_unit) ?one_plusX_2_unit //. rewrite -exprM mul2n addrC exprD1n coefs_sum. have Hord : (i < (i.+1).*2.+1)%N. by rewrite ltnS doubleS -addnn -!addnS leq_addr. rewrite (bigD1 (Ordinal Hord)) //= -!/(_`_i.+1). rewrite coefsMn coef_fpsXn // eqxx /=. rewrite big1 ?addr0 => [|[j /= Hj]]; first last. rewrite -val_eqE /= => {Hj} /negbTE Hj. by rewrite coefsMn coef_fpsXn eq_sym Hj mul0rn. rewrite ltnS in Hord. rewrite -bin_sub // -{2}addnn -addSnnS addnK. by rewrite mulrA -natrM mul_bin_left -addnn addnK natrM mulrC mulKr. Qed. Local Close Scope ring_scope. Theorem Cat_Lagrange i : C i = 'C(i.*2, i) %/ i.+1. Proof. by have:= congr1 (fun m => m %/ i.+1) (CatM_Lagrange i); rewrite mulnC mulnK. Qed. End LagrangeSolution. (** Extraction of the coefficient using Holonomic differential equation *) Section HolonomicSolution. Local Open Scope ring_scope. Local Open Scope fps_scope. Proposition FC_differential_eq : (1 - ''X *+ 2) * FC + (1 - ''X *+ 4) * ''X * FC^`()%fps = 1. Proof. have X2Fu : (1 - ''X *+ 2 * FC) \is a GRing.unit. rewrite unit_fpsE coefsB coefs1. by rewrite mulrnAl coefsMn coef_fpsXM. rewrite -mulrA. have FalgN : ''X * FC ^+ 2 = FC - 1. by apply/eqP; rewrite eq_sym subr_eq addrC -FC_algebraic_eq. have -> : ''X * FC^`()%fps = (FC - 1)/(1 - ''X *+ 2 * FC). rewrite -[LHS]divr1; apply/eqP. rewrite (eq_divr (''X * _)) ?unitr1 // ?X2Fu // mulr1. have /= := congr1 ((fun s => ''X * s) \o (@deriv_fps _)) FC_algebraic_eq. rewrite derivD_fps deriv_fps1 add0r. rewrite derivM_fps /= deriv_fpsX mul1r derivX_fps /= expr1. rewrite mulrDr FalgN => /eqP; rewrite -(subr_eq _ _ (''X * _)) => /eqP <-. rewrite mulrBr mulr1 -!mulrA; apply/eqP; congr (_ - ''X * _). by rewrite !(mulrnAr, mulrnAl) mulrC mulrA. rewrite mulrA -[X in X + _](mulrK X2Fu) -mulrDl -[RHS]divr1. apply/eqP; rewrite eq_divr ?unitr1 // mulr1 mul1r. rewrite -mulrA [FC * _]mulrC [(1 - _ * FC) * FC]mulrBl -mulrA -expr2. rewrite mul1r mulrnAl FalgN. rewrite !mulrnBl opprB addrA (mulr2n FC) (opprD FC) addrA. rewrite [_ - FC]addrC 2!addrA [-FC + _]addrC subrr add0r. rewrite !mulrBr mulr1 addrA addrC !addrA. rewrite opprB mulrBl mul1r mulr_natr -mulrnA -[(2 * 2)%N]/4. rewrite [''X *+ 4 - 1 + _]addrC addrA subrK addrK. rewrite -addrA -mulNr -mulrDl. rewrite opprD [-1 + _]addrC addrA subrK -opprD mulNr. rewrite -[4]/(2 + 2)%N mulrnDr addrA. by rewrite [_ *- _ + _]addrC subrK. Qed. Local Close Scope ring_scope. Local Close Scope tfps_scope. Proposition Catalan_rec n : n.+2 * C (n.+1) = (4 * n + 2) * C n. Proof. have := congr1 (fun x => (x``_n.+1)%R) FC_differential_eq. rewrite coefs1 coefsD !mulrDl !mul1r !coefsD. rewrite -!mulNrn !(mulrnAl, coefsMn, mulNr, coefsN). rewrite -mulrA !coef_fpsXM /= !coef_deriv_fps !coefs_FPSeries. case: n => [|n] /=; first by rewrite !Csimpl. move: {n} n.+1 => n; move: (C n.+1) (C n) => Cn1 Cn. rewrite !mulNrn addrA [X in (X - _)%R]addrC addrA -mulrSr -!mulrnA. move/eqP; rewrite subr_eq add0r subr_eq -natrD Num.Theory.eqr_nat => /eqP. rewrite mulnC -mulnDr => ->. by rewrite mulnC [n * 4]mulnC. Qed. Theorem CatM_from_rec n : n.+1 * C n = 'C(n.*2, n). Proof. elim: n => [| n IHn] /=; first by rewrite C0 bin0. rewrite Catalan_rec doubleS !binS. have leq_n2 : n <= n.*2 by rewrite -addnn leq_addr. rewrite -[X in _ + _ + X]bin_sub; last exact: (leq_trans leq_n2 (leqnSn _)). rewrite subSn // -{4}addnn addnK binS addnn. rewrite addn2 -[4]/(2 * 2) -mulnA !mul2n -doubleS -doubleMl; congr _.*2. rewrite -IHn -{1}addnn -addnS mulnDl; congr (_ + _). have:= mul_bin_down n.*2 n. rewrite mul_bin_diag -{2}addnn addnK -{}IHn mulnA [n * n.+1]mulnC. rewrite -mulnA ![n.+1 * _]mulnC => /(congr1 (fun m => m %/ n.+1)). by rewrite !mulnK. Qed. Theorem Cat_from_rec i : C i = 'C(i.*2, i) %/ i.+1. Proof. by have:= congr1 (fun m => m %/ i.+1) (CatM_from_rec i); rewrite mulnC mulnK. Qed. End HolonomicSolution. End Catalan.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Copyright (C) 1995-2020 The Octave Project Developers % % See the file COPYRIGHT.md in the top-level directory of this % distribution or <https://octave.org/copyright/>. % % This file is part of Octave. % % Octave is free software: you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, see % <https://www.gnu.org/licenses/>. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % -*- texinfo -*- % @deftypefn {} {} cov (@var{x}) % @deftypefnx {} {} cov (@var{x}, @var{opt}) % @deftypefnx {} {} cov (@var{x}, @var{y}) % @deftypefnx {} {} cov (@var{x}, @var{y}, @var{opt}) % Compute the covariance matrix. % % If each row of @var{x} and @var{y} is an observation, and each column is % a variable, then the @w{(@var{i}, @var{j})-th} entry of % @code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th % variable in @var{x} and the @var{j}-th variable in @var{y}. % @tex % $$ % \sigma_{ij} = {1 \over N-1} \sum_{i=1}^N (x_i - \bar{x})(y_i - \bar{y}) % $$ % where $\bar{x}$ and $\bar{y}$ are the mean values of @var{x} and @var{y}. % @end tex % @ifnottex % % @example % cov (@var{x}) = 1/(N-1) * SUM_i (@var{x}(i) - mean(@var{x})) * (@var{y}(i) - mean(@var{y})) % @end example % % @noindent % where @math{N} is the length of the @var{x} and @var{y} vectors. % % @end ifnottex % % If called with one argument, compute @code{cov (@var{x}, @var{x})}, the % covariance between the columns of @var{x}. % % The argument @var{opt} determines the type of normalization to use. % Valid values are % % @table @asis % @item 0: % normalize with @math{N-1}, provides the best unbiased estimator of the % covariance [default] % % @item 1: % normalize with @math{N}, this provides the second moment around the mean % @end table % % Compatibility Note:: Octave always treats rows of @var{x} and @var{y} % as multivariate random variables. % For two inputs, however, @sc{matlab} treats @var{x} and @var{y} as two % univariate distributions regardless of their shapes, and will calculate % @code{cov ([@var{x}(:), @var{y}(:)])} whenever the number of elements in % @var{x} and @var{y} are equal. This will result in a 2x2 matrix. % Code relying on @sc{matlab}'s definition will need to be changed when % running in Octave. % @seealso{corr} % @end deftypefn function c = cov (x, y, opt) if (nargin < 2) y = []; end if (nargin < 3) opt = 0; end if (nargin < 1 || nargin > 3) error('Usage: c = cov (x, y = [], opt = 0)'); end if (~(isnumeric (x) || islogical (x)) || ~(isnumeric (y) || islogical (y))) error ('cov: X and Y must be numeric matrices or vectors'); end if (ndims (x) ~= 2 || ndims (y) ~= 2) error ('cov: X and Y must be 2-D matrices or vectors'); end if (nargin == 2 && isscalar (y)) opt = y; end if (opt ~= 0 && opt ~= 1) error ('cov: normalization OPT must be 0 or 1'); end % Special case, scalar has zero covariance if (isscalar (x)) if (isa (x, 'single')) c = single (0); else c = 0; end return; end if (isrow (x)) x = x.'; end n = size(x,1); if (nargin == 1 || isscalar (y)) %x = center (x, 1); x = bsxfun(@minus, x, mean (x, 1)); c = x' * x / (n - 1 + opt); else if (isrow (y)) y = y.'; end if (size(y,1) ~= n) error ('cov: X and Y must have the same number of observations'); end %x = center (x, 1); %y = center (y, 1); x = bsxfun(@minus, x, mean (x, 1)); y = bsxfun(@minus, y, mean (y, 1)); c = x' * y / (n - 1 + opt); end end
import data.real.basic import data.int.parity /- In this file, we learn how to handle the βˆƒ quantifier. In order to prove `βˆƒ x, P x`, we give some xβ‚€ using tactic `use xβ‚€` and then prove `P xβ‚€`. This xβ‚€ can be an object from the local context or a more complicated expression. -/ example : βˆƒ n : β„•, 8 = 2*n := begin use 4, refl, -- this is the tactic analogue of the rfl proof term end /- In order to use `h : βˆƒ x, P x`, we use the `cases` tactic to fix one xβ‚€ that works. Again h can come straight from the local context or can be a more complicated expression. -/ example (n : β„•) (h : βˆƒ k : β„•, n = k + 1) : n > 0 := begin -- Let's fix kβ‚€ such that n = kβ‚€ + 1. cases h with kβ‚€ hkβ‚€, -- It now suffices to prove kβ‚€ + 1 > 0. rw hkβ‚€, -- and we have a lemma about this exact nat.succ_pos kβ‚€, end /- The next exercises use divisibility in β„€ (beware the ∣ symbol which is not ASCII). By definition, a ∣ b ↔ βˆƒ k, b = a*k, so you can prove a ∣ b using the `use` tactic. -/ -- Until the end of this file, a, b and c will denote integers, unless -- explicitly stated otherwise variables (a b c : β„€) -- 0029 example (h₁ : a ∣ b) (hβ‚‚ : b ∣ c) : a ∣ c := begin cases h₁ with k1 hk1, cases hβ‚‚ with k2 hk2, have h: c = a * (k1 * k2), by {calc c = b * k2 : by rw hk2 ... = (a * k1) * k2 : by rw hk1 ... = a * (k1 * k2) : by rw mul_assoc}, use k1*k2, exact h, end /- A very common pattern is to have an assumption or lemma asserting h : βˆƒ x, y = ... and this is used through the combo: cases h with x hx, rw hx at ... The tactic `rcases` allows us to do recursive `cases`, as indicated by its name, and also simplifies the above combo when the name hx is replaced by the special name `rfl`, as in the following example. It uses the anonymous constructor angle brackets syntax. -/ example (h1 : a ∣ b) (h2 : a ∣ c) : a ∣ b+c := begin rcases h1 with ⟨k, rfl⟩, rcases h2 with ⟨l, rfl⟩, use k+l, ring, end /- You can use the same `rfl` trick with the `rintros` tactic. -/ example : a ∣ b β†’ a ∣ c β†’ a ∣ b+c := begin rintros ⟨k, rfl⟩ ⟨l, rfl⟩, use k+l, ring, end -- 0030 example : 0 ∣ a ↔ a = 0 := begin split, {rintros ⟨k, refl⟩, linarith }, {intros h, use 0, -- 0 = 0 * 0, so 0 | 0 linarith} end /- We can now start combining quantifiers, using the definition surjective (f : X β†’ Y) := βˆ€ y, βˆƒ x, f x = y -/ open function -- In the remaining of this file, f and g will denote functions from -- ℝ to ℝ. variables (f g : ℝ β†’ ℝ) -- 0031 example (h : surjective (g ∘ f)) : surjective g := begin intros x, rcases h x with ⟨t,rfl⟩, exact ⟨f t, rfl⟩ end /- The above exercise can be done in three lines. Try to do the next exercise in four lines. -/ -- 0032 example (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) := begin intros x, rcases hg x with ⟨t, rfl⟩, rcases hf t with ⟨tt, rfl⟩, exact ⟨tt, rfl⟩ end
import algebra.group_power tactic.norm_num algebra.big_operators theorem Q3a (n : β„•) : βˆƒ k, (n+1)+(n+2)+(n+3)+(n+4) = 4*k+2 := sorry lemma of_nat_pow : βˆ€ a b: β„•, int.of_nat(a^b)=(int.of_nat a)^b := begin intros a b, induction b with k Hk, unfold monoid.pow, simp [int.of_nat_one], unfold monoid.pow nat.pow, -- pow_nat nat.pow has_pow_nat.pow_nat monoid.pow, --show int.of_nat (a^k*a) = (int.of_nat a) * (int.of_nat a)^k, rw [int.of_nat_mul,mul_comm,Hk,mul_comm], end theorem Q3helpful_lemma : βˆ€ (e : β„•), 11^e β‰₯ 3^e := begin intro e, induction e with d Hd, exact dec_trivial, exact calc 11^(nat.succ d) = 11*11^d : rfl ... β‰₯ 3*11^d : nat.mul_le_mul_right (11^d) (dec_trivial) ... β‰₯ 3*3^d : nat.mul_le_mul_left 3 Hd ... = 3^(nat.succ d) : rfl end theorem Q3helpful_lemma2 : βˆ€ (e : β„• ), (((11^e-3^e):β„•):β„€) = (11:β„€)^e-(3:β„€)^e := begin intro e, show int.of_nat (11^e - 3^e) = (11:β„€)^e - (3:β„€)^e, rw [int.of_nat_sub (Q3helpful_lemma e)], rw [of_nat_pow,of_nat_pow], refl, end theorem Q3b (n : β„•) : 8 ∣ 11^n - 3^n := sorry theorem Q3ca (n : β„•) : βˆƒ k, (n+1)+(n+2)+(n+3)+(n+4) = 4*k+2 := sorry def Q3sum (d : β„•) (a b : β„€) := finset.sum (finset.range (d+1)) (Ξ» n, a^n*b^(d-n)) --finset.sum_image : -- βˆ€ {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} {f : Ξ± β†’ Ξ²} [_inst_1 : add_comm_monoid Ξ²] -- [_inst_2 : decidable_eq Ξ±] [_inst_3 : decidable_eq Ξ³] {s : finset Ξ³} {g : Ξ³ β†’ Ξ±}, -- (βˆ€ (x : Ξ³), x ∈ s β†’ βˆ€ (y : Ξ³), y ∈ s β†’ g x = g y β†’ x = y) β†’ -- finset.sum (finset.image g s) f = finset.sum s (Ξ» (x : Ξ³), f (g x)) lemma lt_of_in_finset {x y: β„•} : x ∈ finset.range y β†’ x < y := by simp --set_option pp.notation false lemma H8 (d : β„•) : list.map (Ξ» (i : β„•), d - i) (list.range (d + 1)) = list.reverse (list.range (d + 1)) := begin admit, -- and ask Mario end lemma H7 : βˆ€ d : β„•, (finset.range (d+1)).image (Ξ» i,d-i) = finset.range (d+1) := begin -- statement about finsets intro d, unfold finset.image, unfold finset.range, show multiset.to_finset (multiset.map (Ξ» (i : β„•), d - i) (multiset.range (d + 1))) = {val := multiset.range (d + 1), nodup := _}, unfold multiset.to_finset, apply finset.eq_of_veq, show multiset.erase_dup (multiset.map (Ξ» (i : β„•), d - i) (multiset.range (d + 1))) = multiset.range (d + 1), -- now a statement about multisets have this2 := multiset.nodup_range (d+1), suffices : multiset.erase_dup (multiset.map (Ξ» (i : β„•), d - i) (multiset.range (d + 1))) = multiset.erase_dup (multiset.range (d + 1)), rw [this], exact multiset.erase_dup_eq_self.2 this2, apply congr_arg, clear this2, show multiset.map (Ξ» (i : β„•), d - i) (multiset.range (d + 1)) = ↑(list.range (d + 1)), rw ←multiset.coe_reverse, unfold multiset.range, rw multiset.coe_map, apply congr_arg, -- now a statement about lists exact H8 d, end lemma H0 (d : β„•) (a b : β„€) : Q3sum d a b = Q3sum d b a := begin unfold Q3sum, have : (finset.range (d+1)).image (Ξ» i,d-i) = finset.range (d+1), exact H7 d, /- unfold finset.range, unfold multiset.range, rw ←multiset.coe_reverse, -/ rw ←this, -- aargh, rewrites both! have H53 : βˆ€ (x : β„•), x ∈ finset.range(d+1) β†’ βˆ€ (y : β„•), y ∈ finset.range (d+1) β†’ d-x = d-y β†’ x=y, introv Hx Hy Hxy, have : (d-x)+x=d, exact nat.sub_add_cancel (nat.le_of_lt_succ (lt_of_in_finset Hx)), rw Hxy at this, rw ←nat.sub_add_comm (nat.le_of_lt_succ (lt_of_in_finset Hy)) at this, have this2 : (d+x-y)+y=d+x, exact nat.sub_add_cancel (le_trans (nat.le_of_lt_succ (lt_of_in_finset Hy)) (nat.le_add_right _ _)), rw this at this2, exact eq.symm (nat.add_left_cancel this2), rw [@finset.sum_image β„• β„€ β„• (Ξ» (n : β„•), a ^ n * b ^ (d - n)) _ _ _ (finset.range (d+1)) (Ξ» i : β„•, d-i) H53], rw [this], apply finset.sum_congr, introv H, have := lt_of_in_finset H, show a ^ (d - x) * b ^ (d - (d - x)) = b ^ x * a ^ (d - x), rw [nat.sub_sub_self (nat.le_of_lt_succ this)], apply mul_comm, end lemma H5 (e : β„•) : finset.range (nat.succ e) = insert e (finset.range e) := begin exact finset.range_succ, end lemma H1 (d : β„•) (aa b : β„€) : b * Q3sum d aa b = Q3sum (d+1) aa b - aa^(d+1) := begin unfold Q3sum, rw finset.mul_sum, change d+1+1 with nat.succ(d+1), rw (@finset.range_succ (d+1)), rw finset.sum_insert, tactic.swap, intro H, apply lt_irrefl (d+1), exact lt_of_in_finset H, rw [nat.sub_self (d+1)], have : βˆ€ x : β„•, x<(d+1) β†’ b*(aa^x*b^(d-x))= aa^x*b^(d+1-x), intros x Hx, rw [mul_comm], have : d+1-x = (d-x)+1, rw [add_comm,nat.add_sub_assoc (nat.le_of_lt_succ Hx),add_comm], rw [this], rw [pow_succ],simp, rw [pow_zero,mul_one], rw [add_comm (aa^(d+1)),add_sub_cancel], apply finset.sum_congr, intros, apply this x, exact lt_of_in_finset H, end lemma H3 (d : β„•) : 11 * Q3sum d 3 11 = Q3sum (d+1) 3 11 - 3^(d+1) := H1 d 3 11 lemma H2 (d : β„•) : 3 * Q3sum d 3 11 = Q3sum (d+1) 3 11 - 11^(d+1) := begin rw [H0], rw H1 d 11 3, rw [H0] end lemma Q3cb_helper : βˆ€ d : β„•, 8*Q3sum d 3 11 = 11^(d+1)-3^(d+1) := begin intro d, change (8:β„€) with (11:β„€)-3, rw [sub_mul,H3,H2], simp, end theorem Q3cbint (n : β„•) : 8 ∣ (11:β„€)^n - 3^n := sorry theorem Q3cb (n : β„•) : 8 ∣ 11^n - 3^n := sorry
locate constant a at "missing-file.fpp" constant b = a
Require Import CoqlibC Maps. Require Import ASTC Integers Floats Values MemoryC EventsC Globalenvs Smallstep. Require Import Locations Stacklayout Conventions. (** newly added **) Require Import Mach Simulation ValuesC. Require Export Asm. Require Import Skeleton ModSem Mod sflib. Require Import LocationsC AsmregsC StoreArguments. Require Import JunkBlock. Set Implicit Arguments. Local Obligation Tactic := ii; ss; des; inv_all_once; des; ss; clarify; eauto with congruence. Definition get_mem (st: state): mem := match st with | State _ m0 => m0 end. Definition st_rs (st0: state): regset := match st0 with | State rs _ => rs end. Definition st_m (st0: state): mem := match st0 with | State _ m => m end. Definition store_arguments (m0: mem) (rs: regset) (vs: list val) (sg: signature) (m2: mem) : Prop := (<<STORE: StoreArguments.store_arguments m0 (to_mregset rs) vs sg m2>>) /\ (<<RSRSP: rs RSP = Vptr m0.(Mem.nextblock) Ptrofs.zero>>). Definition external_state F V (ge: Genv.t F V) (v : val) : bool := match v with | Vptr blk ofs => match (Genv.find_funct ge (Vptr blk Ptrofs.zero)) with | None => true | _ => false end | _ => true end. Section MODSEM. Variable skenv_link: SkEnv.t. Variable p: program. Let skenv: SkEnv.t := (SkEnv.project skenv_link) (Sk.of_program fn_sig p). Let ge: genv := (SkEnv.revive skenv) p. Record state := mkstate { init_rs: regset; st:> Asm.state; }. Inductive step (se: Senv.t) (ge: genv) (st0: state) (tr: trace) (st1: state): Prop := | step_intro (STEP: Asm.step se ge st0.(st) tr st1.(st)) (INITRS: st0.(init_rs) = st1.(init_rs)). Inductive at_external: state -> Args.t -> Prop := | at_external_cstyle fptr rs m0 m1 sg vs blk1 ofs init_rs (FPTR: rs # PC = fptr) (EXTERNAL: Genv.find_funct ge fptr = None) (SIG: exists skd, (Genv.find_funct skenv_link) fptr = Some skd /\ Sk.get_csig skd = Some sg) (RAPTR: <<TPTR: Val.has_type (rs RA) Tptr>> /\ <<RADEF: rs RA <> Vundef>>) (VALS: Asm.extcall_arguments rs m0 sg vs) (RSP: rs RSP = Vptr blk1 ofs) (ARGSRANGE: Ptrofs.unsigned ofs + 4 * size_arguments sg <= Ptrofs.max_unsigned) (ALIGN: forall chunk (CHUNK: size_chunk chunk <= 4 * (size_arguments sg)), (align_chunk chunk | (Ptrofs.unsigned ofs))) (FREE: Mem.free m0 blk1 (Ptrofs.unsigned ofs) (Ptrofs.unsigned (ofs) + 4 * (size_arguments sg)) = Some m1) : at_external (mkstate init_rs (State rs m0)) (Args.Cstyle fptr vs m1) | at_external_asmstyle fptr rs m0 init_rs (FPTR: rs # PC = fptr) (EXTERNAL: Genv.find_funct ge fptr = None) (SIG: exists skd, (Genv.find_funct skenv_link) fptr = Some skd /\ Sk.get_csig skd = None) (RAPTR: <<TPTR: Val.has_type (rs RA) Tptr>> /\ <<RADEF: rs RA <> Vundef>>) : at_external (mkstate init_rs (State rs m0)) (Args.Asmstyle rs m0) . Inductive initial_frame (args: Args.t): state -> Prop := | initial_frame_cstyle fd m0 rs sg targs n m1 fptr_arg vs_arg m_arg (SIG: sg = fd.(fn_sig)) (CSTYLE0: sg.(sig_cstyle) = true) (CSTYLE: args = Args.Cstyle fptr_arg vs_arg m_arg) (FINDF: Genv.find_funct ge fptr_arg = Some (Internal fd)) (JUNK: assign_junk_blocks m0 n = m1) (RAPTR: <<TPTR: Val.has_type (rs RA) Tptr>> /\ <<RADEF: rs RA <> Vundef>>) (RANOTFPTR: forall blk ofs (RAVAL: rs RA = Vptr blk ofs), ~ Plt blk (Genv.genv_next skenv)) (RSPC: rs # PC = fptr_arg) (TYP: typecheck vs_arg sg targs) (STORE: store_arguments m_arg rs targs sg m0) (PTRFREE: forall pr (PTR: ~ is_junk_value m0 m1 (rs pr)), (<<INARG: exists mr, (<<MR: to_mreg pr = Some mr>>) /\ (<<ARG: In (R mr) (regs_of_rpairs (loc_arguments sg))>>)>>) \/ (<<INPC: pr = PC>>) \/ (<<INRSP: pr = RSP>>)): initial_frame args (mkstate rs (State rs m1)) | initial_frame_asmstyle fd ra n m1 rs_arg rs m_arg (SIG: fd.(fn_sig).(sig_cstyle) = false) (ASMSTYLE: args = Args.Asmstyle rs_arg m_arg) (FINDF: Genv.find_funct ge (rs_arg # PC) = Some (Internal fd)) (JUNK: assign_junk_blocks m_arg n = m1) (RAPTR: <<TPTR: Val.has_type ra Tptr>> /\ <<RADEF: ra <> Vundef>>) (RANOTFPTR: forall blk ofs (RAVAL: ra = Vptr blk ofs), ~ Plt blk (Genv.genv_next skenv)) (RAJUNK: is_junk_value m_arg m1 ra) (RS: rs = rs_arg # RA <- ra) : initial_frame args (mkstate rs (State rs m1)) . Inductive final_frame: state -> Retv.t -> Prop := | final_frame_cstyle (init_rs rs: regset) m0 m1 blk sg mr (INITSIG: exists fd, (Genv.find_funct ge) (init_rs # PC) = Some (Internal fd) /\ fd.(fn_sig) = sg /\ sg.(sig_cstyle) = true) (EXTERNAL: external_state ge (rs # PC)) (RSRA: rs # PC = init_rs # RA) (RANOTFPTR: Genv.find_funct skenv_link (init_rs RA) = None) (CALLEESAVE: forall mr, Conventions1.is_callee_save mr -> Val.lessdef (init_rs (to_preg mr)) (rs (to_preg mr))) (INITRSP: init_rs # RSP = Vptr blk Ptrofs.zero) (RSRSP: rs # RSP = init_rs # RSP) (FREE: Mem.free m0 blk 0 (4 * size_arguments sg) = Some m1) (RETV: loc_result sg = One mr) : final_frame (mkstate init_rs (State rs m0)) (Retv.Cstyle (rs (to_preg mr)) m1) | final_frame_asmstyle (init_rs rs: regset) m0 (INITSIG: exists fd, (Genv.find_funct ge) (init_rs # PC) = Some (Internal fd) /\ fd.(fn_sig).(sig_cstyle) = false) (EXTERNAL: external_state ge (rs # PC)) (RSRA: rs # PC = init_rs # RA) (RANOTFPTR: Genv.find_funct skenv_link (init_rs RA) = None) : final_frame (mkstate init_rs (State rs m0)) (Retv.Asmstyle rs m0) . Inductive after_external: state -> Retv.t -> state -> Prop := | after_external_cstyle init_rs rs0 m0 rs1 m1 retv retv_v retv_m sg blk ofs (CSTYLE: retv = (Retv.Cstyle retv_v retv_m)) (SIG: exists skd, (Genv.find_funct skenv_link) (rs0 # PC) = Some skd /\ Sk.get_csig skd = Some sg) (RS: rs1 = (set_pair (loc_external_result sg) retv_v (regset_after_external rs0)) #PC <- (rs0 RA)) (RSRSP: rs0 RSP = Vptr blk ofs) (UNFREE: Mem_unfree retv_m blk (Ptrofs.unsigned ofs) (Ptrofs.unsigned (ofs) + 4 * (size_arguments sg)) = Some m1): after_external (mkstate init_rs (State rs0 m0)) retv (mkstate init_rs (State rs1 m1)) | after_external_asmstyle init_rs rs0 m0 rs1 retv retv_rs retv_m (ASMSTYLE: retv = (Retv.Asmstyle retv_rs retv_m)) (SIG: exists skd, (Genv.find_funct skenv_link) (rs0 # PC) = Some skd /\ Sk.get_csig skd = None) (RS: rs1 = retv_rs # PC <- (rs0 # RA)) : after_external (mkstate init_rs (State rs0 m0)) retv (mkstate init_rs (State rs1 retv_m)). Program Definition modsem: ModSem.t := {| ModSem.step := step; ModSem.at_external := at_external; ModSem.initial_frame := initial_frame; ModSem.final_frame := final_frame; ModSem.after_external := after_external; ModSem.globalenv := ge; ModSem.skenv := skenv; ModSem.skenv_link := skenv_link; |}. Next Obligation. rewrite RSP in *. clarify. f_equal. eapply Asm.extcall_arguments_determ; eauto. Qed. Next Obligation. all: inv STEP; rewrite H2 in *; ss; des_ifs. Qed. Next Obligation. all: inv EXTERNAL; unfold external_state in *; des_ifs; inv STEP; ss; des_ifs; rewrite Heq in *; clarify. Qed. Lemma modsem_receptive: forall st, receptive_at modsem st. Proof. econs; eauto. - ii; ss. inv H. destruct st0; ss. destruct s1; ss. clarify. inv STEP; try (exploit external_call_receptive; eauto; check_safe; intro T; des); try by (inv_match_traces; (eexists (mkstate _ _); econs; [econs|]; eauto; ss)). - ii. inv H. inv STEP; try (exploit external_call_trace_length; eauto; check_safe; intro T; des); ss; try xomega. Qed. Lemma modsem_determinate: forall st, determinate_at modsem st. Proof. econs; eauto. - ii; ss. inv H; inv H0. destruct st0; ss. destruct s1; ss. destruct s2; ss. clarify. inv STEP; inv STEP0; eq_closure_tac; clarify_meq; try (determ_tac extcall_arguments_determ; check_safe); try (determ_tac eval_builtin_args_determ; check_safe); try (determ_tac external_call_determ; check_safe); esplits; eauto; try (econs; eauto); ii; eq_closure_tac; clarify_meq. - ii. inv H. inv STEP; try (exploit external_call_trace_length; eauto; check_safe; intro T; des); ss; try xomega. Qed. End MODSEM. Program Definition module (p: program): Mod.t := {| Mod.data := p; Mod.get_sk := Sk.of_program fn_sig; Mod.get_modsem := modsem; |}.
PAUSE 13 PAUSE 333 END PROGRAM
function [ a, ipvt, info ] = zgefa ( a, lda, n ) %*****************************************************************************80 % %% ZGEFA factors a complex matrix by Gaussian elimination. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 29 April 2007 % % Author: % % MATLAB version by John Burkardt % % Reference: % % Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart, % LINPACK User's Guide, % SIAM, (Society for Industrial and Applied Mathematics), % 3600 University City Science Center, % Philadelphia, PA, 19104-2688. % % Parameters: % % Input, complex A(LDA,N), the matrix to be factored. % % Input, integer LDA, the leading dimension of A. % % Input, integer N, the order of the matrix. % % Output, complex A(LDA,N); an upper triangular matrix and the multipliers % which were used to obtain it. The factorization can be written A = L*U % where L is a product of permutation and unit lower triangular matrices % and U is upper triangular. % % Output, integer IPVT(N), the pivot indices. % % Output, integer INFO, % 0, normal value. % K, if U(K,K) == 0.0. This is not an error condition for this % subroutine, but it does indicate that ZGESL or ZGEDI will divide by zero % if called. Use RCOND in ZGECO for a reliable indication of singularity. % % % Gaussian elimination with partial pivoting. % info = 0; for k = 1 : n - 1 % % Find L = pivot index. % l = izamax ( n-k+1, a(k:n,k), 1 ) + k - 1; ipvt(k) = l; % % Zero pivot implies this column already triangularized. % if ( zabs1 ( a(l,k) ) == 0.0 ) info = k; continue; end % % Interchange if necessary. % if ( l ~= k ) temp = a(l,k); a(l,k) = a(k,k); a(k,k) = temp; end % % Compute multipliers % a(k+1:n,k) = - a(k+1:n,k) / a(k,k); % % Row elimination with column indexing % for j = k+1 : n t = a(l,j); if ( l ~= k ) a(l,j) = a(k,j); a(k,j) = t; end a(k+1:n,j) = a(k+1:n,j) + t * a(k+1:n,k); end end ipvt(n) = n; if ( zabs1 ( a(n,n) ) == 0.0 ) info = n; end return end
const IniType = Dict{String,Dict{String,Any}} export IniType function parseini(fname::String)::IniType initxt = IniType(); fid = open(fname) blockname = "default" seekstart(fid) lines = eachline(fid) lastkey = "" for line in lines # skip comments and newlines m = match(r"([^#]*)",line); line = strip(chomp(m.captures[1])); if isempty(line) continue end # parse blockname m = match(r"^\s*\[\s*([^\]]+)\s*\]$", line) if (m != nothing) blockname = m.captures[1] continue end # parse key/value m = match(r"^\s*([^=]*\w)\s*=\s*(.*)\s*$", line) if (m != nothing) #Found a key lastkey = m.captures[1] if haskey(initxt,blockname) initxt[blockname][lastkey] = m.captures[2]; else initxt[blockname] = Dict(lastkey => m.captures[2]); end else #Not a key and not a comment append to last known block and key initxt[blockname][lastkey] = string(initxt[blockname][lastkey],line) end end close(fid); #eval loop mblock=[];mkey=[] try foreach(keys(initxt)) do block mblock = block foreach(keys(initxt[block])) do key mkey = key initxt[block][key] = eval(parse(initxt[block][key])) end end catch e error("Error encountered parsing [$(mblock)][$mkey] with\n val: \n $(initxt[mblock][mkey])") end initxt end export parseini writeln(fid,line) = begin isempty(line) && (line = "\n") line[end] != '\n' && (line = string(line,"\n")) write(fid,line) end function saveini{T<:Any}(fname::String,D::Dict{String,Dict{String,T}}) fid = open(fname,"w+") do fid foreach(keys(D)) do block block = strip(block) writeln(fid,"\n[$block]") foreach(keys(D[block])) do key key = strip(key) writeln(fid,"$key = $(print_var(D[block][key]))") end end end nothing end export saveini function setvarini(fname::String,section::String,varname::String,var) section = strip(section) varname= strip(varname) lines = try open(fid->collect(eachline(fid)),fname) catch info("File not found: creating new file $fname") open(fname,"w") do fid writeln(fid,"\n[$section]") writeln(fid,"$varname = $(print_var(var))") end return end S = parseini_structure(lines) if !(section in keys(S)) info("Section [$section] not found in $fname creating new ") open(fname,"w") do fid writeln(fid,"\n[$section]") writeln(fid,"$varname = $(print_var(var))") foreach(line->writeln(fid,line),lines) end return end if varname in keys(S[section].children) info("Variable found: replacing $varname = ") insert_line = S[section][varname].start_line-1 restart_line = S[section][varname].end_line+1 else info("Variable not found: creating $varname = ") insert_line = S[section].start_line restart_line = S[section].start_line+1 end open(fname,"w") do fid for i=1:insert_line writeln(fid,lines[i]); end writeln(fid,"$varname = $(print_var(var))") for i=restart_line:length(lines) writeln(fid,lines[i]); end end end export setvarini print_var(S::String) = string("\"",replace(S,"\\","\\\\"),"\"") print_var(S::Any) = begin res = sprint(print,S) for typ in (:Any,:Int32,:Int64,:Float64,:Float32) res = replace(res,"$(typ)[","[") res = replace(res,",$(typ)[",",[") end res = replace(res,"],[","],\n\t\t[") res end print_var{T <: Real}(M::Matrix{T}) = begin M = Matrix{Float64}(M) res = sprint(print,M) res = replace(res,";",";\n\t\t") end using StaticArrays print_var{N1,N2,T <: Real}(M::SMatrix{N1,N2,T}) = begin M = Matrix{Float64}(M) res = sprint(print,M) res = replace(res,";",";\n\t\t") end print_var{T <: Real}(VV::Vector{Vector{T}}) = begin res = sprint(print,VV) res = replace(res,"Array{$T,1}","") res = replace(res,"],[","],\n\t\t[") res = replace(res,"[[","[\n\t\t[") end mutable struct iniNodeInfo typ::Symbol start_line::Integer end_line::Integer children iniNodeInfo(typ,sl,el) = new(typ,sl,el,Dict{String,iniNodeInfo}()) end import Base: getindex,setindex! getindex(ini::iniNodeInfo,a) = ini.children[a] setindex!(ini::iniNodeInfo,val,key) = setindex!(ini.children,val,key) function parseini_structure(fname::String) open(fname) do fid parseini_structure(collect(eachline(fid))) end end function parseini_structure(lines::Vector{String}) S = Dict{String,iniNodeInfo}(); blockname = "default" S[blockname] = iniNodeInfo(:block,1,0) lastkey = "" for idx=1:length(lines) line = lines[idx] # skip comments and newlines m = match(r"([^#]*)",line); line = strip(chomp(m.captures[1])); if isempty(line) continue end # parse blockname m = match(r"^\s*\[\s*([^\]]+)\s*\]$", line) if (m != nothing) blockname = m.captures[1] S[blockname] = iniNodeInfo(:block,idx,idx) continue end S[blockname].end_line += 1 # parse key/value m = match(r"^\s*([^=]*\w)\s*=\s*(.*)\s*$", line) if (m != nothing) #Found a key lastkey = m.captures[1] S[blockname][lastkey] = iniNodeInfo(:key,idx,idx) else #Not a key and not a comment append to last known block and key S[blockname][lastkey].end_line += 1 end end S end nothing
State Before: Ξ± : Type ?u.7362 α₁ : Type u_1 Ξ±β‚‚ : Type u_2 Ξ² : Ξ± β†’ Type ?u.7373 β₁ : α₁ β†’ Type u_3 Ξ²β‚‚ : Ξ±β‚‚ β†’ Type u_4 f₁ : α₁ β†’ Ξ±β‚‚ fβ‚‚ : (a : α₁) β†’ β₁ a β†’ Ξ²β‚‚ (f₁ a) h₁ : Surjective f₁ hβ‚‚ : βˆ€ (a : α₁), Surjective (fβ‚‚ a) ⊒ Surjective (Sigma.map f₁ fβ‚‚) State After: Ξ± : Type ?u.7362 α₁ : Type u_1 Ξ±β‚‚ : Type u_2 Ξ² : Ξ± β†’ Type ?u.7373 β₁ : α₁ β†’ Type u_3 Ξ²β‚‚ : Ξ±β‚‚ β†’ Type u_4 f₁ : α₁ β†’ Ξ±β‚‚ fβ‚‚ : (a : α₁) β†’ β₁ a β†’ Ξ²β‚‚ (f₁ a) h₁ : Surjective f₁ hβ‚‚ : βˆ€ (a : α₁), Surjective (fβ‚‚ a) ⊒ βˆ€ (x : α₁) (b : Ξ²β‚‚ (f₁ x)), βˆƒ a, Sigma.map f₁ fβ‚‚ a = { fst := f₁ x, snd := b } Tactic: simp only [Function.Surjective, Sigma.forall, h₁.forall] State Before: Ξ± : Type ?u.7362 α₁ : Type u_1 Ξ±β‚‚ : Type u_2 Ξ² : Ξ± β†’ Type ?u.7373 β₁ : α₁ β†’ Type u_3 Ξ²β‚‚ : Ξ±β‚‚ β†’ Type u_4 f₁ : α₁ β†’ Ξ±β‚‚ fβ‚‚ : (a : α₁) β†’ β₁ a β†’ Ξ²β‚‚ (f₁ a) h₁ : Surjective f₁ hβ‚‚ : βˆ€ (a : α₁), Surjective (fβ‚‚ a) ⊒ βˆ€ (x : α₁) (b : Ξ²β‚‚ (f₁ x)), βˆƒ a, Sigma.map f₁ fβ‚‚ a = { fst := f₁ x, snd := b } State After: no goals Tactic: exact fun i ↦ (hβ‚‚ _).forall.2 fun x ↦ ⟨⟨i, x⟩, rfl⟩
import Mathlib.Data.Fintype.Card import Mathlib.Data.Fintype.Sum import Mathlib.Data.Fintype.Sigma import Mathlib.Data.Fintype.BigOperators import Lean4bits.defs import Mathlib.Tactic.Zify import Mathlib.Tactic.Ring open Sum variable {Ξ± Ξ² Ξ±' Ξ²' : Type} {Ξ³ : Ξ² β†’ Type} def propagateAux (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) : β„• β†’ (Ξ± β†’ Bool) Γ— Bool | 0 => next_bit init_carry (fun i => x i 0) | n+1 => next_bit (propagateAux init_carry next_bit x n).1 (fun i => x i (n+1)) def propagate (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) (i : β„•) : Bool := (propagateAux init_carry next_bit x i).2 @[simp] def propagateCarry (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (x : Ξ² β†’ β„• β†’ Bool) : β„• β†’ (Ξ± β†’ Bool) | 0 => next_bit init_carry (fun i => x i 0) | n+1 => next_bit (propagateCarry init_carry next_bit x n) (fun i => x i (n+1)) @[simp] def propagateCarry2 (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (x : Ξ² β†’ β„• β†’ Bool) : β„• β†’ (Ξ± β†’ Bool) | 0 => init_carry | n+1 => next_bit (propagateCarry2 init_carry next_bit x n) (fun i => x i n) lemma propagateCarry2_succ (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (x : Ξ² β†’ β„• β†’ Bool) : βˆ€ (n : β„•), propagateCarry2 init_carry next_bit x (n+1) = propagateCarry init_carry next_bit x n | 0 => rfl | n+1 => by rw [propagateCarry2, propagateCarry2_succ _ _ _ n, propagateCarry] @[simp] lemma propagateAux_fst_eq_carry (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) : βˆ€ n : β„•, (propagateAux init_carry next_bit x n).1 = propagateCarry init_carry (fun c b => (next_bit c b).1) x n | 0 => rfl | n+1 => by rw [propagateAux, propagateCarry, propagateAux_fst_eq_carry _ _ _ n] @[simp] lemma propagate_zero (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) : propagate init_carry next_bit x 0 = (next_bit init_carry (fun i => x i 0)).2 := rfl lemma propagate_succ (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) (i : β„•) : propagate init_carry next_bit x (i+1) = (next_bit (propagateCarry init_carry (fun c b => (next_bit c b).1) x i) (Ξ» j => x j (i+1))).2 := by rw [← propagateAux_fst_eq_carry]; rfl lemma propagate_succ2 (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ² β†’ β„• β†’ Bool) (i : β„•) : propagate init_carry next_bit x (i+1) = (next_bit (propagateCarry2 init_carry (Ξ» c b => (next_bit c b).1) x (i+1)) (Ξ» j => x j (i+1))).2 := by rw [propagateCarry2_succ, ← propagateAux_fst_eq_carry]; rfl lemma propagateCarry_propagate {Ξ΄ : Ξ² β†’ Type} {Ξ²' : Type} (f : βˆ€ a, Ξ΄ a β†’ Ξ²') : βˆ€ (n : β„•) (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (init_carry_x : βˆ€ a, Ξ³ a β†’ Bool) (next_bit_x : βˆ€ a (_carry : Ξ³ a β†’ Bool) (_bits : Ξ΄ a β†’ Bool), (Ξ³ a β†’ Bool) Γ— Bool) (x : Ξ²' β†’ β„• β†’ Bool), propagateCarry init_carry next_bit (Ξ» a => propagate (init_carry_x a) (next_bit_x a) (Ξ» d => x (f a d))) n = propagateCarry (Ξ» a : Ξ± βŠ• (Ξ£ a, Ξ³ a) => Sum.elim init_carry (Ξ» b : Ξ£ a, Ξ³ a => init_carry_x b.1 b.2) a) (Ξ» (carry : (Ξ± βŠ• (Ξ£ a, Ξ³ a)) β†’ Bool) (bits : Ξ²' β†’ Bool) => -- first compute (propagate (init_carry_x a) (next_bit_x a) (x a) n) let f : βˆ€ (a : Ξ²), (Ξ³ a β†’ Bool) Γ— Bool := Ξ» a => next_bit_x a (Ξ» d => carry (inr ⟨a, d⟩)) (Ξ» d => bits (f a d)) let g : (Ξ± β†’ Bool) := (next_bit (carry ∘ inl) (Ξ» a => (f a).2)) Sum.elim g (Ξ» x => (f x.1).1 x.2)) x n ∘ inl | 0, init_carry, next_bit, init_carry_x, next_bit_x, x => rfl | n+1, init_carry, next_bit, init_carry_x, next_bit_x, x => by have := propagateCarry_propagate f n simp only [propagateCarry, propagate_succ, elim_inl, Nat.add] at * conv_lhs => simp only [this] clear this dsimp congr ext a dsimp congr ext b dsimp [propagateCarry, propagate_succ, elim_inl, Nat.add] congr dsimp induction' n with n ih . simp . simp [ih] lemma propagate_propagate {Ξ΄ : Ξ² β†’ Type} {Ξ²' : Type} (f : βˆ€ a, Ξ΄ a β†’ Ξ²') : βˆ€ (n : β„•) (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (init_carry_x : βˆ€ a, Ξ³ a β†’ Bool) (next_bit_x : βˆ€ a (_carry : Ξ³ a β†’ Bool) (_bits : Ξ΄ a β†’ Bool), (Ξ³ a β†’ Bool) Γ— Bool) (x : Ξ²' β†’ β„• β†’ Bool), propagate init_carry next_bit (Ξ» a => propagate (init_carry_x a) (next_bit_x a) (Ξ» d => x (f a d))) n = propagate (Ξ» a : Ξ± βŠ• (Ξ£ a, Ξ³ a) => Sum.elim init_carry (Ξ» b : Ξ£ a, Ξ³ a => init_carry_x b.1 b.2) a) (Ξ» (carry : (Ξ± βŠ• (Ξ£ a, Ξ³ a)) β†’ Bool) (bits : Ξ²' β†’ Bool) => -- first compute (propagate (init_carry_x a) (next_bit_x a) (x a) n) let f : βˆ€ (a : Ξ²), (Ξ³ a β†’ Bool) Γ— Bool := Ξ» a => next_bit_x a (Ξ» d => carry (inr ⟨a, d⟩)) (Ξ» d => bits (f a d)) let g : (Ξ± β†’ Bool) Γ— Bool := (next_bit (carry ∘ inl) (Ξ» a => (f a).2)) (Sum.elim g.1 (Ξ» x => (f x.1).1 x.2), g.2) ) x n | 0, init_carry, next_bit, init_carry_x, next_bit_x, x => rfl | n+1, init_carry, next_bit, init_carry_x, next_bit_x, x => by simp only [propagate_succ] rw [propagateCarry_propagate] congr ext congr induction' n with n ih . simp . simp [ih] lemma propagateCarry_changeVars {Ξ²' : Type} (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (x : Ξ²' β†’ β„• β†’ Bool) (i : β„•) (changeVars : Ξ² β†’ Ξ²') : propagateCarry init_carry next_bit (Ξ» b => x (changeVars b)) i = propagateCarry init_carry (Ξ» (carry : Ξ± β†’ Bool) (bits : Ξ²' β†’ Bool) => next_bit carry (Ξ» b => bits (changeVars b))) x i := by induction i . simp . simp [*] lemma propagate_changeVars {Ξ²' : Type} (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (x : Ξ²' β†’ β„• β†’ Bool) (i : β„•) (changeVars : Ξ² β†’ Ξ²') : propagate init_carry next_bit (Ξ» b => x (changeVars b)) i = propagate init_carry (Ξ» (carry : Ξ± β†’ Bool) (bits : Ξ²' β†’ Bool) => next_bit carry (Ξ» b => bits (changeVars b))) x i := by induction' i with i ih . rfl . simp only [propagate_succ, propagateCarry_changeVars, ih] open Term @[simp] def arity : Term β†’ β„• | (var n) => n+1 | zero => 0 | one => 0 | negOne => 0 | Term.and t₁ tβ‚‚ => max (arity t₁) (arity tβ‚‚) | Term.or t₁ tβ‚‚ => max (arity t₁) (arity tβ‚‚) | Term.xor t₁ tβ‚‚ => max (arity t₁) (arity tβ‚‚) | Term.not t => arity t | ls t => arity t | add t₁ tβ‚‚ => max (arity t₁) (arity tβ‚‚) | sub t₁ tβ‚‚ => max (arity t₁) (arity tβ‚‚) | neg t => arity t | incr t => arity t | decr t => arity t @[simp] def Term.evalFin : βˆ€ (t : Term) (_vars : Fin (arity t) β†’ β„• β†’ Bool), β„• β†’ Bool | var n, vars => vars (Fin.last n) | zero, _vars => zeroSeq | one, _vars => oneSeq | negOne, _vars => negOneSeq | Term.and t₁ tβ‚‚, vars => andSeq (Term.evalFin t₁ (fun i => vars (Fin.castLe (by simp [arity]) i))) (Term.evalFin tβ‚‚ (fun i => vars (Fin.castLe (by simp [arity]) i))) | Term.or t₁ tβ‚‚, vars => orSeq (Term.evalFin t₁ (fun i => vars (Fin.castLe (by simp [arity]) i))) (Term.evalFin tβ‚‚ (fun i => vars (Fin.castLe (by simp [arity]) i))) | Term.xor t₁ tβ‚‚, vars => xorSeq (Term.evalFin t₁ (fun i => vars (Fin.castLe (by simp [arity]) i))) (Term.evalFin tβ‚‚ (fun i => vars (Fin.castLe (by simp [arity]) i))) | not t, vars => notSeq (Term.evalFin t vars) | ls t, vars => lsSeq (Term.evalFin t vars) | add t₁ tβ‚‚, vars => addSeq (Term.evalFin t₁ (fun i => vars (Fin.castLe (by simp [arity]) i))) (Term.evalFin tβ‚‚ (fun i => vars (Fin.castLe (by simp [arity]) i))) | sub t₁ tβ‚‚, vars => subSeq (Term.evalFin t₁ (fun i => vars (Fin.castLe (by simp [arity]) i))) (Term.evalFin tβ‚‚ (fun i => vars (Fin.castLe (by simp [arity]) i))) | neg t, vars => negSeq (Term.evalFin t vars) | incr t, vars => incrSeq (Term.evalFin t vars) | decr t, vars => decrSeq (Term.evalFin t vars) lemma evalFin_eq_eval (t : Term) (vars : β„• β†’ β„• β†’ Bool) : Term.evalFin t (fun i => vars i) = Term.eval t vars := by induction t <;> dsimp [Term.evalFin, Term.eval, arity] at * <;> simp [*] lemma id_eq_propagate (x : β„• β†’ Bool) : x = propagate Empty.elim (Ξ» _ (y : Unit β†’ Bool) => (Empty.elim, y ())) (Ξ» _ => x) := by ext n; cases n <;> rfl lemma zero_eq_propagate : zeroSeq = propagate Empty.elim (Ξ» (_ _ : Empty β†’ Bool) => (Empty.elim, false)) Empty.elim := by ext n; cases n <;> rfl lemma one_eq_propagate : oneSeq = propagate (Ξ» _ : Unit => true) (Ξ» f (_ : Empty β†’ Bool) => (Ξ» _ => false, f ())) Empty.elim := by ext n match n with | 0 => rfl | 1 => rfl | n+2 => simp [oneSeq, propagate_succ] lemma and_eq_propagate (x y : β„• β†’ Bool) : andSeq x y = propagate Empty.elim (Ξ» _ (y : Bool β†’ Bool) => (Empty.elim, y true && y false)) (Ξ» b => cond b x y) := by ext n; cases n <;> simp [propagate, propagateAux, andSeq] lemma or_eq_propagate (x y : β„• β†’ Bool) : orSeq x y = propagate Empty.elim (Ξ» _ (y : Bool β†’ Bool) => (Empty.elim, y true || y false)) (Ξ» b => cond b x y) := by ext n; cases n <;> simp [propagate, propagateAux, orSeq] lemma xor_eq_propagate (x y : β„• β†’ Bool) : xorSeq x y = propagate Empty.elim (Ξ» _ (y : Bool β†’ Bool) => (Empty.elim, xor (y true) (y false))) (Ξ» b => cond b x y) := by ext n; cases n <;> simp [propagate, propagateAux, xorSeq] lemma not_eq_propagate (x : β„• β†’ Bool) : notSeq x = propagate Empty.elim (Ξ» _ (y : Unit β†’ Bool) => (Empty.elim, !(y ()))) (Ξ» _ => x) := by ext n; cases n <;> simp [propagate, propagateAux, notSeq] lemma ls_eq_propagate (x : β„• β†’ Bool) : lsSeq x = propagate (Ξ» _ : Unit => false) (Ξ» (carry x : Unit β†’ Bool) => (x, carry ())) (Ξ» _ => x) := by ext n match n with | 0 => rfl | 1 => rfl | n+2 => simp [lsSeq, propagate_succ] lemma addSeqAux_eq_propagateCarry (x y : β„• β†’ Bool) (n : β„•) : (addSeqAux x y n).2 = propagateCarry (Ξ» _ => false) (Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => Ξ» _ => (bits true && bits false) || (bits false && carry ()) || (bits true && carry ())) (Ξ» b => cond b x y) n () := by induction n <;> simp [addSeqAux, *] lemma add_eq_propagate (x y : β„• β†’ Bool) : addSeq x y = propagate (Ξ» _ => false) (Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => (Ξ» _ => (bits true && bits false) || (bits false && carry ()) || (bits true && carry ()), _root_.xor (bits true) (_root_.xor (bits false) (carry ())))) (Ξ» b => cond b x y) := by ext n match n with | 0 => simp [addSeq, addSeqAux] | 1 => simp [addSeq, addSeqAux, propagate, propagateAux] | n+2 => simp [addSeq, addSeqAux, addSeqAux_eq_propagateCarry, propagate_succ] lemma subSeqAux_eq_propagateCarry (x y : β„• β†’ Bool) (n : β„•) : (subSeqAux x y n).2 = propagateCarry (Ξ» _ => false) (Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => Ξ» _ => (!(bits true) && (bits false)) || (!(_root_.xor (bits true) (bits false))) && carry ()) (Ξ» b => cond b x y) n () := by induction n <;> simp [subSeqAux, *] lemma sub_eq_propagate (x y : β„• β†’ Bool) : subSeq x y = propagate (Ξ» _ => false) (Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => (Ξ» _ => (!(bits true) && (bits false)) || ((!(_root_.xor (bits true) (bits false))) && carry ()), _root_.xor (bits true) (_root_.xor (bits false) (carry ())))) (Ξ» b => cond b x y) := by ext n match n with | 0 => simp [subSeq, subSeqAux] | 1 => simp [subSeq, subSeqAux, propagate, propagateAux] | n+2 => simp [subSeq, subSeqAux, subSeqAux_eq_propagateCarry, propagate_succ] lemma negSeqAux_eq_propagateCarry (x : β„• β†’ Bool) (n : β„•) : (negSeqAux x n).2 = propagateCarry (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => Ξ» _ => (!(bits ())) && (carry ())) (Ξ» _ => x) n () := by induction n <;> simp [negSeqAux, *] lemma neg_eq_propagate (x : β„• β†’ Bool) : negSeq x = propagate (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => (Ξ» _ => (!(bits ())) && (carry ()), _root_.xor (!(bits ())) (carry ()))) (Ξ» _ => x) := by ext n match n with | 0 => simp [negSeq, negSeqAux] | 1 => simp [negSeq, negSeqAux, propagate, propagateAux] | n+2 => simp [negSeq, negSeqAux, negSeqAux_eq_propagateCarry, propagate_succ] lemma incrSeqAux_eq_propagateCarry (x : β„• β†’ Bool) (n : β„•) : (incrSeqAux x n).2 = propagateCarry (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => Ξ» _ => (bits ()) && carry ()) (Ξ» _ => x) n () := by induction n <;> simp [incrSeqAux, *] lemma incr_eq_propagate (x : β„• β†’ Bool) : incrSeq x = propagate (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => (Ξ» _ => (bits ()) && carry (), _root_.xor (bits ()) (carry ()))) (Ξ» _ => x) := by ext n match n with | 0 => simp [incrSeq, incrSeqAux] | 1 => simp [incrSeq, incrSeqAux, propagate, propagateAux] | n+2 => simp [incrSeq, incrSeqAux, incrSeqAux_eq_propagateCarry, propagate_succ] lemma decrSeqAux_eq_propagateCarry (x : β„• β†’ Bool) (n : β„•) : (decrSeqAux x n).2 = propagateCarry (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => Ξ» _ => (!(bits ())) && carry ()) (Ξ» _ => x) n () := by induction n <;> simp [decrSeqAux, *] lemma decr_eq_propagate (x : β„• β†’ Bool) : decrSeq x = propagate (Ξ» _ => true) (Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => (Ξ» _ => (!(bits ())) && carry (), _root_.xor (bits ()) (carry ()))) (Ξ» _ => x) := by ext n match n with | 0 => simp [decrSeq, decrSeqAux] | 1 => simp [decrSeq, decrSeqAux, propagate, propagateAux] | n+2 => simp [decrSeq, decrSeqAux, decrSeqAux_eq_propagateCarry, propagate_succ] structure PropagateStruc (arity : Type) : Type 1 := ( Ξ± : Type ) [ i : Fintype Ξ± ] ( init_carry : Ξ± β†’ Bool ) ( next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : arity β†’ Bool), (Ξ± β†’ Bool) Γ— Bool ) attribute [instance] PropagateStruc.i namespace PropagateStruc variable {arity : Type} (p : PropagateStruc arity) def eval : (arity β†’ β„• β†’ Bool) β†’ β„• β†’ Bool := propagate p.init_carry p.next_bit def changeVars {arity2 : Type} (changeVars : arity β†’ arity2) : PropagateStruc arity2 := { Ξ± := p.Ξ±, i := p.i, init_carry := p.init_carry, next_bit := Ξ» carry bits => p.next_bit carry (fun i => bits (changeVars i)) } def compose [Fintype arity] (new_arity : Type) (q_arity : arity β†’ Type) (vars : βˆ€ (a : arity), q_arity a β†’ new_arity) (q : βˆ€ (a : arity), PropagateStruc (q_arity a)) : PropagateStruc (new_arity) := { Ξ± := p.Ξ± βŠ• (Ξ£ a, (q a).Ξ±), i := by letI := p.i; infer_instance, init_carry := Sum.elim p.init_carry (Ξ» x => (q x.1).init_carry x.2), next_bit := Ξ» carry bits => let f : βˆ€ (a : arity), ((q a).Ξ± β†’ Bool) Γ— Bool := Ξ» a => (q a).next_bit (Ξ» d => carry (inr ⟨a, d⟩)) (Ξ» d => bits (vars a d)) let g : (p.Ξ± β†’ Bool) Γ— Bool := (p.next_bit (carry ∘ inl) (Ξ» a => (f a).2)) (Sum.elim g.1 (Ξ» x => (f x.1).1 x.2), g.2) } lemma eval_compose [Fintype arity] (new_arity : Type) (q_arity : arity β†’ Type) (vars : βˆ€ (a : arity), q_arity a β†’ new_arity) (q : βˆ€ (a : arity), PropagateStruc (q_arity a)) (x : new_arity β†’ β„• β†’ Bool): (p.compose new_arity q_arity vars q).eval x = p.eval (Ξ» a => (q a).eval (fun i => x (vars _ i))) := by ext n; simp only [eval, compose, propagate_propagate] def and : PropagateStruc Bool := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry bits => (Empty.elim, bits true && bits false) } @[simp] lemma eval_and (x : Bool β†’ β„• β†’ Bool) : and.eval x = andSeq (x true) (x false) := by ext n; cases n <;> simp [and, andSeq, eval, propagate_succ] def or : PropagateStruc Bool := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry bits => (Empty.elim, bits true || bits false) } @[simp] lemma eval_or (x : Bool β†’ β„• β†’ Bool) : or.eval x = orSeq (x true) (x false) := by ext n; cases n <;> simp [or, orSeq, eval, propagate_succ] def xor : PropagateStruc Bool := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry bits => (Empty.elim, _root_.xor (bits true) (bits false)) } @[simp] lemma eval_xor (x : Bool β†’ β„• β†’ Bool) : xor.eval x = xorSeq (x true) (x false) := by ext n; cases n <;> simp [xor, xorSeq, eval, propagate_succ] def add : PropagateStruc Bool := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => false, next_bit := Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => (Ξ» _ => (bits true && bits false) || (bits false && carry ()) || (bits true && carry ()), _root_.xor (bits true) (_root_.xor (bits false) (carry ()))) } @[simp] lemma eval_add (x : Bool β†’ β„• β†’ Bool) : add.eval x = addSeq (x true) (x false) := by dsimp [add, eval] rw [add_eq_propagate] congr funext b cases b; rfl simp congr funext i cases i <;> simp def sub : PropagateStruc Bool := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => false, next_bit := Ξ» (carry : Unit β†’ Bool) (bits : Bool β†’ Bool) => (Ξ» _ => (!(bits true) && (bits false)) || ((!(_root_.xor (bits true) (bits false))) && carry ()), _root_.xor (bits true) (_root_.xor (bits false) (carry ()))) } @[simp] lemma eval_sub (x : Bool β†’ β„• β†’ Bool) : sub.eval x = subSeq (x true) (x false) := by dsimp [sub, eval] rw [sub_eq_propagate] congr funext b cases b; rfl simp congr funext i cases i <;> simp def neg : PropagateStruc Unit := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => true, next_bit := Ξ» (carry : Unit β†’ Bool) (bits : Unit β†’ Bool) => (Ξ» _ => (!(bits ())) && (carry ()), _root_.xor (!(bits ())) (carry ())) } @[simp] lemma eval_neg (x : Unit β†’ β„• β†’ Bool) : neg.eval x = negSeq (x ()) := by dsimp [neg, eval] rw [neg_eq_propagate] def not : PropagateStruc Unit := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry bits => (Empty.elim, !(bits ())) } @[simp] lemma eval_not (x : Unit β†’ β„• β†’ Bool) : not.eval x = notSeq (x ()) := by ext n; cases n <;> simp [not, notSeq, eval, propagate_succ] def zero : PropagateStruc (Fin 0) := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry _bits => (Empty.elim, false) } @[simp] lemma eval_zero (x : Fin 0 β†’ β„• β†’ Bool) : zero.eval x = zeroSeq := by ext n; cases n <;> simp [zero, zeroSeq, eval, propagate_succ] def one : PropagateStruc (Fin 0) := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => true, next_bit := Ξ» carry _bits => (Ξ» _ => false, carry ()) } @[simp] lemma eval_one (x : Fin 0 β†’ β„• β†’ Bool) : one.eval x = oneSeq := by ext n; cases n <;> simp [one, oneSeq, eval, propagate_succ2, @eq_comm _ false] def negOne : PropagateStruc (Fin 0) := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry _bits => (Empty.elim, true) } @[simp] lemma eval_negOne (x : Fin 0 β†’ β„• β†’ Bool) : negOne.eval x = negOneSeq := by ext n; cases n <;> simp [negOne, negOneSeq, eval, propagate_succ2] def ls : PropagateStruc Unit := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => false, next_bit := Ξ» carry bits => (bits, carry ()) } @[simp] lemma eval_ls (x : Unit β†’ β„• β†’ Bool) : ls.eval x = lsSeq (x ()) := by ext n; cases n <;> simp [ls, lsSeq, eval, propagate_succ2] def var (n : β„•) : PropagateStruc (Fin (n+1)) := { Ξ± := Empty, i := by infer_instance, init_carry := Empty.elim, next_bit := Ξ» _carry bits => (Empty.elim, bits (Fin.last n)) } @[simp] lemma eval_var (n : β„•) (x : Fin (n+1) β†’ β„• β†’ Bool) : (var n).eval x = x (Fin.last n) := by ext m; cases m <;> simp [var, eval, propagate_succ] def incr : PropagateStruc Unit := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => true, next_bit := Ξ» carry bits => (Ξ» _ => bits () && carry (), _root_.xor (bits ()) (carry ())) } @[simp] lemma eval_incr (x : Unit β†’ β„• β†’ Bool) : incr.eval x = incrSeq (x ()) := by dsimp [incr, eval] rw [incr_eq_propagate] def decr : PropagateStruc Unit := { Ξ± := Unit, i := by infer_instance, init_carry := Ξ» _ => true, next_bit := Ξ» carry bits => (Ξ» _ => !(bits ()) && carry (), _root_.xor (bits ()) (carry ())) } @[simp] lemma eval_decr (x : Unit β†’ β„• β†’ Bool) : decr.eval x = decrSeq (x ()) := by dsimp [decr, eval] rw [decr_eq_propagate] end PropagateStruc structure PropagateSolution (t : Term) extends PropagateStruc (Fin (arity t)) := ( good : t.evalFin = toPropagateStruc.eval ) def composeUnary (p : PropagateStruc Unit) {t : Term} (q : PropagateSolution t) : PropagateStruc (Fin (arity t)) := p.compose (Fin (arity t)) _ (Ξ» _ => id) (Ξ» _ => q.toPropagateStruc) def X := @Bool.casesOn def composeBinary (p : PropagateStruc Bool) {t₁ tβ‚‚ : Term} (q₁ : PropagateSolution t₁) (qβ‚‚ : PropagateSolution tβ‚‚) : PropagateStruc (Fin (max (arity t₁) (arity tβ‚‚))) := p.compose (Fin (max (arity t₁) (arity tβ‚‚))) (Ξ» b => Fin (cond b (arity t₁) (arity tβ‚‚))) (Ξ» b i => Fin.castLe (by cases b <;> simp) i) (Ξ» b => match b with | true => q₁.toPropagateStruc | false => qβ‚‚.toPropagateStruc) @[simp] lemma composeUnary_eval (p : PropagateStruc Unit) {t : Term} (q : PropagateSolution t) (x : Fin (arity t) β†’ β„• β†’ Bool) : (composeUnary p q).eval x = p.eval (Ξ» _ => t.evalFin x) := by rw [composeUnary, PropagateStruc.eval_compose, q.good]; rfl @[simp] lemma composeBinary_eval (p : PropagateStruc Bool) {t₁ tβ‚‚ : Term} (q₁ : PropagateSolution t₁) (qβ‚‚ : PropagateSolution tβ‚‚) (x : Fin (max (arity t₁) (arity tβ‚‚)) β†’ β„• β†’ Bool) : (composeBinary p q₁ qβ‚‚).eval x = p.eval (Ξ» b => cond b (t₁.evalFin (fun i => x (Fin.castLe (by simp) i))) (tβ‚‚.evalFin (fun i => x (Fin.castLe (by simp) i)))) := by rw [composeBinary, PropagateStruc.eval_compose, q₁.good, qβ‚‚.good] congr ext b cases b <;> dsimp <;> congr <;> funext b <;> cases b <;> simp instance {Ξ± Ξ² : Type} [Fintype Ξ±] [Fintype Ξ²] (b : Bool) : Fintype (cond b Ξ± Ξ²) := by cases b <;> simp <;> infer_instance lemma cond_propagate {Ξ± Ξ±' Ξ² Ξ²' : Type} (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (init_carry' : Ξ±' β†’ Bool) (next_bit' : βˆ€ (_carry : Ξ±' β†’ Bool) (_bits : Ξ²' β†’ Bool), (Ξ±' β†’ Bool) Γ— Bool) {Ξ³ : Type} (fΞ² : Ξ² β†’ Ξ³) (fΞ²' : Ξ²' β†’ Ξ³) (x : Ξ³ β†’ β„• β†’ Bool) (b : Bool) : cond b (propagate init_carry next_bit (Ξ» b => (x (fΞ² b)))) (propagate init_carry' next_bit' (Ξ» b => (x (fΞ²' b)))) = propagate (show cond b Ξ± Ξ±' β†’ Bool from Bool.rec init_carry' init_carry b) (show βˆ€ (_carry : cond b Ξ± Ξ±' β†’ Bool) (_bits : cond b Ξ² Ξ²' β†’ Bool), (cond b Ξ± Ξ±' β†’ Bool) Γ— Bool from Bool.rec next_bit' next_bit b) (show cond b Ξ² Ξ²' β†’ β„• β†’ Bool from Bool.rec (Ξ» b => (x (fΞ²' b))) (Ξ» b => (x (fΞ² b))) b) := by cases b <;> rfl def termEvalEqPropagate : βˆ€ (t : Term), PropagateSolution t | var n => { toPropagateStruc := PropagateStruc.var n, good := by ext; simp [Term.evalFin] } | zero => { toPropagateStruc := PropagateStruc.zero, good := by ext; simp [Term.evalFin] } | one => { toPropagateStruc := PropagateStruc.one, good := by ext; simp [Term.evalFin] } | negOne => { toPropagateStruc := PropagateStruc.negOne, good := by ext; simp [Term.evalFin] } | Term.and t₁ tβ‚‚ => let q₁ := termEvalEqPropagate t₁ let qβ‚‚ := termEvalEqPropagate tβ‚‚ { toPropagateStruc := composeBinary PropagateStruc.and q₁ qβ‚‚, good := by ext; simp } | Term.or t₁ tβ‚‚ => let q₁ := termEvalEqPropagate t₁ let qβ‚‚ := termEvalEqPropagate tβ‚‚ { toPropagateStruc := composeBinary PropagateStruc.or q₁ qβ‚‚, good := by ext; simp } | Term.xor t₁ tβ‚‚ => let q₁ := termEvalEqPropagate t₁ let qβ‚‚ := termEvalEqPropagate tβ‚‚ { toPropagateStruc := composeBinary PropagateStruc.xor q₁ qβ‚‚, good := by ext; simp } | ls t => let q := termEvalEqPropagate t { toPropagateStruc := by dsimp [arity]; exact composeUnary PropagateStruc.ls q, good := by ext; simp } | Term.not t => let q := termEvalEqPropagate t { toPropagateStruc := by dsimp [arity]; exact composeUnary PropagateStruc.not q, good := by ext; simp } | add t₁ tβ‚‚ => let q₁ := termEvalEqPropagate t₁ let qβ‚‚ := termEvalEqPropagate tβ‚‚ { toPropagateStruc := composeBinary PropagateStruc.add q₁ qβ‚‚, good := by ext; simp } | sub t₁ tβ‚‚ => let q₁ := termEvalEqPropagate t₁ let qβ‚‚ := termEvalEqPropagate tβ‚‚ { toPropagateStruc := composeBinary PropagateStruc.sub q₁ qβ‚‚, good := by ext; simp } | neg t => let q := termEvalEqPropagate t { toPropagateStruc := by dsimp [arity]; exact composeUnary PropagateStruc.neg q, good := by ext; simp } | incr t => let q := termEvalEqPropagate t { toPropagateStruc := by dsimp [arity]; exact composeUnary PropagateStruc.incr q, good := by ext; simp } | decr t => let q := termEvalEqPropagate t { toPropagateStruc := by dsimp [arity]; exact composeUnary PropagateStruc.decr q, good := by ext; simp } variable (init_carry : Ξ± β†’ Bool) (next_carry : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) variable [Fintype Ξ±] [Fintype Ξ±'] open Fintype lemma exists_repeat_carry (seq : Ξ² β†’ β„• β†’ Bool) : βˆƒ n m : Fin (2 ^ (card Ξ±) + 1), propagateCarry2 init_carry next_carry seq n = propagateCarry2 init_carry next_carry seq m ∧ n < m := by by_contra h haveI := Classical.decEq Ξ± push_neg at h have := Ξ» a b hab => (le_antisymm (h a b hab) (h b a hab.symm)).symm have := Fintype.card_le_of_injective _ this simp at this lemma propagateCarry2_eq_of_seq_eq_lt (seq₁ seqβ‚‚ : Ξ² β†’ β„• β†’ Bool) (init_carry : Ξ± β†’ Bool) (next_carry : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)) (i : β„•) (h : βˆ€ (b) (j) (_hj : j < i), seq₁ b j = seqβ‚‚ b j) : propagateCarry2 init_carry next_carry seq₁ i = propagateCarry2 init_carry next_carry seqβ‚‚ i := by induction' i with i ih { simp [propagateCarry2] } { simp only [propagateCarry2, h _ i (Nat.lt_succ_self i)] rw [ih] exact Ξ» b j hj => h b j (Nat.lt_succ_of_lt hj) } lemma propagate_eq_of_seq_eq_le (seq₁ seqβ‚‚ : Ξ² β†’ β„• β†’ Bool) (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) (i : β„•) (h : βˆ€ (b) (j) (_hj : j ≀ i), seq₁ b j = seqβ‚‚ b j) : propagate init_carry next_bit seq₁ i = propagate init_carry next_bit seqβ‚‚ i := by cases i { simp [propagate_zero, h _ 0 (le_refl _)] } { simp only [propagate_succ2, propagate_succ2, h _ _ (le_refl _)] congr 2 apply propagateCarry2_eq_of_seq_eq_lt exact Ξ» b j hj => h b j (le_of_lt hj) } lemma propagateCarry2_eq_of_carry_eq (seq₁ seqβ‚‚ : Ξ² β†’ β„• β†’ Bool) (m n : β„•) (h₁ : propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seq₁ m = propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seqβ‚‚ n) (x : β„•) (h₃ : βˆ€ y b, y ≀ x β†’ seq₁ b (m + y) = seqβ‚‚ b (n + y)) : propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seq₁ (m + x) = propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seqβ‚‚ (n + x) := by induction' x with x ih generalizing seq₁ seqβ‚‚ { simp [*] at * } { simp only [propagateCarry2, Nat.add_eq, h₃ x _ (Nat.le_succ _)] at * rw [ih] assumption exact Ξ» y b h => h₃ y b (Nat.le_succ_of_le h) } lemma propagate_eq_of_carry_eq (seq₁ seqβ‚‚ : Ξ² β†’ β„• β†’ Bool) (m n : β„•) (h₁ : propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seq₁ m = propagateCarry2 init_carry (Ξ» carry bits => (next_bit carry bits).1) seqβ‚‚ n) (x : β„•) (h₃ : βˆ€ y b, y ≀ x β†’ seq₁ b (m + y) = seqβ‚‚ b (n + y)) : propagate init_carry next_bit seq₁ (m + x) = propagate init_carry next_bit seqβ‚‚ (n + x) := by cases x { cases m { cases n { simp [h₃ 0 _ (le_refl _), propagateCarry2, *] at * } { simp [*, h₃ 0 _ (le_refl _), propagate_succ2] at * rw [← h₁] } } { cases n { simp [*, propagate_succ2] at * have := fun i => h₃ 0 i rfl dsimp at this simp [this] simp [h₁] } { rw [propagate_succ2, h₁, propagate_succ2] have := h₃ 0 simp [*] at * } } } { erw [Nat.add_succ, propagate_succ2, propagate_succ2, Nat.add_eq, Nat.add_eq] simp [← Nat.succ_eq_add_one, ← Nat.add_succ, h₃ _ _ (le_refl _)] congr . apply propagateCarry2_eq_of_carry_eq . assumption . exact Ξ» y b h => h₃ y b (Nat.le_succ_of_le h) . funext i rw [h₃] exact Nat.le_succ _ } lemma propagateCarry_propagateCarry_add (x : Ξ² β†’ β„• β†’ Bool) : βˆ€ (init_carry : Ξ± β†’ Bool) (next_carry : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool)), βˆ€ n i : β„•, propagateCarry2 (propagateCarry2 init_carry next_carry x n) next_carry (Ξ» b k => x b (k + n)) i = propagateCarry2 init_carry next_carry x (i + n) | init_carry, _next_carry, 0, 0 => by simp [propagateCarry2] | init_carry, next_carr, n+1, 0 => by simp [propagateCarry, propagateCarry2_succ] | init_carry, next_carry, n, i+1 => by rw [propagateCarry2, add_assoc, propagateCarry_propagateCarry_add _ _ _ _ i] simp only [Nat.one_add, Nat.add_one, Nat.succ_add, Nat.add_succ, add_zero, propagateCarry2, zero_add] lemma exists_repeat : βˆ€ (seq : Ξ² β†’ β„• β†’ Bool) (n : β„•), βˆƒ (m : β„•) (_hm : m < 2 ^ (card Ξ±)) (seq2 : Ξ² β†’ β„• β†’ Bool), propagate init_carry next_bit seq2 m = propagate init_carry next_bit seq n | seq, n => by by_cases hn2 : n < 2 ^ card Ξ± { exact ⟨n, hn2, seq, rfl⟩ } { rcases exists_repeat_carry (propagateCarry2 init_carry (Ξ» c b => (next_bit c b).1) seq (n - 2 ^ card Ξ±)) (Ξ» carry bits => (next_bit carry bits).1) (Ξ» b i => seq b (i + (n - 2^ (card Ξ±)))) with ⟨a, b, h₁, hβ‚‚βŸ© simp only [propagateCarry_propagateCarry_add] at h₁ rcases have _wf : n - (b - a) < n := Nat.sub_lt (lt_of_lt_of_le (pow_pos (by norm_num) _) (le_of_not_lt hn2)) (Nat.sub_pos_of_lt hβ‚‚) exists_repeat (Ξ» c i => if i < a + (n - 2 ^ card Ξ±) then seq c i else seq c (i + (b - a))) (n - (b - a)) with ⟨m, hmle, seq2, hm⟩ use m; use hmle; use seq2 rw [hm]; clear hm have h1 : n - (b - a) = (a + (n - 2 ^ (card Ξ±))) + (2 ^ card Ξ± - b) := by { zify rw [Nat.cast_sub, Nat.cast_sub, Nat.cast_sub, Nat.cast_sub] ring_nf exact Nat.le_of_lt_succ b.2 simp [*] at * exact hn2 exact le_of_lt hβ‚‚ exact le_trans (Nat.sub_le _ _) (le_trans (Nat.le_of_lt_succ b.2) (le_of_not_lt hn2)) } rw [h1] have h2 : n = (b + (n - 2 ^ card Ξ±)) + (2 ^ card Ξ± - b) := by { zify rw [Nat.cast_sub, Nat.cast_sub] ring exact Nat.le_of_lt_succ b.2 simp [*] at * exact hn2 } conv_rhs => rw [h2] refine' propagate_eq_of_carry_eq _ _ _ _ _ _ _ _ _ { have _h : ↑b + (n - 2 ^ card Ξ±) = (a + (n - 2 ^ card Ξ±)) + (b - a) := by { zify rw [Nat.cast_sub, Nat.cast_sub] ring_nf exact le_of_lt hβ‚‚ exact le_of_not_lt hn2 } rw [← h₁] apply propagateCarry2_eq_of_seq_eq_lt simp (config := { contextual := true }) } { intro y c _hc simp only [add_lt_iff_neg_left, not_lt_zero', if_false] congr 1 zify rw [Nat.cast_sub, Nat.cast_sub] ring exact le_of_lt hβ‚‚ exact le_of_not_lt hn2 } } lemma propagate_eq_zero_iff (init_carry : Ξ± β†’ Bool) (next_bit : βˆ€ (_carry : Ξ± β†’ Bool) (_bits : Ξ² β†’ Bool), (Ξ± β†’ Bool) Γ— Bool) : (βˆ€ seq, propagate init_carry next_bit seq = zeroSeq) ↔ (βˆ€ seq, βˆ€ i < 2 ^ (card Ξ±), propagate init_carry next_bit seq i = false) := by constructor { intro h i _ simp [h, zeroSeq] } { intro h seq funext i rcases exists_repeat init_carry next_bit seq i with ⟨j, hj, seq2, hseq2⟩ rw [← hseq2, h seq2 j hj, zeroSeq] } lemma eq_iff_xorSeq_eq_zero (seq₁ seqβ‚‚ : β„• β†’ Bool) : (βˆ€ i, seq₁ i = seqβ‚‚ i) ↔ (βˆ€ i, xorSeq seq₁ seqβ‚‚ i = zeroSeq i) := by simp [Function.funext_iff, xorSeq, zeroSeq] constructor { intro i _; simp [*] } { intro h a specialize h a revert h cases (seq₁ a) <;> cases (seqβ‚‚ a) <;> simp [*] at * } lemma eval_eq_iff_xorSeq_eq_zero (t₁ tβ‚‚ : Term) : t₁.eval = tβ‚‚.eval ↔ (t₁.xor tβ‚‚).evalFin = Ξ» _ => zeroSeq := by simp only [Function.funext_iff, Term.eval, Term.evalFin, ← eq_iff_xorSeq_eq_zero, ← evalFin_eq_eval] constructor { intro h seq n have := h (Ξ» j => if hj : j < (arity (t₁.xor tβ‚‚)) then seq ⟨j, hj⟩ else Ξ» _ => false) n simp at this convert this } { intro h seq m exact h (Ξ» j => seq j) _ }
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* Properties of machine operations. *) theory Machine_AI imports Bits_AI begin definition "no_irq f \<equiv> \<forall>P. \<lbrace>\<lambda>s. P (irq_masks s)\<rbrace> f \<lbrace>\<lambda>_ s. P (irq_masks s)\<rbrace>" lemma wpc_helper_no_irq: "no_irq f \<Longrightarrow> wpc_helper (P, P') (Q, Q') (no_irq f)" by (simp add: wpc_helper_def) wpc_setup "\<lambda>m. no_irq m" wpc_helper_no_irq ML \<open> structure CrunchNoIrqInstance : CrunchInstance = struct val name = "no_irq"; val prefix_name_scheme = true; type extra = unit; val eq_extra = op =; fun parse_extra ctxt extra = case extra of "" => (Syntax.parse_term ctxt "%_. True", ()) | _ => error "no_irq does not need a precondition"; val has_preconds = false; fun mk_term _ body _ = (Syntax.parse_term @{context} "no_irq") $ body; fun dest_term (Const (@{const_name no_irq}, _) $ body) = SOME (Term.dummy, body, ()) | dest_term _ = NONE; fun put_precond _ _ = error "crunch no_irq should not be calling put_precond"; val pre_thms = []; val wpc_tactic = wp_cases_tactic_weak; fun wps_tactic _ _ _ = no_tac; val magic = Syntax.parse_term @{context} "\<lambda>mapp_lambda_ignore. no_irq mapp_lambda_ignore"; val get_monad_state_type = get_nondet_monad_state_type; end; structure CrunchNoIrq : CRUNCH = Crunch(CrunchNoIrqInstance); \<close> setup \<open> add_crunch_instance "no_irq" (CrunchNoIrq.crunch_x, CrunchNoIrq.crunch_ignore_add_dels) \<close> crunch_ignore (no_irq) (add: NonDetMonad.bind return "when" get gets fail assert put modify unless select alternative assert_opt gets_the returnOk throwError lift bindE liftE whenE unlessE throw_opt assertE liftM liftME sequence_x zipWithM_x mapM_x sequence mapM sequenceE_x mapME_x catch select_f handleE' handleE handle_elseE forM forM_x zipWithM ignore_failure) context Arch begin lemma det_getRegister: "det (getRegister x)" by (simp add: getRegister_def) lemma det_setRegister: "det (setRegister x w)" by (simp add: setRegister_def det_def modify_def get_def put_def bind_def) lemma det_getRestartPC: "det getRestartPC" by (simp add: getRestartPC_def det_getRegister) lemma det_setNextPC: "det (setNextPC p)" by (simp add: setNextPC_def det_setRegister) (* FIXME empty_fail: make all empty_fail [intro!, wp], and non-conditional ones [simp] *) lemma ef_loadWord: "empty_fail (loadWord x)" by (fastforce simp: loadWord_def) lemma ef_storeWord: "empty_fail (storeWord x y)" by (fastforce simp: storeWord_def) lemma no_fail_getRestartPC: "no_fail \<top> getRestartPC" by (simp add: getRestartPC_def getRegister_def) lemma no_fail_loadWord [wp]: "no_fail (\<lambda>_. is_aligned p 3) (loadWord p)" apply (simp add: loadWord_def is_aligned_mask [symmetric]) apply (rule no_fail_pre) apply wp apply simp done lemma no_fail_storeWord: "no_fail (\<lambda>_. is_aligned p 3) (storeWord p w)" apply (simp add: storeWord_def is_aligned_mask [symmetric]) apply (rule no_fail_pre) apply (wp) apply simp done lemma no_fail_machine_op_lift [simp]: "no_fail \<top> (machine_op_lift f)" by (simp add: machine_op_lift_def) lemma ef_machine_op_lift [simp]: "empty_fail (machine_op_lift f)" by (simp add: machine_op_lift_def) lemma no_fail_setNextPC: "no_fail \<top> (setNextPC pc)" by (simp add: setNextPC_def setRegister_def) lemma no_fail_initL2Cache: "no_fail \<top> initL2Cache" by (simp add: initL2Cache_def) lemma no_fail_resetTimer[wp]: "no_fail \<top> resetTimer" by (simp add: resetTimer_def) lemma loadWord_inv: "\<lbrace>P\<rbrace> loadWord x \<lbrace>\<lambda>x. P\<rbrace>" apply (simp add: loadWord_def) apply wp apply simp done lemma getRestartPC_inv: "\<lbrace>P\<rbrace> getRestartPC \<lbrace>\<lambda>rv. P\<rbrace>" by (simp add: getRestartPC_def getRegister_def) lemma no_fail_clearMemory[simp, wp]: "no_fail (\<lambda>_. is_aligned p 3) (clearMemory p b)" apply (simp add: clearMemory_def mapM_x_mapM) apply (rule no_fail_pre) apply (wp no_fail_mapM' no_fail_storeWord ) apply (clarsimp simp: upto_enum_step_def) apply (erule aligned_add_aligned) apply (simp add: word_size_def) apply (rule is_aligned_mult_triv2 [where n = 3, simplified]) apply simp done lemma no_fail_freeMemory[simp, wp]: "no_fail (\<lambda>_. is_aligned p 3) (freeMemory p b)" apply (simp add: freeMemory_def mapM_x_mapM) apply (rule no_fail_pre) apply (wp no_fail_mapM' no_fail_storeWord) apply (clarsimp simp: upto_enum_step_def) apply (erule aligned_add_aligned) apply (simp add: word_size_def) apply (rule is_aligned_mult_triv2 [where n = 3, simplified]) apply simp done lemma no_fail_getActiveIRQ[wp]: "no_fail \<top> (getActiveIRQ in_kernel)" apply (simp add: getActiveIRQ_def) apply (rule no_fail_pre) apply (wp no_fail_select) apply simp done definition "irq_state_independent P \<equiv> \<forall>f s. P s \<longrightarrow> P (irq_state_update f s)" lemma getActiveIRQ_inv [wp]: "\<lbrakk>irq_state_independent P\<rbrakk> \<Longrightarrow> \<lbrace>P\<rbrace> getActiveIRQ in_kernel \<lbrace>\<lambda>rv. P\<rbrace>" apply (simp add: getActiveIRQ_def) apply (wp alternative_wp select_wp) apply (simp add: irq_state_independent_def) done lemma no_fail_ackInterrupt[wp]: "no_fail \<top> (ackInterrupt irq)" by (simp add: ackInterrupt_def) lemma no_fail_maskInterrupt[wp]: "no_fail \<top> (maskInterrupt irq bool)" by (simp add: maskInterrupt_def) lemma no_irq_use: "\<lbrakk> no_irq f; (rv,s') \<in> fst (f s) \<rbrakk> \<Longrightarrow> irq_masks s' = irq_masks s" apply (simp add: no_irq_def valid_def) apply (erule_tac x="\<lambda>x. x = irq_masks s" in allE) apply fastforce done lemma no_irq_machine_rest_lift: "no_irq (machine_rest_lift f)" apply (clarsimp simp: no_irq_def machine_rest_lift_def split_def) apply wp apply simp done crunch (no_irq) no_irq[wp, simp]: machine_op_lift lemma no_irq: "no_irq f \<Longrightarrow> \<lbrace>\<lambda>s. P (irq_masks s)\<rbrace> f \<lbrace>\<lambda>_ s. P (irq_masks s)\<rbrace>" by (simp add: no_irq_def) lemma no_irq_invalidateTLB: "no_irq invalidateTLB" by (simp add: invalidateTLB_def) lemma no_irq_initL2Cache: "no_irq initL2Cache" by (simp add: initL2Cache_def) lemma no_irq_gets [simp]: "no_irq (gets f)" by (simp add: no_irq_def) lemma no_irq_resetTimer: "no_irq resetTimer" by (simp add: resetTimer_def) lemma no_irq_debugPrint: "no_irq (debugPrint $ xs)" by (simp add: no_irq_def) context notes no_irq[wp] begin lemma no_irq_ackInterrupt: "no_irq (ackInterrupt irq)" by (wp | clarsimp simp: no_irq_def ackInterrupt_def)+ lemma no_irq_writeCR3: "no_irq (writeCR3 vs asid)" by (wp | clarsimp simp: no_irq_def writeCR3_def)+ lemma no_irq_loadWord: "no_irq (loadWord x)" apply (clarsimp simp: no_irq_def) apply (rule loadWord_inv) done lemma no_irq_getActiveIRQ: "no_irq (getActiveIRQ in_kernel)" apply (clarsimp simp: no_irq_def) apply (rule getActiveIRQ_inv) apply (simp add: irq_state_independent_def) done lemma no_irq_mapM: "(\<And>x. x \<in> set xs \<Longrightarrow> no_irq (f x)) \<Longrightarrow> no_irq (mapM f xs)" apply (subst no_irq_def) apply clarify apply (rule mapM_wp) prefer 2 apply (rule order_refl) apply (wp; simp) done lemma no_irq_mapM_x: "(\<And>x. x \<in> set xs \<Longrightarrow> no_irq (f x)) \<Longrightarrow> no_irq (mapM_x f xs)" apply (subst no_irq_def) apply clarify apply (rule mapM_x_wp) prefer 2 apply (rule order_refl) apply (wp; simp) done lemma no_irq_swp: "no_irq (f y x) \<Longrightarrow> no_irq (swp f x y)" by (simp add: swp_def) lemma no_irq_seq [wp]: "\<lbrakk> no_irq f; \<And>x. no_irq (g x) \<rbrakk> \<Longrightarrow> no_irq (f >>= g)" apply (subst no_irq_def) apply clarsimp apply (rule hoare_seq_ext) apply (wp|simp)+ done lemma no_irq_return [simp, wp]: "no_irq (return v)" unfolding no_irq_def return_def by (rule allI, simp add: valid_def) lemma no_irq_fail [simp, wp]: "no_irq fail" unfolding no_irq_def fail_def by (rule allI, simp add: valid_def) lemma no_irq_assert [simp, wp]: "no_irq (assert P)" unfolding assert_def by simp lemma no_irq_modify: "(\<And>s. irq_masks (f s) = irq_masks s) \<Longrightarrow> no_irq (modify f)" unfolding modify_def no_irq_def apply (rule allI, simp add: valid_def put_def get_def) apply (clarsimp simp: in_monad) done lemma no_irq_invalidateTLBEntry: "no_irq (invalidateTLBEntry a)" by (clarsimp simp: invalidateTLBEntry_def) lemma no_irq_storeWord: "no_irq (storeWord w p)" apply (simp add: storeWord_def) apply (wp no_irq_modify) apply simp done lemma no_irq_when: "\<lbrakk>P \<Longrightarrow> no_irq f\<rbrakk> \<Longrightarrow> no_irq (when P f)" by (simp add: when_def) lemma no_irq_clearMemory: "no_irq (clearMemory a b)" apply (simp add: clearMemory_def) apply (wp no_irq_mapM_x no_irq_storeWord) done lemma no_irq_in8: "no_irq (in8 irq)" by (wp | clarsimp simp: in8_def)+ lemma no_irq_in16: "no_irq (in16 irq)" by (wp | clarsimp simp: in16_def)+ lemma no_irq_in32: "no_irq (in32 irq)" by (wp | clarsimp simp: in32_def)+ lemma no_irq_out8: "no_irq (out8 irq b)" by (wp | clarsimp simp: out8_def)+ lemma no_irq_out16: "no_irq (out16 irq b)" by (wp | clarsimp simp: out16_def)+ lemma no_irq_out32: "no_irq (out32 irq b)" by (wp | clarsimp simp: out32_def)+ lemma no_irq_invalidateLocalPageStructureCacheASID: "no_irq (invalidateLocalPageStructureCacheASID vspace asid)" by (wpsimp simp: invalidateLocalPageStructureCacheASID_def) lemmas invalidateLocalPageStructureCacheASID_irq_masks = no_irq[OF no_irq_invalidateLocalPageStructureCacheASID] lemma no_irq_nativeThreadUsingFPU: "no_irq (nativeThreadUsingFPU thread)" by (wp | clarsimp simp: nativeThreadUsingFPU_def)+ lemma no_irq_switchFpuOwner: "no_irq (switchFpuOwner thread cpu)" by (wp | clarsimp simp: switchFpuOwner_def)+ lemmas nativeThreadUsingFPU_irq_masks = no_irq[OF no_irq_nativeThreadUsingFPU] lemmas switchFpuOwner_irq_masks = no_irq[OF no_irq_switchFpuOwner] lemma getActiveIRQ_le_maxIRQ': "\<lbrace>\<lambda>s. \<forall>irq > maxIRQ. irq_masks s irq\<rbrace> getActiveIRQ in_kernel \<lbrace>\<lambda>rv s. \<forall>x. rv = Some x \<longrightarrow> x \<le> maxIRQ\<rbrace>" apply (simp add: getActiveIRQ_def) apply (wp alternative_wp select_wp) apply clarsimp apply (rule ccontr) apply (simp add: linorder_not_le) done (* FIXME: follows already from getActiveIRQ_le_maxIRQ *) lemma getActiveIRQ_neq_Some0xFF': "\<lbrace>\<top>\<rbrace> getActiveIRQ in_kernel \<lbrace>\<lambda>rv s. rv \<noteq> Some 0x3FF\<rbrace>" apply (simp add: getActiveIRQ_def) apply (wp alternative_wp select_wp) apply simp done lemma getActiveIRQ_neq_non_kernel: "\<lbrace>\<top>\<rbrace> getActiveIRQ True \<lbrace>\<lambda>rv s. rv \<notin> Some ` non_kernel_IRQs \<rbrace>" apply (simp add: getActiveIRQ_def) apply (wp alternative_wp select_wp) apply auto done lemma dmo_getActiveIRQ_non_kernel[wp]: "\<lbrace>\<top>\<rbrace> do_machine_op (getActiveIRQ True) \<lbrace>\<lambda>rv s. \<forall>irq. rv = Some irq \<longrightarrow> irq \<in> non_kernel_IRQs \<longrightarrow> P irq s\<rbrace>" unfolding do_machine_op_def apply wpsimp apply (drule use_valid, rule getActiveIRQ_neq_non_kernel, rule TrueI) apply clarsimp done lemma empty_fail_invalidateTLB: "empty_fail invalidateTLB" by (simp add: invalidateTLB_def) lemma empty_fail_initL2Cache: "empty_fail initL2Cache" by (simp add: initL2Cache_def) lemma empty_fail_clearMemory [simp, intro!]: "\<And>a b. empty_fail (clearMemory a b)" by (fastforce simp: clearMemory_def mapM_x_mapM ef_storeWord) lemma getFaultAddress_ef[simp,wp]: "empty_fail getFaultAddress" by (simp add: getFaultAddress_def) lemma ioapicMapPinToVector_ef[simp,wp]: "empty_fail (ioapicMapPinToVector a b c d e)" by (simp add: ioapicMapPinToVector_def) lemma invalidateTLBEntry_ef[simp,wp]: "empty_fail (invalidateTLBEntry b)" by (simp add: invalidateTLBEntry_def) lemma invalidateASID_ef[simp,wp]: "empty_fail (invalidateASID a b)" by (simp add: invalidateASID_def) lemma invalidateTranslationSingleASID_ef[simp,wp]: "empty_fail (invalidateTranslationSingleASID a b)" by (simp add: invalidateTranslationSingleASID_def) lemma hwASIDInvalidate_ef[simp,wp]: "empty_fail (hwASIDInvalidate b a)" by (simp add: hwASIDInvalidate_def) lemma updateIRQState_ef[simp,wp]: "empty_fail (updateIRQState b c)" by (fastforce simp: updateIRQState_def) lemma writeCR3_ef[simp,wp]: "empty_fail (writeCR3 a b)" by (simp add: writeCR3_def) lemma in8_ef[simp,wp]: "empty_fail (in8 port)" by (fastforce simp: in8_def) lemma in16_ef[simp,wp]: "empty_fail (in16 port)" by (fastforce simp: in16_def) lemma in32_ef[simp,wp]: "empty_fail (in32 port)" by (fastforce simp: in32_def) lemma out8_ef[simp,wp]: "empty_fail (out8 port dat)" by (simp add: out8_def) lemma out16_ef[simp,wp]: "empty_fail (out16 port dat)" by (simp add: out16_def) lemma out32_ef[simp,wp]: "empty_fail (out32 port dat)" by (simp add: out32_def) end end context begin interpretation Arch . requalify_facts det_getRegister det_setRegister det_getRestartPC det_setNextPC end end
! { dg-do run } ! { dg-options "-frepack-arrays" } ! ! Check that arrays marked with TARGET attribute are not repacked. ! program test2 use iso_c_binding implicit none real, target :: x(7) type(c_ptr) cp1, cp2 x = 42 if (.not. c_associated(c_loc(x(3)),point(x(::2)))) STOP 1 contains function point(x) use iso_c_binding real, intent(in), target :: x(:) type(c_ptr) point real, pointer :: p p => x(2) point = c_loc(p) end function point end program test2
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.associated import algebra.big_operators.basic /-! # Prime elements in rings This file contains lemmas about prime elements of commutative rings. -/ variables {R : Type*} [comm_cancel_monoid_with_zero R] open finset open_locale big_operators /-- If `x * y = a * ∏ i in s, p i` where `p i` is always prime, then `x` and `y` can both be written as a divisor of `a` multiplied by a product over a subset of `s` -/ lemma mul_eq_mul_prime_prod {Ξ± : Type*} [decidable_eq Ξ±] {x y a : R} {s : finset Ξ±} {p : Ξ± β†’ R} (hp : βˆ€ i ∈ s, prime (p i)) (hx : x * y = a * ∏ i in s, p i) : βˆƒ (t u : finset Ξ±) (b c : R), t βˆͺ u = s ∧ disjoint t u ∧ a = b * c ∧ x = b * ∏ i in t, p i ∧ y = c * ∏ i in u, p i := begin induction s using finset.induction with i s his ih generalizing x y a, { exact βŸ¨βˆ…, βˆ…, x, y, by simp [hx]⟩ }, { rw [prod_insert his, ← mul_assoc] at hx, have hpi : prime (p i), { exact hp i (mem_insert_self _ _) }, rcases ih (Ξ» i hi, hp i (mem_insert_of_mem hi)) hx with ⟨t, u, b, c, htus, htu, hbc, rfl, rfl⟩, have hit : i βˆ‰ t, from Ξ» hit, his (htus β–Έ mem_union_left _ hit), have hiu : i βˆ‰ u, from Ξ» hiu, his (htus β–Έ mem_union_right _ hiu), obtain ⟨d, rfl⟩ | ⟨d, rfl⟩ : p i ∣ b ∨ p i ∣ c, from hpi.div_or_div ⟨a, by rw [← hbc, mul_comm]⟩, { rw [mul_assoc, mul_comm a, mul_right_inj' hpi.ne_zero] at hbc, exact ⟨insert i t, u, d, c, by rw [insert_union, htus], disjoint_insert_left.2 ⟨hiu, htu⟩, by simp [hbc, prod_insert hit, mul_assoc, mul_comm, mul_left_comm]⟩ }, { rw [← mul_assoc, mul_right_comm b, mul_left_inj' hpi.ne_zero] at hbc, exact ⟨t, insert i u, b, d, by rw [union_insert, htus], disjoint_insert_right.2 ⟨hit, htu⟩, by simp [← hbc, prod_insert hiu, mul_assoc, mul_comm, mul_left_comm]⟩ } } end /-- If ` x * y = a * p ^ n` where `p` is prime, then `x` and `y` can both be written as the product of a power of `p` and a divisor of `a`. -/ lemma mul_eq_mul_prime_pow {x y a p : R} {n : β„•} (hp : prime p) (hx : x * y = a * p ^ n) : βˆƒ (i j : β„•) (b c : R), i + j = n ∧ a = b * c ∧ x = b * p ^ i ∧ y = c * p ^ j := begin rcases mul_eq_mul_prime_prod (Ξ» _ _, hp) (show x * y = a * (range n).prod (Ξ» _, p), by simpa) with ⟨t, u, b, c, htus, htu, rfl, rfl, rfl⟩, exact ⟨t.card, u.card, b, c, by rw [← card_disjoint_union htu, htus, card_range], by simp⟩, end
Autistic young adults -- are we ready for them? Autism is the fastest-growing developmental disability in the United States. Those born within the first big wave of diagnosed cases in the United States are now entering adulthood, and it has become a difficult and volatile future. Some will not go to college; others will not be able to get jobs. Many autistic adults will live with their parents for most of their lives and in some cases, only if they get the proper guidance and support, they may find a part-time job. Thousands of Latinos are part of the generation of young autistic adults. They were diagnosed in the early 1990s. The lack of information, language barriers, and the limited resources available for Spanish-speaking parents makes these young autistic Latinos more prone to difficulties in their transition to adulthood and the potential for independence. Our KVEA Telemundo Los Angeles audience is mainly non-English-speaking Hispanics. Due to the majority of these families not having proper support to overcome the challenges for their autistic adult children, they end up misinformed and without help or resources. Our 2013 California Endowment Health Journalism project studied in-depth the dark reality, and some of our findings are very concerning. The Center for Disease Control and Prevention (CDC) explained that from 2002 to 2008 the biggest increase in children diagnosed with autism was among Hispanics -- a 110% increase. Another big eye opener was the lack of services for autistic young adults available after graduating high school. We interviewed Professor Paul Shattuck Ph.D. from the University of Washington in St. Louis and his findings are overwhelming. Shattuck notes that approximately 50,000 young adults in the U.S. suffering from Autism Spectrum Disorder (ASD) turned 18 in 2013. In a phone interview he commented about the lack of services offered to autistic young adults after graduating high school. 46.9% students with autism receive medical services during their high school years. This percentage decrease when they finish high school, at which only 23.5% are left with this service. 74.6 % of students with autism receive speech therapy during their high school years, which later decreases to only 9.1%, post high school. Those numbers are more devastating among non-English-speaking families. Gloria Rodriguez from the organization Parents with Exceptional Kids, explained that over 90% of the families she works with do not speak English. She states that the majority of these families are afraid of law enforcement because of their immigrant status. Some of these parents strongly believe their autistic young adults born in the United States do not have rights. We also interviewed Elizabeth Gomez regarding her 18-year-old son. She shared that the regional center where she lives is not helping her son with any programs. β€œWe are abandoned; my son should have the same rights like any other human being in this world," relates Elizabeth Gomez. This subject is very important for our audience because the majority of non-English-speaking Hispanics are looking for information and guidance in their native language. During our project we were able to connect with various organizations focused on helping Hispanics with autistic children. This project had the capacity of organizing meetings and accomplished a direct connection with dozens of families that are commonly faced with these challenges. One of the most important lessons of this project was discovering help, finding the light at the end of the tunnel. We managed to find two organizations dedicated to improving the lives of these autistic young adults and their loved ones. These organizations are: Parents with Exceptional Kids and Wiley Speech and Language Center. Parents with Exceptional Kids support parents of autistic children with many services, such designing an Individualized Education Plan (IEP) for special needs students. This plan helps parents to involve the entire family into the support structure created for the autistic family member. These services are available in Spanish and are privately held on a one-on-one basis. There is also a monthly support group, which we attended, witnessing the commitment of the participants. Wiley Speech and Language Center has a program solely dedicated to integrating autistic young adults into society. It teaches them simple life routines like working, providing for themselves and independent living. The program places these autistic young adults in a classroom as their work environment. In these classrooms, autistic young adults care for younger children with autism. Many of these students respond favorably to the program. Some of the autistic young adults in this program expressed the possibility of predicting the behavior of the younger children with autism due to their previous experiences -- something that seems almost impossible for any expert. Sadly this program is one of the few dedicated to integrating these young adults with autism to our everyday lives. One particular challenge in this project is that I have an autistic young adult at home, and it was difficult not to get distracted by my personal experience. My son is soon turning 22, and that is the age when an autistic person no longer qualifies to receive government-funded education -- among other services -- directly from the public school system. His level of autism is at a moderate stage, which is considered not severe enough to get services and participate in special programs. Also, his IQ is not at a level where he can reach adult independence. Because I am able to speak and understand English, I have better access to information and programs than those parents who cannot speak English. Because of the cultural barriers and immigrant status, many Latino parents live in fear and do not engage in any social services. The project was intense and the product was positive, yet cruel for thousands of families and their special-needs children that lack the access to programs that can change the way they live their lives. The reaction from the community to our reporting was very positive. We managed to accomplish various workshops, reunions, and meetings with families and their autistic young adults. The two part story was aired on Telemundo, and also posted on the Telemundo website, NBC-Latino, Facebook, YouTube and Twitter. Engaging our audience was a very important aspect of our project. This was accomplished through a strategy to connect to our Latino community. We skillfully communicated with our audience through social media and informed them about community programs created to support parents and autistic young adults. Our project provided comprehensive information on how to deal with the issues facing us. However, we believe this project is not complete. We need to continue with the studies to close the gap between information and the families in need of this valuable information. I appreciate your comments and support. Our work to improve the quality of life for young adult autistics is constant and it's possible thanks to all of you. This article enlightened me on Autism. It is well researched and written. It has inspired me to do more research on the subject, which ultimately may get me involved in it. I knew you were a great one the first time we spoke. This story was comprehensive and very well done. It was also proactive and encouraging to families. Families are their child's best advocate and knowledge is power. Thank you for using your voice and your personal experience to reach so many. Thank you also for including our center in your story. Great reporting.
lemmas tendsto_cnj [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_cnj] and isCont_cnj [simp] = bounded_linear.isCont [OF bounded_linear_cnj] and continuous_cnj [simp, continuous_intros] = bounded_linear.continuous [OF bounded_linear_cnj] and continuous_on_cnj [simp, continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_cnj] and has_derivative_cnj [simp, derivative_intros] = bounded_linear.has_derivative [OF bounded_linear_cnj]
import GroundZero.Proto namespace GroundZero.Types universe u v theorem UIP {A : Type u} {a b : A} (p q : a = b) : p = q := begin rfl end section variable (A : Sort u) instance : @Reflexive A Eq := ⟨@Eq.refl A⟩ instance : @Symmetric A Eq := ⟨@Eq.symm A⟩ instance : @Transitive A Eq := ⟨@Eq.trans A⟩ end inductive Id {A : Type u} : A β†’ A β†’ Type u | refl {a : A} : Id a a infix:50 (priority := high) " = " => Id /- fails! hott theorem Id.UIP {A : Type u} {a b : A} (p q : a = b) : p = q := begin cases p; cases q; apply Id.refl end -/ @[match_pattern] abbrev idp {A : Type u} (a : A) : a = a := Id.refl attribute [eliminator] Id.casesOn hott def J₁ {A : Type u} {a : A} (B : Ξ  (b : A), a = b β†’ Type v) (Bidp : B a (idp a)) {b : A} (p : a = b) : B b p := @Id.casesOn A a B b p Bidp hott def Jβ‚‚ {A : Type u} {b : A} (B : Ξ  (a : A), a = b β†’ Type v) (Bidp : B b (idp b)) {a : A} (p : a = b) : B a p := by { induction p; apply Bidp } namespace Id hott def symm {A : Type u} {a b : A} (p : a = b) : b = a := begin induction p; apply idp end hott def trans {A : Type u} {a b c : A} (p : a = b) (q : b = c) : a = c := begin induction p; apply q end instance (A : Type u) : Reflexive (@Id A) := ⟨@Id.refl A⟩ instance (A : Type u) : Symmetric (@Id A) := ⟨@symm A⟩ instance (A : Type u) : Transitive (@Id A) := ⟨@trans A⟩ hott def inv {A : Type u} {a b : A} (p : a = b) : b = a := symm p infixl:60 " ⬝ " => trans postfix:max "⁻¹" => symm hott def JSymm {A : Type} {a b : A} (B : Ξ  x, b = x β†’ Type v) (p : a = b) (w : B b (idp b)) : J₁ B w p⁻¹ = Jβ‚‚ (Ξ» x q, B x q⁻¹) w p := begin induction p; reflexivity end hott def compInv {A : Type u} {a b : A} (p : a = b) : p ⬝ p⁻¹ = idp a := begin induction p; reflexivity end hott def invComp {A : Type u} {a b : A} (p : a = b) : p⁻¹ ⬝ p = idp b := begin induction p; reflexivity end hott def reflLeft {A : Type u} {a b : A} (p : a = b) : idp a ⬝ p = p := begin induction p; reflexivity end hott def reflRight {A : Type u} {a b : A} (p : a = b) : p ⬝ idp b = p := begin induction p; reflexivity end hott def reflTwice {A : Type u} {a b : A} (p : a = b) : idp a ⬝ p ⬝ idp b = p := begin induction p; reflexivity end hott def explodeInv {A : Type u} {a b c : A} (p : a = b) (q : b = c) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := begin induction p; induction q; reflexivity end hott def invInv {A : Type u} {a b : A} (p : a = b) : (p⁻¹)⁻¹ = p := begin induction p; reflexivity end hott def invEqIfEqInv {A : Type u} {a b : A} {p : a = b} {q : b = a} : p⁻¹ = q β†’ p = q⁻¹ := begin induction p; intro Ξ·; induction Ξ·; reflexivity end hott def eqEnvIfInvEq {A : Type u} {a b : A} {p : a = b} {q : b = a} : p = q⁻¹ β†’ p⁻¹ = q := Ξ» Ξ· => @invEqIfEqInv A b a p⁻¹ q⁻¹ (invInv p ⬝ Ξ·) ⬝ invInv q hott def assoc {A : Type u} {a b c d : A} (p : a = b) (q : b = c) (r : c = d) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := begin induction p; reflexivity end hott def mpr {A B : Type u} (p : A = B) : B β†’ A := begin induction p; intro x; exact x end hott def map {A : Type u} {B : Type v} {a b : A} (f : A β†’ B) (p : a = b) : f a = f b := begin induction p; reflexivity end hott def cancelCompInv {A : Type u} {a b c : A} (p : a = b) (q : b = c) : (p ⬝ q) ⬝ q⁻¹ = p := (assoc p q q⁻¹)⁻¹ ⬝ map (trans p) (compInv q) ⬝ (reflRight p) hott def cancelInvComp {A : Type u} {a b c : A} (p : a = b) (q : c = b) : (p ⬝ q⁻¹) ⬝ q = p := (assoc p q⁻¹ q)⁻¹ ⬝ map (trans p) (invComp q) ⬝ (reflRight p) hott def mapInv {A : Type u} {B : Type v} {a b : A} (f : A β†’ B) (p : a = b) : map f p⁻¹ = (map f p)⁻¹ := begin induction p; reflexivity end hott def transCancelLeft {A : Type u} {a b c : A} (r : a = b) (p q : b = c) : r ⬝ p = r ⬝ q β†’ p = q := begin intro ΞΌ; induction r; exact ΞΌ end hott def transCancelRight {A : Type u} {a b c : A} (r : b = c) (p q : a = b) : p ⬝ r = q ⬝ r β†’ p = q := begin intro ΞΌ; induction r; transitivity; { symmetry; apply reflRight }; symmetry; transitivity; { symmetry; apply reflRight }; exact μ⁻¹ end hott def idConjIfComm {A : Type u} {a : A} (p q : a = a) : p ⬝ q = q ⬝ p β†’ q⁻¹ ⬝ p ⬝ q = p := begin intro r; apply transCancelLeft q; transitivity; apply assoc; transitivity; apply map (Β· ⬝ q); transitivity; apply assoc; apply map (Β· ⬝ p); apply compInv; exact r end hott def compReflIfEq {A : Type u} {a b : A} (p q : a = b) : p = q β†’ p⁻¹ ⬝ q = idp b := begin intro A; induction A; apply invComp end section variable {A : Type u} {B : Type v} {a b : A} (f : A β†’ B) (p : a = b) def cong := map f p def ap := map f p end hott def apβ‚‚ {A : Type u} {B : Type v} {a b : A} {p q : a = b} (f : A β†’ B) (r : p = q) : ap f p = ap f q := ap (ap f) r class dotted (space : Type u) := (point : space) structure pointed := (space : Type u) (point : space) notation "Type⁎" => pointed def pointed.map (A B : Type⁎) := Ξ£ (f : A.space β†’ B.space), f A.point = B.point notation "Map⁎" => pointed.map namespace pointed.map variable {A B : Type⁎} (Ο† : Map⁎ A B) def ap : A.space β†’ B.space := Ο†.fst def id : Ο†.ap A.point = B.point := Ο†.snd end pointed.map def loopSpace (X : Type⁎) : Type⁎ := ⟨X.point = X.point, Id.refl⟩ hott def iteratedLoopSpace : Type⁎ β†’ β„• β†’ Type⁎ | X, 0 => X | X, n + 1 => iteratedLoopSpace (loopSpace X) n def loopPointedSpace (A : Type u) [dotted A] := iteratedLoopSpace ⟨A, dotted.point⟩ macro:max "Ξ©" n:superscript "(" Ο„:term ")" : term => do `((loopPointedSpace $Ο„ $(← Meta.Notation.parseSuperscript n)).space) macro:max "Θ" n:superscript "(" Ο„:term ")" : term => do `((iteratedLoopSpace $Ο„ $(← Meta.Notation.parseSuperscript n)).point) end Id def Not (A : Type u) : Type u := A β†’ (𝟎 : Type) def Neq {A : Type u} (a b : A) := Not (Id a b) namespace Not prefix:90 (priority := high) "Β¬" => Not infix:50 (priority := high) " β‰  " => Neq def absurd {A : Type u} {B : Type v} (h : A) (g : Β¬A) : B := nomatch (g h) def univ : (𝟎 : Type u) β†’ (𝟎 : Type v) := Ξ» e, nomatch e end Not namespace whiskering variable {A : Type u} {a b c : A} hott def rightWhs {p q : a = b} (Ξ½ : p = q) (r : b = c) : p ⬝ r = q ⬝ r := begin induction r; apply (Id.reflRight p) ⬝ Ξ½ ⬝ (Id.reflRight q)⁻¹ end infix:60 " ⬝ᡣ " => rightWhs hott def leftWhs {r s : b = c} (q : a = b) (ΞΊ : r = s) : q ⬝ r = q ⬝ s := begin induction q; exact (Id.reflLeft r) ⬝ ΞΊ ⬝ (Id.reflLeft s)⁻¹ end infix:60 " ⬝ₗ " => leftWhs variable {p q : a = b} {r s : b = c} hott def horizontalComp₁ (Ξ½ : p = q) (ΞΊ : r = s) := (Ξ½ ⬝ᡣ r) ⬝ (q ⬝ₗ ΞΊ) infix:65 " ⋆ " => horizontalComp₁ hott def horizontalCompβ‚‚ (Ξ½ : p = q) (ΞΊ : r = s) := (p ⬝ₗ ΞΊ) ⬝ (Ξ½ ⬝ᡣ s) infix:65 " ⋆′ " => horizontalCompβ‚‚ hott lemma compUniq (Ξ½ : p = q) (ΞΊ : r = s) : Ξ½ ⋆ ΞΊ = Ξ½ ⋆′ ΞΊ := begin induction p; induction r; induction Ξ½; induction ΞΊ; reflexivity end hott lemma loop₁ {A : Type u} {a : A} {Ξ½ ΞΊ : idp a = idp a} : Ξ½ ⬝ ΞΊ = Ξ½ ⋆ ΞΊ := begin apply Id.symm; transitivity; { apply Id.map (Β· ⬝ (Id.refl ⬝ ΞΊ ⬝ Id.refl)); apply Id.reflTwice }; apply Id.map (Ξ½ ⬝ Β·); apply Id.reflTwice end hott lemma loopβ‚‚ {A : Type u} {a : A} {Ξ½ ΞΊ : idp a = idp a} : Ξ½ ⋆′ ΞΊ = ΞΊ ⬝ Ξ½ := begin transitivity; { apply Id.map (Β· ⬝ (Id.refl ⬝ Ξ½ ⬝ Id.refl)); apply Id.reflTwice }; apply Id.map (ΞΊ ⬝ Β·); apply Id.reflTwice end hott theorem Β«Eckmann–Hilton argumentΒ» {A : Type u} {a : A} (Ξ½ ΞΊ : idp a = idp a) : Ξ½ ⬝ ΞΊ = ΞΊ ⬝ Ξ½ := loop₁ ⬝ compUniq Ξ½ ΞΊ ⬝ loopβ‚‚ end whiskering end GroundZero.Types
lemma residue_simple_pole: assumes "isolated_singularity_at f z0" assumes "is_pole f z0" "zorder f z0 = - 1" shows "residue f z0 = zor_poly f z0 z0"
lemma sgn_one [simp]: "sgn (1::'a::real_normed_algebra_1) = 1"
function S = read_mclust_t(tfilelist) % adapted from M-clust function LoadSpikes %------------------- % Check input type %------------------- if ~isa(tfilelist, 'cell') ft_error('LoadSpikes: tfilelist should be a cell-array.'); end nFiles = length(tfilelist); S = cell(nFiles, 1); for iF = 1:nFiles tfn = tfilelist{iF}; if ~isempty(tfn) try tfp = fopen_or_error(tfn, 'rb','b'); catch err warning([ 'Could not open tfile ' tfn]); continue end ReadHeader(tfp); S{iF} = fread(tfp,inf,'uint64'); S{iF} = double(S{iF}*100); fclose(tfp); end % if tfn valid end % for all files fprintf(2,'\n');
module Linalg where {-# LANGUAGE RankNTypes, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, AllowAmbiguousTypes, DataKinds, ScopedTypeVariables, #-} import Data.Matrix import Data.Bifunctor import qualified Data.Vector as V import qualified Data.List.Zipper as ZP import Data.Complex import qualified Data.List as DL import qualified Data.Set as DS import qualified Data.Map as DM import GHC.Float import Data.Maybe import Data.Euclidean subtr :: Num a => Matrix a -> Matrix a -> Matrix a subtr = elementwise (-) add :: Num a => Matrix a -> Matrix a -> Matrix a add = elementwise (+) norm2 :: Floating a => Matrix a -> a norm2 v = sqrt $ foldr (\x r -> x * x + r) 0 (toList v) norm2C :: RealFloat a => Matrix (Complex a) -> a norm2C v = sqrt $ foldr (\x r -> realPart (x * conjugate x) + r) 0 (toList v) getDiagonal :: Num a => Matrix a -> Matrix a getDiagonal m = diagonalList (nrows m) 0 $ V.toList $ getDiag m gershgorinCircles :: Num a => Matrix a -> [(a, a)] gershgorinCircles m = zip cs rs where cs = V.toList $ getDiag m diag = getDiagonal m rs = map (foldr (\x r -> abs x + r) 0) (toLists $ m `subtr` diag) outUnitCircle :: (Num a, Ord a) => Matrix a -> Bool outUnitCircle m = foldr (\(c, r) acc -> (abs c + r >= 1) || acc) False (gershgorinCircles m) {- Simple iteration method of solving linear equations systems. Complexity O(n^2) per iteration. -} simpleIteration :: (Floating a, Ord a) => [[a]] -> [[a]] -> a -> Either Int (Matrix a) simpleIteration m b = simpleIteration' (fromLists m) (fromLists b) simpleIteration' :: (Floating a, Ord a) => Matrix a -> Matrix a -> a -> Either Int (Matrix a) simpleIteration' m b eps = doIterations m' b (zero size 1) eps (outUnitCircle m) 0 where size = nrows m m' = identity size `subtr` m doIterations m b x eps outCircle cnt | outCircle && cnt == 20 = Left 0 | outCircle && norm2 x' >= norm2 x + 1 = doIterations m b x' eps outCircle (cnt + 1) | norm2 (x `subtr` x') < eps = Right x' | otherwise = doIterations m b x' eps outCircle 0 where x' = (m `multStd` x) `add` b lowerTriangle :: Num a => Matrix a -> Matrix a lowerTriangle m = mapPos (\(i, j) e -> if (size - i + 1) + j <= size + 1 then e else 0) m where size = nrows m upperTriangle :: Num a => Matrix a -> Matrix a upperTriangle m = transpose $ m' `subtr` diag where m' = lowerTriangle $ transpose m diag = getDiagonal m gaussPartial :: (Floating a, Ord a) => Matrix a -> Matrix a -> Matrix a gaussPartial m b = fromLists $ map (: []) (foldl gaussStep [] mlist) where m' = b <|> m mlist = toLists m' gaussStep ans row = ans ++ [xi] where coef = foldr (\e acc -> if e /= 0 && acc == 0 then e else acc) 0 row bi = head row row' = tail row sm = sum $ zipWith (*) ans row' xi = (bi - sm) / coef {- Gauss-Zeidel method of solving linear equations systems. Complexity O(n^2) per iteration. -} gaussZeidel :: (Floating a, Ord a) => [[a]] -> [[a]] -> a -> Either Int (Matrix a) gaussZeidel m b = gaussZeidel' (fromLists m) (fromLists b) gaussZeidel' :: (Floating a, Ord a) => Matrix a -> Matrix a -> a -> Either Int (Matrix a) gaussZeidel' m b eps = doGaussZeidel l negu b (zero size 1) eps (outUnitCircle m) 0 where size = nrows m l = lowerTriangle m negu = zero size size `subtr` upperTriangle m doGaussZeidel l negu b x eps outCircle cnt | outCircle && cnt == 20 = Left 0 | outCircle && norm2 x' >= norm2 x + 1 = doGaussZeidel l negu b x' eps outCircle (cnt + 1) | norm2 ((l `multStd` x) `subtr` b') < eps = Right x | otherwise = doGaussZeidel l negu b x' eps outCircle 0 where b' = (negu `multStd` x) `add` b x' = gaussPartial l b' {- Givens rotation of matrix. Complexity O(n). -} givensRotation :: Num a => [[a]] -> Int -> Int -> a -> a -> [[a]] givensRotation m i j c s = zipWith subst [1..] m where ui = m !! (i - 1) uj = m !! (j - 1) uinew = zipWith (\xi xj -> c * xi + s * xj) ui uj ujnew = zipWith (\xi xj -> (- s) * xi + c * xj) ui uj subst pos row | pos == i = uinew | pos == j = ujnew | otherwise = row trans :: [[a]] -> [[a]] trans = toLists . transpose . fromLists idMatrix :: Num a => Int -> [[a]] idMatrix sz = toLists $ identity sz firstNonzero :: (Num a, Ord a) => [a] -> Int -> Int firstNonzero v k = foldl (\acc (j, x) -> if j >= k && x /= 0 && acc == 0 then j else acc) 0 (zip [1..] v) appToPair f (x, y) = (f x, f y) {- Givens rotation method of QR decomposition. Complexity O(n^3). -} qrDecompGivens :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a) qrDecompGivens m = appToPair fromLists $ first trans qr where idm = idMatrix $ length m qr = foldl handler (idm, m) [1..(length m - 1)] handler (q, r) k | i == 0 = (q, r) | otherwise = (givensRotation q'' k i 0 1, givensRotation r'' k i 0 1) where col = trans r !! (k - 1) i = firstNonzero col k (q'', r'') = fst $ foldl handler' ((q, r), col !! (i - 1)) (zip [1..] col) handler' ((q', r'), xi) (j, xj) | j <= i = ((q', r'), xi) | otherwise = ((givensRotation q' j i c s, givensRotation r' j i c s), (- s) * xj + c * xi) where n = sqrt $ xi * xi + xj * xj c = xi / n s = (- xj) / n {- Householder matrix multiplication. Complexity O(n^2). -} multHouseholder :: Num a => [[a]] -> [[a]] -> [[a]] multHouseholder m' v' = toLists $ m `subtr` prod where m = fromLists m' v = fromLists v' vt = transpose v prod = scaleMatrix 2 v `multStd` (vt `multStd` m) {- Householder reflection method of QR decomposition. Complexity O(n^3). -} qrDecompHouseholder :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a) qrDecompHouseholder m = appToPair fromLists $ first trans qr where idm = idMatrix $ length m qr = foldl handler (idm, m) [1..(length m - 1)] handler (q, r) k | norm2 v' == 0 || u == e1 = (q, r) | otherwise = (multHouseholder q v, multHouseholder r v) where col = trans r !! (k - 1) v' = fromLists $ zipWith (\j x -> if j < k then [0] else [x]) [1..length col] col u = scaleMatrix (1 / norm2 v') v' e1 = mapPos (\(j, _) _-> if j == k then 1 else 0) v' v = toLists $ scaleMatrix (1 / norm2 (u `subtr` e1)) (u `subtr` e1) {- Simple iteration method of calculation the maximum modulo eigenvalue. Complexity O(n^2) per iteration. -} simpleIterationMaxEV :: RealFloat a => [[Complex a]] -> [[Complex a]] -> a -> Int -> Either Int (Complex a, Matrix (Complex a)) simpleIterationMaxEV m v = doItersMaxEV (fromLists m) (fromLists v) doItersMaxEV m x eps cnt | cnt == 0 = Left 0 | norm2C diff < eps = Right (ev, x) | otherwise = doItersMaxEV m x' eps (cnt - 1) where norm = norm2C (m `multStd` x) :+ 0 x' = scaleMatrix (1 / norm) (m `multStd` x) ev = head $ head $ toLists $ transpose x `multStd` (m `multStd` x) diff = (m `multStd` x) `subtr` scaleMatrix ev x {- QR-algorithm of calculation the matrix spectrum. Complexity O(n^3) per iteration. -} qrEV :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a) qrEV m eps = doItersQrEV m eps (identity $ length m) doItersQrEV m eps qk | lessEps = (evs, qk) | otherwise = doItersQrEV m' eps (qk `multStd` q) where (q, r) = qrDecompGivens m m' = toLists $ r `multStd` q circles = gershgorinCircles (fromLists m) lessEps = foldr (\(_, rd) acc -> (rd < eps) && acc) True circles evs = V.toList $ getDiag $ fromLists m multHouseholderRight :: Num a => [[a]] -> [[a]] -> [[a]] multHouseholderRight m' v' = toLists $ m `subtr` prod where m = fromLists m' v = fromLists v' vt = transpose v prod = scaleMatrix 2 ((m `multStd` v) `multStd` vt) {- Matrix transformation to tridiagonal form. Complexity O(n^3). -} getTridiagonal :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a) getTridiagonal m = appToPair fromLists $ second trans tridiag where idm = idMatrix $ length m tridiag = foldl handler (m, idm) [1..(length m - 1)] handler (a, q) k | norm2 v' == 0 || u == e1 = (a, q) | otherwise = (newa, newq) where col = trans a !! (k - 1) v' = fromLists $ zipWith (\j x -> if j <= k then [0] else [x]) [1..length col] col u = scaleMatrix (1 / norm2 v') v' e1 = mapPos (\(j, _) _-> if j == k + 1 then 1 else 0) v' v = toLists $ scaleMatrix (1 / norm2 (u `subtr` e1)) (u `subtr` e1) newa = multHouseholderRight (multHouseholder a v) v newq = multHouseholder q v cursorp :: ZP.Zipper a -> Int cursorp (ZP.Zip l _) = length l rightn :: Int -> ZP.Zipper a -> ZP.Zipper a rightn 0 z = z rightn n z = rightn (n - 1) (ZP.right z) givensRotationZ :: Num a => [ZP.Zipper a] -> Int -> Int -> a -> a -> [ZP.Zipper a] givensRotationZ m i j c s = zipWith subst [1..] m where ui = m !! (i - 1) uj = m !! (j - 1) curspUi = cursorp ui curspUj = cursorp uj uinew = rightn curspUi $ ZP.fromList $ zipWith (\xi xj -> c * xi + s * xj) (ZP.toList ui) (ZP.toList uj) ujnew = rightn curspUj $ ZP.fromList $ zipWith (\xi xj -> (- s) * xi + c * xj) (ZP.toList ui) (ZP.toList uj) subst pos row | pos == i = uinew | pos == j = ujnew | otherwise = row {- QR decomposition for the tridiagonal matrices. Complexity O(n^2). -} qrDecompTridiagonal :: (Floating a, Ord a) => [[a]] -> ([(Int, Int, a, a)], Matrix a) qrDecompTridiagonal m = second (fromLists . fmap ZP.toList) $ foldl handler ([], zipped_m) [1..(length m - 1)] where zipped_m = fmap ZP.fromList m handler (gs, r) k | n == 0 = (gs, r) | otherwise = ((k + 1, k, c, s) : gs, map ZP.right $ givensRotationZ r (k + 1) k c s) where col = map ZP.cursor r xi = col !! (k - 1) xj = col !! k n = sqrt $ xi * xi + xj * xj c = xi / n s = (- xj) / n multGivens :: Num a => [(Int, Int, a, a)] -> [[a]] -> [[a]] multGivens gs m = foldr (\(i, j, c, s) acc -> givensRotation acc i j c s) m gs {- QR-algorithm of calculation the matrix spectrum for the tridiagonal matrices. Complexity O(n^2) per iteration. -} qrEVTridiagonal :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a) qrEVTridiagonal m eps = second (transpose . fromLists) $ doItersQrEVsTridiagonal m eps (idMatrix $ length m) doItersQrEVsTridiagonal m eps qk | lessEps = (evs, qk) | otherwise = doItersQrEVsTridiagonal m' eps q where (gs, r) = qrDecompTridiagonal m m' = trans $ multGivens gs (trans $ toLists r) q = multGivens gs qk circles = gershgorinCircles (fromLists m) lessEps = foldr (\(_, rd) acc -> (rd < eps) && acc) True circles evs = V.toList $ getDiag $ fromLists m doItersQrEVsTridiagonalNTimes m cnt qk | cnt == 0 = (evs, qk) | otherwise = doItersQrEVsTridiagonalNTimes m' (cnt - 1) q where (gs, r) = qrDecompTridiagonal m m' = trans $ multGivens gs (trans $ toLists r) q = multGivens gs qk evs = V.toList $ getDiag $ fromLists m doItersQrMinEVTridiagonal m eps qk | radius < eps = (qk, m) | otherwise = doItersQrMinEVTridiagonal m' eps q where (gs, r) = qrDecompTridiagonal m m' = trans $ multGivens gs (trans $ toLists r) q = multGivens gs qk lastRow = last m radius = foldr (\x acc -> abs x + acc) 0 lastRow - abs (last lastRow) swapMinor :: Num a => Matrix a -> Matrix a -> Matrix a swapMinor minor m = m' `add` minor' where minorSz = nrows minor mSz = nrows m m' = mapPos (\(i, j) x -> if i <= minorSz && j <= minorSz then 0 else x) m minor' = extendTo 0 mSz mSz minor {- Wilkinson shifts QR-algorithm of calculation the matrix spectrum for the tridiagonal matrices. Complexity O(n^2) per iteration. -} qrEVShifts :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a) qrEVShifts mt eps = (evs, transpose q) where sz = length mt (q, d) = foldl handler (identity (length mt), fromLists mt) [0..sz - 2] evs = V.toList $ getDiag d handler (qk, m) k = (qt `multStd` qk, swapMinor r' m) where m' = submatrix 1 (sz - k) 1 (sz - k) m sz' = nrows m' lowerSq = submatrix (sz' - 1) sz' (sz' - 1) sz' m' maxIters = 20 s = head $ tail $ fst $ doItersQrEVsTridiagonalNTimes (toLists lowerSq) maxIters (idMatrix 2) m'' = m' `subtr` scaleMatrix s (identity sz') (qt, r) = first fromLists $ doItersQrMinEVTridiagonal (toLists m'') eps (idMatrix sz) r' = fromLists r `add` scaleMatrix s (identity sz') {- Test graphs on nonisomorphism. Complexity O(Time(qrEVShifts)). -} isomorphic :: (Floating a, Ord a) => [[a]] -> [[a]] -> Bool isomorphic g1 g2 | length g1 /= length g2 = False | otherwise = norm2 (g1Spec `subtr` g2Spec) <= 10 * eps where eps = 0.00001 g1' = toLists $ fst $ getTridiagonal g1 g2' = toLists $ fst $ getTridiagonal g2 g1Spec = fromLists $ map (: []) $ DL.sort $ fst $ qrEVShifts g1' eps g2Spec = fromLists $ map (: []) $ DL.sort $ fst $ qrEVShifts g2' eps getAdjMap :: Num a => Int -> DM.Map Int (DM.Map Int a) getAdjMap n = adjMap where buildRow = DM.fromList $ map (\k -> (k, 0)) [0..n - 1] adjMap = DM.fromList $ map (\k -> (k, buildRow)) [0..n - 1] addEdge (x, y) = DM.update (Just . DM.update (Just . (+ 1)) y) x buildAdjMatrix :: Num a => Int -> (Int -> DM.Map Int (DM.Map Int a) -> DM.Map Int (DM.Map Int a)) -> Matrix a buildAdjMatrix n genEdges = m where adjMap = getAdjMap n adjMap' = foldr genEdges adjMap [0..n - 1] m = matrix n n fill fill (i, j) = x where i' = i - 1 j' = j - 1 x = fromJust $ DM.lookup (j - 1) $ fromJust $ DM.lookup (i - 1) adjMap' buildGraph1 :: Int -> Matrix Double buildGraph1 n = buildAdjMatrix (n * n) genEdges where genEdges x = foldr (\y acc -> genEdges' (x, y) . acc) id [0..n - 1] genEdges' (x, y) | x >= n = id | otherwise = addEdge (v, u1) . addEdge (v, u2) . addEdge (v, u3) . addEdge (v, u4) . addEdge (v, u5) . addEdge (v, u6) . addEdge (v, u7) . addEdge (v, u8) where x1 = (x + 2 * y) `mod` n x2 = (x - 2 * y + 3 * n) `mod` n x3 = (x + 2 * y + 1) `mod` n x4 = (x - 2 * y - 1 + 3 * n) `mod` n y1 = (y + 2 * x) `mod` n y2 = (y - 2 * x + 3 * n) `mod` n y3 = (y + 2 * x + 1) `mod` n y4 = (y - 2 * x - 1 + 3 * n) `mod` n u1 = x1 * n + y u2 = x2 * n + y u3 = x3 * n + y u4 = x4 * n + y u5 = x * n + y1 u6 = x * n + y2 u7 = x * n + y3 u8 = x * n + y4 v = x * n + y inv :: Int -> Int -> Int inv x md = ((xinv `mod` md) + md) `mod` md where xinv = snd $ gcdExt x md buildGraph2 :: Int -> Matrix Double buildGraph2 p = buildAdjMatrix (p + 1) genEdges where genEdges x | x == p = addEdge (x, xInv) . addEdge (x, x) . addEdge (x, x) | otherwise = addEdge (x, xInv) . addEdge (x, x1) . addEdge (x, x2) where xInv | x == 0 = p | x == p = 0 | otherwise = inv x p x1 = (x + 1) `mod` p x2 = (x - 1 + p) `mod` p {- Calculation the optimal alpha for expander. Complexity O(Time(qrEVShifts)). -} expanderAlpha :: Int -> Matrix Double -> Double -> Double expanderAlpha n g d = max (abs ev1) (abs ev2) / d where eps = 0.00001 evs = fst $ qrEVShifts (toLists $ fst $ getTridiagonal $ toLists g) eps sortedEVs = reverse $ DL.sort evs ev1 = head $ tail sortedEVs ev2 = last sortedEVs expanderAlpha1 :: Int -> Double expanderAlpha1 n = expanderAlpha n g 8 where g = buildGraph1 n expanderAlpha2 :: Int -> Double expanderAlpha2 n = expanderAlpha (n + 1) g 3 where g = buildGraph2 n
-- | -- Module: Optics.Each.Core -- Description: An 'IxTraversal' for each element of a (potentially monomorphic) container. -- -- This module defines the 'Each' class, which provides an 'IxTraversal' that -- extracts 'each' element of a (potentially monomorphic) container. -- -- Note that orphan instances for this class are defined in the @Optics.Each@ -- module from @optics-extra@, so if you are not simply depending on @optics@ -- you may wish to import that module instead. -- {-# LANGUAGE UndecidableInstances #-} module Optics.Each.Core ( -- * Each Each(..) ) where import Data.Array import Data.Complex import Data.Functor.Identity import Data.IntMap as IntMap import Data.List.NonEmpty import Data.Map as Map import Data.Sequence as Seq import Data.Tree as Tree import Optics.IxTraversal -- | Extract 'each' element of a (potentially monomorphic) container. -- -- >>> over each (*10) (1,2,3) -- (10,20,30) -- -- >>> iover each (\i a -> a*10 + succ i) (1,2,3) -- (11,22,33) -- class Each i s t a b | s -> i a, t -> i b, s b -> t, t a -> s where each :: IxTraversal i s t a b default each :: (TraversableWithIndex i g, s ~ g a, t ~ g b) => IxTraversal i s t a b each = itraversed {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a) (b, b) a b@ instance (a ~ a1, b ~ b1 ) => Each Int (a, a1) (b, b1) a b where each = itraversalVL $ \f (a0, a1) -> (,) <$> f 0 a0 <*> f 1 a1 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a) (b, b, b) a b@ instance (a ~ a1, a ~ a2, b ~ b1, b ~ b2 ) => Each Int (a, a1, a2) (b, b1, b2) a b where each = itraversalVL $ \f (a0, a1, a2) -> (,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a) (b, b, b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, b ~ b1, b ~ b2, b ~ b3 ) => Each Int (a, a1, a2, a3) (b, b1, b2, b3) a b where each = itraversalVL $ \f (a0, a1, a2, a3) -> (,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a) (b, b, b, b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, b ~ b1, b ~ b2, b ~ b3, b ~ b4 ) => Each Int (a, a1, a2, a3, a4) (b, b1, b2, b3, b4) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4) -> (,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a, a) (b, b, b, b, b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, a ~ a5, b ~ b1, b ~ b2, b ~ b3, b ~ b4, b ~ b5 ) => Each Int (a, a1, a2, a3, a4, a5) (b, b1, b2, b3, b4, b5) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4, a5) -> (,,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 <*> f 5 a5 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a, a, a) (b, b, b, b, b, b, b) -- a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, a ~ a5, a ~ a6, b ~ b1, b ~ b2, b ~ b3, b ~ b4, b ~ b5, b ~ b6 ) => Each Int (a, a1, a2, a3, a4, a5, a6) (b, b1, b2, b3, b4, b5, b6) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4, a5, a6) -> (,,,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 <*> f 5 a5 <*> f 6 a6 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a, a, a, a) (b, b, b, b, b, b, -- b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, a ~ a5, a ~ a6, a ~ a7, b ~ b1, b ~ b2, b ~ b3, b ~ b4, b ~ b5, b ~ b6, b ~ b7 ) => Each Int (a, a1, a2, a3, a4, a5, a6, a7) (b, b1, b2, b3, b4, b5, b6, b7) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4, a5, a6, a7) -> (,,,,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 <*> f 5 a5 <*> f 6 a6 <*> f 7 a7 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a, a, a, a, a) (b, b, b, b, b, -- b, b, b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, a ~ a5, a ~ a6, a ~ a7, a ~ a8, b ~ b1, b ~ b2, b ~ b3, b ~ b4, b ~ b5, b ~ b6, b ~ b7, b ~ b8 ) => Each Int (a, a1, a2, a3, a4, a5, a6, a7, a8) (b, b1, b2, b3, b4, b5, b6, b7, b8) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4, a5, a6, a7, a8) -> (,,,,,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 <*> f 5 a5 <*> f 6 a6 <*> f 7 a7 <*> f 8 a8 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' (a, a, a, a, a, a, a, a, a, a) (b, b, b, b, -- b, b, b, b, b, b) a b@ instance (a ~ a1, a ~ a2, a ~ a3, a ~ a4, a ~ a5, a ~ a6, a ~ a7, a ~ a8, a ~ a9, b ~ b1, b ~ b2, b ~ b3, b ~ b4, b ~ b5, b ~ b6, b ~ b7, b ~ b8, b ~ b9 ) => Each Int (a, a1, a2, a3, a4, a5, a6, a7, a8, a9) (b, b1, b2, b3, b4, b5, b6, b7, b8, b9) a b where each = itraversalVL $ \f (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) -> (,,,,,,,,,) <$> f 0 a0 <*> f 1 a1 <*> f 2 a2 <*> f 3 a3 <*> f 4 a4 <*> f 5 a5 <*> f 6 a6 <*> f 7 a7 <*> f 8 a8 <*> f 9 a9 {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' ('Either' () ()) ('Either' a a) ('Either' b b) a -- b@ instance (a ~ a', b ~ b' ) => Each (Either () ()) (Either a a') (Either b b') a b where each = itraversalVL $ \f -> \case Left a -> Left <$> f (Left ()) a Right a -> Right <$> f (Right ()) a {-# INLINE[1] each #-} -- | @'each' :: ('RealFloat' a, 'RealFloat' b) => 'IxTraversal' (Either () ()) -- ('Complex' a) ('Complex' b) a b@ instance Each (Either () ()) (Complex a) (Complex b) a b where each = itraversalVL $ \f (a :+ b) -> (:+) <$> f (Left ()) a <*> f (Right ()) b {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' k ('Map' k a) ('Map' k b) a b@ instance k ~ k' => Each k (Map k a) (Map k' b) a b where -- traverseWithKey has best performance for all flavours for some reason. each = itraversalVL Map.traverseWithKey {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' ('IntMap' a) ('IntMap' b) a b@ instance Each Int (IntMap a) (IntMap b) a b where -- traverseWithKey has best performance for all flavours for some reason. each = itraversalVL IntMap.traverseWithKey {-# INLINE[1] each #-} -- | @'each' :: 'IxTraversal' 'Int' [a] [b] a b@ instance Each Int [a] [b] a b -- | @'each' :: 'IxTraversal' 'Int' (NonEmpty a) (NonEmpty b) a b@ instance Each Int (NonEmpty a) (NonEmpty b) a b -- | @'each' :: 'IxTraversal' () ('Identity' a) ('Identity' b) a b@ instance Each () (Identity a) (Identity b) a b -- | @'each' :: 'IxTraversal' () ('Maybe' a) ('Maybe' b) a b@ instance Each () (Maybe a) (Maybe b) a b -- | @'each' :: 'IxTraversal' 'Int' ('Seq' a) ('Seq' b) a b@ instance Each Int (Seq a) (Seq b) a b -- | @'each' :: 'IxTraversal' [Int] ('Tree' a) ('Tree' b) a b@ instance Each [Int] (Tree a) (Tree b) a b -- | @'each' :: 'Ix' i => 'IxTraversal' i ('Array' i a) ('Array' i b) a b@ instance (Ix i, i ~ j) => Each i (Array i a) (Array j b) a b -- $setup -- >>> import Optics.Core
myTestRule { # This microservice is deprecated #Input parameters are: # Collection path name # Destination resource name for replicas # Option string containing # all - # irodsAdmin - for administrator initiated replication # backupMode - will not throw an error if a good copy # already exists #Output parameter is: # Status # Output from running the example is: # Replicate collection /tempZone/home/rods/sub1 to location destRescName=testResc # Put a file in the collection msiDataObjPut(*Path,*Resource,"localPath=*LocalFile++++forceFlag=",*Status); msiSplitPath(*Path, *Coll, *File); #Replicate the collection msiReplColl(*Coll,*Dest,*Flag,*Status); writeLine("stdout","Replicate collection *Coll to location *Dest"); } INPUT *Path="/tempZone/home/rods/sub1/foo1",*Resource="demoResc", *Dest="testResc", *LocalFile="foo1", *Flag="backupMode" OUTPUT ruleExecOut
Damage Indicators Mod adds a damage indicator, and health bar to Minecraft making it absolutely more playable and have more immersion into it. This mod adds an RPG-ish vibe into the game as it enables the players to see the damage he has done to the enemy and the damage the enemy has done to them. This mod is customizable through its settings and also includes a small portrait of the enemy you are currently fighting as well. This makes Minecraft look like a better role-playing game so you can now determine how much damage you are doing to the monster at the same time you can now monitor how much health the mobs have left. If you love this pack and want to have more in the future, you can show your love to Damage Indicators Mod. You can check his Youtube Channel to support him. You can check more PVP packs over here. How to Install Damage Indicators Mod? If you don’t know how to install the Damage Indicators Mod just look below, we’ll provide you with a short tutorial there. This installation guide should work with all Minecraft versions. To see the Official Download Links just scroll down.
State Before: a b d : Int hda : d ∣ a hdb : d ∣ b h : a / d = b / d ⊒ a = b State After: no goals Tactic: rw [← Int.mul_ediv_cancel' hda, ← Int.mul_ediv_cancel' hdb, h]
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Mario Carneiro, Yury Kudryashov -/ import topology.algebra.order.basic import topology.extend_from /-! # Lemmas about `extend_from` in an order topology. -/ open filter set topological_space open_locale topological_space classical universes u v variables {Ξ± : Type u} {Ξ² : Type v} lemma continuous_on_Icc_extend_from_Ioo [topological_space Ξ±] [linear_order Ξ±] [densely_ordered Ξ±] [order_topology Ξ±] [topological_space Ξ²] [regular_space Ξ²] {f : Ξ± β†’ Ξ²} {a b : Ξ±} {la lb : Ξ²} (hab : a β‰  b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (𝓝[>] a) (𝓝 la)) (hb : tendsto f (𝓝[<] b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Icc a b) := begin apply continuous_on_extend_from, { rw closure_Ioo hab }, { intros x x_in, rcases eq_endpoints_or_mem_Ioo_of_mem_Icc x_in with rfl | rfl | h, { exact ⟨la, ha.mono_left $ nhds_within_mono _ Ioo_subset_Ioi_self⟩ }, { exact ⟨lb, hb.mono_left $ nhds_within_mono _ Ioo_subset_Iio_self⟩ }, { use [f x, hf x h] } } end lemma eq_lim_at_left_extend_from_Ioo [topological_space Ξ±] [linear_order Ξ±] [densely_ordered Ξ±] [order_topology Ξ±] [topological_space Ξ²] [t2_space Ξ²] {f : Ξ± β†’ Ξ²} {a b : Ξ±} {la : Ξ²} (hab : a < b) (ha : tendsto f (𝓝[>] a) (𝓝 la)) : extend_from (Ioo a b) f a = la := begin apply extend_from_eq, { rw closure_Ioo hab.ne, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma eq_lim_at_right_extend_from_Ioo [topological_space Ξ±] [linear_order Ξ±] [densely_ordered Ξ±] [order_topology Ξ±] [topological_space Ξ²] [t2_space Ξ²] {f : Ξ± β†’ Ξ²} {a b : Ξ±} {lb : Ξ²} (hab : a < b) (hb : tendsto f (𝓝[<] b) (𝓝 lb)) : extend_from (Ioo a b) f b = lb := begin apply extend_from_eq, { rw closure_Ioo hab.ne, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma continuous_on_Ico_extend_from_Ioo [topological_space Ξ±] [linear_order Ξ±] [densely_ordered Ξ±] [order_topology Ξ±] [topological_space Ξ²] [regular_space Ξ²] {f : Ξ± β†’ Ξ²} {a b : Ξ±} {la : Ξ²} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (𝓝[>] a) (𝓝 la)) : continuous_on (extend_from (Ioo a b) f) (Ico a b) := begin apply continuous_on_extend_from, { rw [closure_Ioo hab.ne], exact Ico_subset_Icc_self, }, { intros x x_in, rcases eq_left_or_mem_Ioo_of_mem_Ico x_in with rfl | h, { use la, simpa [hab] }, { use [f x, hf x h] } } end lemma continuous_on_Ioc_extend_from_Ioo [topological_space Ξ±] [linear_order Ξ±] [densely_ordered Ξ±] [order_topology Ξ±] [topological_space Ξ²] [regular_space Ξ²] {f : Ξ± β†’ Ξ²} {a b : Ξ±} {lb : Ξ²} (hab : a < b) (hf : continuous_on f (Ioo a b)) (hb : tendsto f (𝓝[<] b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Ioc a b) := begin have := @continuous_on_Ico_extend_from_Ioo (order_dual Ξ±) _ _ _ _ _ _ _ f _ _ _ hab, erw [dual_Ico, dual_Ioi, dual_Ioo] at this, exact this hf hb end
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes ! This file was ported from Lean 3 source module data.nat.multiplicity ! leanprover-community/mathlib commit 290a7ba01fbcab1b64757bdaa270d28f4dcede35 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.BigOperators.Intervals import Mathbin.Algebra.GeomSum import Mathbin.Data.Nat.Bitwise import Mathbin.Data.Nat.Log import Mathbin.Data.Nat.Parity import Mathbin.Data.Nat.Prime import Mathbin.RingTheory.Multiplicity /-! # Natural number multiplicity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `nat.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n/p + ... + n/p^b` for any `b` such that `n/p^(b + 1) = 0`. * `nat.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `nat.multiplicity_choose`: The multiplicity of `p` in `n.choose k` is the number of carries when `k` and`n - k` are added in base `p`. ## Other declarations * `nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `nat.prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p β‰  1` and other trivialities, along with translating between `prime` and `nat.prime`. ## Tags Legendre, p-adic -/ open Finset Nat multiplicity open BigOperators Nat namespace Nat /- warning: nat.multiplicity_eq_card_pow_dvd -> Nat.multiplicity_eq_card_pow_dvd is a dubious translation: lean 3 declaration is forall {m : Nat} {n : Nat} {b : Nat}, (Ne.{1} Nat m (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) -> (LT.lt.{0} Nat Nat.hasLt (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) n) -> (LT.lt.{0} Nat Nat.hasLt (Nat.log m n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) m n) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => Dvd.Dvd.{0} Nat Nat.hasDvd (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) m i) n) (fun (a : Nat) => Nat.decidableDvd (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) m a) n) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b))))) but is expected to have type forall {m : Nat} {n : Nat} {b : Nat}, (Ne.{1} Nat m (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) -> (LT.lt.{0} Nat instLTNat (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) n) -> (LT.lt.{0} Nat instLTNat (Nat.log m n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) m n) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => Dvd.dvd.{0} Nat Nat.instDvdNat (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) m i) n) (fun (a : Nat) => Nat.decidable_dvd (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) m a) n) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b))))) Case conversion may be inaccurate. Consider using '#align nat.multiplicity_eq_card_pow_dvd Nat.multiplicity_eq_card_pow_dvdβ‚“'. -/ /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ theorem multiplicity_eq_card_pow_dvd {m n b : β„•} (hm : m β‰  1) (hn : 0 < n) (hb : log m n < b) : multiplicity m n = ↑((Finset.Ico 1 b).filterβ‚“ fun i => m ^ i ∣ n).card := calc multiplicity m n = ↑(Ico 1 <| (multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1).card := by simp _ = ↑((Finset.Ico 1 b).filterβ‚“ fun i => m ^ i ∣ n).card := congr_arg coe <| congr_arg card <| Finset.ext fun i => by rw [mem_filter, mem_Ico, mem_Ico, lt_succ_iff, ← @PartENat.coe_le_coe i, PartENat.natCast_get, ← pow_dvd_iff_le_multiplicity, and_right_comm] refine' (and_iff_left_of_imp fun h => lt_of_le_of_lt _ hb).symm cases m Β· rw [zero_pow, zero_dvd_iff] at h exacts[(hn.ne' h.2).elim, h.1] exact le_log_of_pow_le (one_lt_iff_ne_zero_and_ne_one.2 ⟨m.succ_ne_zero, hm⟩) (le_of_dvd hn h.2) #align nat.multiplicity_eq_card_pow_dvd Nat.multiplicity_eq_card_pow_dvd namespace Prime /- warning: nat.prime.multiplicity_one -> Nat.Prime.multiplicity_one is a dubious translation: lean 3 declaration is forall {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) (OfNat.ofNat.{0} PartENat 0 (OfNat.mk.{0} PartENat 0 (Zero.zero.{0} PartENat PartENat.hasZero)))) but is expected to have type forall {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) (OfNat.ofNat.{0} PartENat 0 (Zero.toOfNat0.{0} PartENat PartENat.instZeroPartENat))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_one Nat.Prime.multiplicity_oneβ‚“'. -/ theorem multiplicity_one {p : β„•} (hp : p.Prime) : multiplicity p 1 = 0 := multiplicity.one_right hp.Prime.not_unit #align nat.prime.multiplicity_one Nat.Prime.multiplicity_one /- warning: nat.prime.multiplicity_mul -> Nat.Prime.multiplicity_mul is a dubious translation: lean 3 declaration is forall {p : Nat} {m : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat Nat.hasMul) m n)) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p m) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p n))) but is expected to have type forall {p : Nat} {m : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat instMulNat) m n)) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p m) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p n))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_mul Nat.Prime.multiplicity_mulβ‚“'. -/ theorem multiplicity_mul {p m n : β„•} (hp : p.Prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul hp.Prime #align nat.prime.multiplicity_mul Nat.Prime.multiplicity_mul /- warning: nat.prime.multiplicity_pow -> Nat.Prime.multiplicity_pow is a dubious translation: lean 3 declaration is forall {p : Nat} {m : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) m n)) (SMul.smul.{0, 0} Nat PartENat (AddMonoid.SMul.{0} PartENat (AddMonoidWithOne.toAddMonoid.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))) n (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p m))) but is expected to have type forall {p : Nat} {m : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) m n)) (HSMul.hSMul.{0, 0, 0} Nat PartENat PartENat (instHSMul.{0, 0} Nat PartENat (AddMonoid.SMul.{0} PartENat (AddMonoidWithOne.toAddMonoid.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)))) n (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p m))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_pow Nat.Prime.multiplicity_powβ‚“'. -/ theorem multiplicity_pow {p m n : β„•} (hp : p.Prime) : multiplicity p (m ^ n) = n β€’ multiplicity p m := multiplicity.pow hp.Prime #align nat.prime.multiplicity_pow Nat.Prime.multiplicity_pow /- warning: nat.prime.multiplicity_self -> Nat.Prime.multiplicity_self is a dubious translation: lean 3 declaration is forall {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p p) (OfNat.ofNat.{0} PartENat 1 (OfNat.mk.{0} PartENat 1 (One.one.{0} PartENat PartENat.hasOne)))) but is expected to have type forall {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p p) (OfNat.ofNat.{0} PartENat 1 (One.toOfNat1.{0} PartENat PartENat.instOnePartENat))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_self Nat.Prime.multiplicity_selfβ‚“'. -/ theorem multiplicity_self {p : β„•} (hp : p.Prime) : multiplicity p p = 1 := multiplicity_self hp.Prime.not_unit hp.NeZero #align nat.prime.multiplicity_self Nat.Prime.multiplicity_self /- warning: nat.prime.multiplicity_pow_self -> Nat.Prime.multiplicity_pow_self is a dubious translation: lean 3 declaration is forall {p : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p n)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) n)) but is expected to have type forall {p : Nat} {n : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p n)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) n)) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_pow_self Nat.Prime.multiplicity_pow_selfβ‚“'. -/ theorem multiplicity_pow_self {p n : β„•} (hp : p.Prime) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.NeZero hp.Prime.not_unit n #align nat.prime.multiplicity_pow_self Nat.Prime.multiplicity_pow_self /- warning: nat.prime.multiplicity_factorial -> Nat.Prime.multiplicity_factorial is a dubious translation: lean 3 declaration is forall {p : Nat}, (Nat.Prime p) -> (forall {n : Nat} {b : Nat}, (LT.lt.{0} Nat Nat.hasLt (Nat.log p n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial n)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) n (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)))))) but is expected to have type forall {p : Nat}, (Nat.Prime p) -> (forall {n : Nat} {b : Nat}, (LT.lt.{0} Nat instLTNat (Nat.log p n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial n)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) n (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)))))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_factorial Nat.Prime.multiplicity_factorialβ‚“'. -/ /-- **Legendre's Theorem** The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem multiplicity_factorial {p : β„•} (hp : p.Prime) : βˆ€ {n b : β„•}, log p n < b β†’ multiplicity p n ! = (βˆ‘ i in Ico 1 b, n / p ^ i : β„•) | 0, b, hb => by simp [Ico, hp.multiplicity_one] | n + 1, b, hb => calc multiplicity p (n + 1)! = multiplicity p n ! + multiplicity p (n + 1) := by rw [factorial_succ, hp.multiplicity_mul, add_comm] _ = (βˆ‘ i in Ico 1 b, n / p ^ i : β„•) + ((Finset.Ico 1 b).filterβ‚“ fun i => p ^ i ∣ n + 1).card := by rw [multiplicity_factorial ((log_mono_right <| le_succ _).trans_lt hb), ← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] _ = (βˆ‘ i in Ico 1 b, n / p ^ i + if p ^ i ∣ n + 1 then 1 else 0 : β„•) := by rw [sum_add_distrib, sum_boole] simp _ = (βˆ‘ i in Ico 1 b, (n + 1) / p ^ i : β„•) := congr_arg coe <| Finset.sum_congr rfl fun _ _ => (succ_div _ _).symm #align nat.prime.multiplicity_factorial Nat.Prime.multiplicity_factorial /- warning: nat.prime.multiplicity_factorial_mul_succ -> Nat.Prime.multiplicity_factorial_mul_succ is a dubious translation: lean 3 declaration is forall {n : Nat} {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat Nat.hasMul) p (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) n (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))))))) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat Nat.hasMul) p n))) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) n (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))))) (OfNat.ofNat.{0} PartENat 1 (OfNat.mk.{0} PartENat 1 (One.one.{0} PartENat PartENat.hasOne))))) but is expected to have type forall {n : Nat} {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat instMulNat) p (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) n (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)))))) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat instMulNat) p n))) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) n (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))))) (OfNat.ofNat.{0} PartENat 1 (One.toOfNat1.{0} PartENat PartENat.instOnePartENat)))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_factorial_mul_succ Nat.Prime.multiplicity_factorial_mul_succβ‚“'. -/ /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ theorem multiplicity_factorial_mul_succ {n p : β„•} (hp : p.Prime) : multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 := by have hp' := hp.prime have h0 : 2 ≀ p := hp.two_le have h1 : 1 ≀ p * n + 1 := Nat.le_add_left _ _ have h2 : p * n + 1 ≀ p * (n + 1) linarith have h3 : p * n + 1 ≀ p * (n + 1) + 1 linarith have hm : multiplicity p (p * n)! β‰  ⊀ := by rw [Ne.def, eq_top_iff_not_finite, Classical.not_not, finite_nat_iff] exact ⟨hp.ne_one, factorial_pos _⟩ revert hm have h4 : βˆ€ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0 := by intro m hm rw [multiplicity_eq_zero, ← not_dvd_iff_between_consec_multiples _ hp.pos] rw [mem_Ico] at hm exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ simp_rw [← prod_Ico_id_eq_factorial, multiplicity.Finset.prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc] intro h rw [PartENat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp', hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm (1 : PartENat)] #align nat.prime.multiplicity_factorial_mul_succ Nat.Prime.multiplicity_factorial_mul_succ /- warning: nat.prime.multiplicity_factorial_mul -> Nat.Prime.multiplicity_factorial_mul is a dubious translation: lean 3 declaration is forall {n : Nat} {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat Nat.hasMul) p n))) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial n)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) n))) but is expected to have type forall {n : Nat} {p : Nat}, (Nat.Prime p) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat instMulNat) p n))) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial n)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) n))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_factorial_mul Nat.Prime.multiplicity_factorial_mulβ‚“'. -/ /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ theorem multiplicity_factorial_mul {n p : β„•} (hp : p.Prime) : multiplicity p (p * n)! = multiplicity p n ! + n := by induction' n with n ih Β· simp Β· simp only [succ_eq_add_one, multiplicity.mul, hp, hp.prime, ih, multiplicity_factorial_mul_succ, ← add_assoc, Nat.cast_one, Nat.cast_add, factorial_succ] congr 1 rw [add_comm, add_assoc] #align nat.prime.multiplicity_factorial_mul Nat.Prime.multiplicity_factorial_mul #print Nat.Prime.pow_dvd_factorial_iff /- /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ theorem pow_dvd_factorial_iff {p : β„•} {n r b : β„•} (hp : p.Prime) (hbn : log p n < b) : p ^ r ∣ n ! ↔ r ≀ βˆ‘ i in Ico 1 b, n / p ^ i := by rw [← PartENat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] #align nat.prime.pow_dvd_factorial_iff Nat.Prime.pow_dvd_factorial_iff -/ /- warning: nat.prime.multiplicity_factorial_le_div_pred -> Nat.Prime.multiplicity_factorial_le_div_pred is a dubious translation: lean 3 declaration is forall {p : Nat}, (Nat.Prime p) -> (forall (n : Nat), LE.le.{0} PartENat PartENat.hasLe (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.factorial n)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) n (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) p (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))))))) but is expected to have type forall {p : Nat}, (Nat.Prime p) -> (forall (n : Nat), LE.le.{0} PartENat PartENat.instLEPartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.factorial n)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) (HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) n (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) p (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)))))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_factorial_le_div_pred Nat.Prime.multiplicity_factorial_le_div_predβ‚“'. -/ theorem multiplicity_factorial_le_div_pred {p : β„•} (hp : p.Prime) (n : β„•) : multiplicity p n ! ≀ (n / (p - 1) : β„•) := by rw [hp.multiplicity_factorial (lt_succ_self _), PartENat.coe_le_coe] exact Nat.geom_sum_Ico_le hp.two_le _ _ #align nat.prime.multiplicity_factorial_le_div_pred Nat.Prime.multiplicity_factorial_le_div_pred /- warning: nat.prime.multiplicity_choose_aux -> Nat.Prime.multiplicity_choose_aux is a dubious translation: lean 3 declaration is forall {p : Nat} {n : Nat} {b : Nat} {k : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat Nat.hasLe k n) -> (Eq.{1} Nat (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) n (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i))) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i))) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)))) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => LE.le.{0} Nat Nat.hasLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)))) (fun (a : Nat) => Nat.decidableLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a)))) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b))))) but is expected to have type forall {p : Nat} {n : Nat} {b : Nat} {k : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat instLENat k n) -> (Eq.{1} Nat (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) n (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i))) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i))) (Finset.sum.{0, 0} Nat Nat Nat.addCommMonoid (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b) (fun (i : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)))) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => LE.le.{0} Nat instLENat (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)))) (fun (a : Nat) => Nat.decLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a)))) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b))))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_choose_aux Nat.Prime.multiplicity_choose_auxβ‚“'. -/ theorem multiplicity_choose_aux {p n b k : β„•} (hp : p.Prime) (hkn : k ≀ n) : (βˆ‘ i in Finset.Ico 1 b, n / p ^ i) = ((βˆ‘ i in Finset.Ico 1 b, k / p ^ i) + βˆ‘ i in Finset.Ico 1 b, (n - k) / p ^ i) + ((Finset.Ico 1 b).filterβ‚“ fun i => p ^ i ≀ k % p ^ i + (n - k) % p ^ i).card := calc (βˆ‘ i in Finset.Ico 1 b, n / p ^ i) = βˆ‘ i in Finset.Ico 1 b, (k + (n - k)) / p ^ i := by simp only [add_tsub_cancel_of_le hkn] _ = βˆ‘ i in Finset.Ico 1 b, k / p ^ i + (n - k) / p ^ i + if p ^ i ≀ k % p ^ i + (n - k) % p ^ i then 1 else 0 := by simp only [Nat.add_div (pow_pos hp.pos _)] _ = _ := by simp [sum_add_distrib, sum_boole] #align nat.prime.multiplicity_choose_aux Nat.Prime.multiplicity_choose_aux /- warning: nat.prime.multiplicity_choose -> Nat.Prime.multiplicity_choose is a dubious translation: lean 3 declaration is forall {p : Nat} {n : Nat} {k : Nat} {b : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat Nat.hasLe k n) -> (LT.lt.{0} Nat Nat.hasLt (Nat.log p n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.choose n k)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => LE.le.{0} Nat Nat.hasLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p i)))) (fun (a : Nat) => Nat.decidableLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.hasMod) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p a)))) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring))) Nat.locallyFiniteOrder (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne))) b))))) but is expected to have type forall {p : Nat} {n : Nat} {k : Nat} {b : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat instLENat k n) -> (LT.lt.{0} Nat instLTNat (Nat.log p n) b) -> (Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.choose n k)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) (Finset.card.{0} Nat (Finset.filter.{0} Nat (fun (i : Nat) => LE.le.{0} Nat instLENat (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p i)))) (fun (a : Nat) => Nat.decLe (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a)) (HMod.hMod.{0, 0, 0} Nat Nat Nat (instHMod.{0} Nat Nat.instModNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n k) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p a)))) (Finset.Ico.{0} Nat (PartialOrder.toPreorder.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring)) instLocallyFiniteOrderNatToPreorderToPartialOrderStrictOrderedSemiring (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) b))))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_choose Nat.Prime.multiplicity_chooseβ‚“'. -/ /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem multiplicity_choose {p n k b : β„•} (hp : p.Prime) (hkn : k ≀ n) (hnb : log p n < b) : multiplicity p (choose n k) = ((Ico 1 b).filterβ‚“ fun i => p ^ i ≀ k % p ^ i + (n - k) % p ^ i).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k ! * (n - k)!) = ((Finset.Ico 1 b).filterβ‚“ fun i => p ^ i ≀ k % p ^ i + (n - k) % p ^ i).card + multiplicity p (k ! * (n - k)!) := by rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial ((log_mono_right hkn).trans_lt hnb), hp.multiplicity_factorial (lt_of_le_of_lt (log_mono_right tsub_le_self) hnb), multiplicity_choose_aux hp hkn] simp [add_comm] (PartENat.add_right_cancel_iff (PartENat.ne_top_iff_dom.2 <| finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1 h₁ #align nat.prime.multiplicity_choose Nat.Prime.multiplicity_choose /- warning: nat.prime.multiplicity_le_multiplicity_choose_add -> Nat.Prime.multiplicity_le_multiplicity_choose_add is a dubious translation: lean 3 declaration is forall {p : Nat}, (Nat.Prime p) -> (forall (n : Nat) (k : Nat), LE.le.{0} PartENat PartENat.hasLe (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p n) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.choose n k)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p k))) but is expected to have type forall {p : Nat}, (Nat.Prime p) -> (forall (n : Nat) (k : Nat), LE.le.{0} PartENat PartENat.instLEPartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p n) (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.choose n k)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p k))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_le_multiplicity_choose_add Nat.Prime.multiplicity_le_multiplicity_choose_addβ‚“'. -/ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ theorem multiplicity_le_multiplicity_choose_add {p : β„•} (hp : p.Prime) : βˆ€ n k : β„•, multiplicity p n ≀ multiplicity p (choose n k) + multiplicity p k | _, 0 => by simp | 0, _ + 1 => by simp | n + 1, k + 1 => by rw [← hp.multiplicity_mul] refine' multiplicity_le_multiplicity_of_dvd_right _ rw [← succ_mul_choose_eq] exact dvd_mul_right _ _ #align nat.prime.multiplicity_le_multiplicity_choose_add Nat.Prime.multiplicity_le_multiplicity_choose_add variable {p n k : β„•} /- warning: nat.prime.multiplicity_choose_prime_pow_add_multiplicity -> Nat.Prime.multiplicity_choose_prime_pow_add_multiplicity is a dubious translation: lean 3 declaration is forall {p : Nat} {n : Nat} {k : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat Nat.hasLe k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p n)) -> (Ne.{1} Nat k (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) -> (Eq.{1} PartENat (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.hasAdd) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.choose (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p n) k)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p k)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) n)) but is expected to have type forall {p : Nat} {n : Nat} {k : Nat}, (Nat.Prime p) -> (LE.le.{0} Nat instLENat k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p n)) -> (Ne.{1} Nat k (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) -> (Eq.{1} PartENat (HAdd.hAdd.{0, 0, 0} PartENat PartENat PartENat (instHAdd.{0} PartENat PartENat.instAddPartENat) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.choose (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p n) k)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p k)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) n)) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_choose_prime_pow_add_multiplicity Nat.Prime.multiplicity_choose_prime_pow_add_multiplicityβ‚“'. -/ theorem multiplicity_choose_prime_pow_add_multiplicity (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (by have hdisj : Disjoint ((Ico 1 n.succ).filterβ‚“ fun i => p ^ i ≀ k % p ^ i + (p ^ n - k) % p ^ i) ((Ico 1 n.succ).filterβ‚“ fun i => p ^ i ∣ k) := by simp (config := { contextual := true }) [disjoint_right, *, dvd_iff_mod_eq_zero, Nat.mod_lt _ (pow_pos hp.pos _)] rw [multiplicity_choose hp hkn (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0.bot_lt (lt_succ_of_le (log_mono_right hkn)), ← Nat.cast_add, PartENat.coe_le_coe, log_pow hp.one_lt, ← card_disjoint_union hdisj, filter_union_right] have filter_le_Ico := (Ico 1 n.succ).card_filter_le _ rwa [card_Ico 1 n.succ] at filter_le_Ico) (by rw [← hp.multiplicity_pow_self] <;> exact multiplicity_le_multiplicity_choose_add hp _ _) #align nat.prime.multiplicity_choose_prime_pow_add_multiplicity Nat.Prime.multiplicity_choose_prime_pow_add_multiplicity /- warning: nat.prime.multiplicity_choose_prime_pow -> Nat.Prime.multiplicity_choose_prime_pow is a dubious translation: lean 3 declaration is forall {p : Nat} {n : Nat} {k : Nat} (hp : Nat.Prime p), (LE.le.{0} Nat Nat.hasLe k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p n)) -> (forall (hk0 : Ne.{1} Nat k (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))), Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p (Nat.choose (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat (Monoid.Pow.{0} Nat Nat.monoid)) p n) k)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) n (Part.get.{0} Nat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) p k) (Iff.mpr (multiplicity.Finite.{0} Nat Nat.monoid p k) (And (Ne.{1} Nat p (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) (LT.lt.{0} Nat Nat.hasLt (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) k)) (multiplicity.finite_nat_iff p k) (And.intro (Ne.{1} Nat p (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) (LT.lt.{0} Nat Nat.hasLt (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) k) (Nat.Prime.ne_one p hp) (Ne.bot_lt.{0} Nat (OrderedCancelAddCommMonoid.toPartialOrder.{0} Nat (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{0} Nat Nat.strictOrderedSemiring)) Nat.orderBot k hk0))))))) but is expected to have type forall {p : Nat} {n : Nat} {k : Nat} (hp : Nat.Prime p), (LE.le.{0} Nat instLENat k (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p n)) -> (forall (hk0 : Ne.{1} Nat k (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))), Eq.{1} PartENat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p (Nat.choose (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) p n) k)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) n (Part.get.{0} Nat (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) p k) (Iff.mpr (multiplicity.Finite.{0} Nat Nat.monoid p k) (And (Ne.{1} Nat p (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) (LT.lt.{0} Nat instLTNat (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) k)) (multiplicity.finite_nat_iff p k) (And.intro (Ne.{1} Nat p (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) (LT.lt.{0} Nat instLTNat (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) k) (Nat.Prime.ne_one p hp) (Ne.bot_lt.{0} Nat (StrictOrderedSemiring.toPartialOrder.{0} Nat Nat.strictOrderedSemiring) Nat.orderBot k hk0))))))) Case conversion may be inaccurate. Consider using '#align nat.prime.multiplicity_choose_prime_pow Nat.Prime.multiplicity_choose_prime_powβ‚“'. -/ theorem multiplicity_choose_prime_pow {p n k : β„•} (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : multiplicity p (choose (p ^ n) k) = ↑(n - (multiplicity p k).get (finite_nat_iff.2 ⟨hp.ne_one, hk0.bot_lt⟩)) := PartENat.eq_natCast_sub_of_add_eq_natCast <| multiplicity_choose_prime_pow_add_multiplicity hp hkn hk0 #align nat.prime.multiplicity_choose_prime_pow Nat.Prime.multiplicity_choose_prime_pow #print Nat.Prime.dvd_choose_pow /- theorem dvd_choose_pow (hp : Prime p) (hk : k β‰  0) (hkp : k β‰  p ^ n) : p ∣ (p ^ n).choose k := by obtain hkp | hkp := hkp.symm.lt_or_lt Β· simp [choose_eq_zero_of_lt hkp] refine' multiplicity_ne_zero.1 fun h => hkp.not_le <| Nat.le_of_dvd hk.bot_lt _ have H := hp.multiplicity_choose_prime_pow_add_multiplicity hkp.le hk rw [h, zero_add, eq_coe_iff] at H exact H.1 #align nat.prime.dvd_choose_pow Nat.Prime.dvd_choose_pow -/ #print Nat.Prime.dvd_choose_pow_iff /- theorem dvd_choose_pow_iff (hp : Prime p) : p ∣ (p ^ n).choose k ↔ k β‰  0 ∧ k β‰  p ^ n := by refine' ⟨fun h => ⟨_, _⟩, fun h => dvd_choose_pow hp h.1 h.2⟩ <;> rintro rfl <;> simpa [hp.ne_one] using h #align nat.prime.dvd_choose_pow_iff Nat.Prime.dvd_choose_pow_iff -/ end Prime /- warning: nat.multiplicity_two_factorial_lt -> Nat.multiplicity_two_factorial_lt is a dubious translation: lean 3 declaration is forall {n : Nat}, (Ne.{1} Nat n (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) -> (LT.lt.{0} PartENat (Preorder.toLT.{0} PartENat (PartialOrder.toPreorder.{0} PartENat PartENat.partialOrder)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidableDvd a b) (OfNat.ofNat.{0} Nat 2 (OfNat.mk.{0} Nat 2 (bit0.{0} Nat Nat.hasAdd (One.one.{0} Nat Nat.hasOne)))) (Nat.factorial n)) ((fun (a : Type) (b : Type) [self : HasLiftT.{1, 1} a b] => self.0) Nat PartENat (HasLiftT.mk.{1, 1} Nat PartENat (CoeTCβ‚“.coe.{1, 1} Nat PartENat (Nat.castCoe.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.addCommMonoidWithOne))))) n)) but is expected to have type forall {n : Nat}, (Ne.{1} Nat n (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) -> (LT.lt.{0} PartENat (Preorder.toLT.{0} PartENat (PartialOrder.toPreorder.{0} PartENat PartENat.partialOrder)) (multiplicity.{0} Nat Nat.monoid (fun (a : Nat) (b : Nat) => Nat.decidable_dvd a b) (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2)) (Nat.factorial n)) (Nat.cast.{0} PartENat (AddMonoidWithOne.toNatCast.{0} PartENat (AddCommMonoidWithOne.toAddMonoidWithOne.{0} PartENat PartENat.instAddCommMonoidWithOnePartENat)) n)) Case conversion may be inaccurate. Consider using '#align nat.multiplicity_two_factorial_lt Nat.multiplicity_two_factorial_ltβ‚“'. -/ theorem multiplicity_two_factorial_lt : βˆ€ {n : β„•} (h : n β‰  0), multiplicity 2 n ! < n := by have h2 := prime_two.prime refine' binary_rec _ _ Β· contradiction Β· intro b n ih h by_cases hn : n = 0 Β· subst hn simp at h simp [h, one_right h2.not_unit] have : multiplicity 2 (2 * n)! < (2 * n : β„•) := by rw [prime_two.multiplicity_factorial_mul] refine' (PartENat.add_lt_add_right (ih hn) (PartENat.natCast_ne_top _)).trans_le _ rw [two_mul] norm_cast cases b Β· simpa [bit0_eq_two_mul n] Β· suffices multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1 by simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, Nat.bit1_eq_succ_bit0, bit0_eq_two_mul n] rw [multiplicity_eq_zero.2 (two_not_dvd_two_mul_add_one n), zero_add] refine' this.trans _ exact_mod_cast lt_succ_self _ #align nat.multiplicity_two_factorial_lt Nat.multiplicity_two_factorial_lt end Nat
lemma smult_eq_iff: fixes b :: "'a :: field" assumes "b \<noteq> 0" shows "smult a p = smult b q \<longleftrightarrow> smult (a / b) p = q" (is "?lhs \<longleftrightarrow> ?rhs")
(* Title: HOL/Auth/n_mesi.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_mesi Protocol Case Study*} theory n_mesi imports n_mesi_lemma_invs_on_rules n_mesi_on_inis begin lemma main: assumes a1: "s \<in> reachableSet {andList (allInitSpecs N)} (rules N)" and a2: "0 < N" shows "\<forall> f. f \<in> (invariants N) --> formEval f s" proof (rule consistentLemma) show "consistent (invariants N) {andList (allInitSpecs N)} (rules N)" proof (cut_tac a1, unfold consistent_def, rule conjI) show "\<forall> f ini s. f \<in> (invariants N) --> ini \<in> {andList (allInitSpecs N)} --> formEval ini s --> formEval f s" proof ((rule allI)+, (rule impI)+) fix f ini s assume b1: "f \<in> (invariants N)" and b2: "ini \<in> {andList (allInitSpecs N)}" and b3: "formEval ini s" have b4: "formEval (andList (allInitSpecs N)) s" apply (cut_tac b2 b3, simp) done show "formEval f s" apply (rule on_inis, cut_tac b1, assumption, cut_tac b2, assumption, cut_tac b3, assumption) done qed next show "\<forall> f r s. f \<in> invariants N --> r \<in> rules N --> invHoldForRule s f r (invariants N)" proof ((rule allI)+, (rule impI)+) fix f r s assume b1: "f \<in> invariants N" and b2: "r \<in> rules N" show "invHoldForRule s f r (invariants N)" apply (rule invs_on_rules, cut_tac b1, assumption, cut_tac b2, assumption) done qed qed next show "s \<in> reachableSet {andList (allInitSpecs N)} (rules N)" apply (metis a1) done qed end
double complex function Fcc_qpgpgpqm(j1,j2,j3,j4,j5,j6,za,zb) implicit none integer j1,j2,j3,j4,j5,j6 include 'constants.f' include 'zprods_decl.f' include 'sprods_com.f' double complex L0,Lsm1,Lsm1_2me double precision t Fcc_qpgpgpqm= .-(((-Lsm1(-s(j1,j2),-t(j1,j2,j3),-s(j2,j3),-t(j1,j2,j3))- .Lsm1(-s(j2,j3),-t(j2,j3,j4),-s(j3,j4),-t(j2,j3,j4))- .Lsm1_2me(t(j1,j2,j3),t(j2,j3,j4),s(j2,j3),s(j5,j6)))*za(j4,j5)**2) ./ .(za(j1,j2)*za(j2,j3)*za(j3,j4)*za(j5,j6)))- .(2d0*L0(-t(j2,j3,j4),-s(j3,j4))*za(j2,j5)*za(j4,j5)*zb(j2,j3))/ .(s(j3,j4)*za(j1,j2)*za(j2,j3)*za(j5,j6))- .(2d0*L0(-s(j5,j6),-t(j2,j3,j4))*za(j1,j5)*za(j4,j5)* .(za(j2,j4)*zb(j1,j2)+za(j3,j4)*zb(j1,j3)))/ .(za(j1,j2)*za(j2,j3)*za(j3,j4)*za(j5,j6)*t(j2,j3,j4)) return end
Formal statement is: lemma emeasure_bounded_finite: assumes "bounded A" shows "emeasure lborel A < \<infinity>" Informal statement is: If $A$ is a bounded set, then the Lebesgue measure of $A$ is finite.
{-# OPTIONS_GHC -Wall #-} module Diagrams.Spirograph ( Spiro(Spiro) , drawSpiros , drawSpirosIntermediate ) where import Data.Complex (Complex(..), mkPolar) import Diagrams.Prelude (Diagram, P2) import qualified Diagrams.Backend.SVG.CmdLine as SVG import qualified Diagrams.Prelude as D import Data.Monoid (Sum(..)) data Spiro = Spiro { offset ∷ Double , speed ∷ Double } newtype Path w = Path (Double β†’ w) deriving newtype instance Semigroup w β‡’ Semigroup (Path w) deriving newtype instance Monoid w β‡’ Monoid (Path w) newtype P = P (Sum (P2 Double)) runP ∷ P β†’ P2 Double runP (P (Sum p)) = p deriving newtype instance Semigroup P deriving newtype instance Monoid P -- | @'disk' d@ is the path that @d@ will travel. disk ∷ Spiro β†’ Path P disk Spiro{..} = Path $ \t β†’ P $ Sum $ p2 $ mkPolar offset (speed * t) disks ∷ [Spiro] β†’ Path P disks = foldMap disk allSpiros ∷ [Spiro] β†’ [Path P] allSpiros = \case [] β†’ mempty (x:xs) β†’ px : map f pxs where px = disk x pxs = allSpiros xs f ∷ Path P β†’ Path P f p = px <> p -- | Form a point in diagrams in terms of a complex number. p2 ∷ Complex a β†’ P2 a p2 (x :+ y) = D.p2 (x, y) -- | Convert a path into a path. sample ∷ Path P β†’ [P2 Double] sample (Path f) = runP . f <$> enumFromThenTo 0 0.1 100 drawSpiros ∷ [Spiro] β†’ Diagram SVG.B drawSpiros xs = D.fromVertices $ sample (disks xs) drawSpirosIntermediate ∷ [Spiro] β†’ Diagram SVG.B drawSpirosIntermediate xs = foldMap step (allSpiros xs) where step p = D.fromVertices $ sample p
module _ where primitive primGlue : _
The fractional polynomial $1$ is equal to $1$.
function ffun(x, y) implicit none !GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN double precision :: x, y, ffun ffun = x + y * y end function
ifthenelse : String ifthenelse = "\{ if True then "a" else "b" }"
[STATEMENT] lemma Integral_mult: "[| a \<le> b; Integral(a,b) f k |] ==> Integral(a,b) (%x. c * f x) (c * k)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>a \<le> b; Integral (a, b) f k\<rbrakk> \<Longrightarrow> Integral (a, b) (\<lambda>x. c * f x) (c * k) [PROOF STEP] apply (auto simp add: order_le_less) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Integral (a, b) f k; a < b\<rbrakk> \<Longrightarrow> Integral (a, b) (\<lambda>x. c * f x) (c * k) [PROOF STEP] apply (cases "c = 0", simp add: Integral_zero_fun) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>Integral (a, b) f k; a < b; c \<noteq> 0\<rbrakk> \<Longrightarrow> Integral (a, b) (\<lambda>x. c * f x) (c * k) [PROOF STEP] apply (rule IntegralI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>e. \<lbrakk>Integral (a, b) f k; a < b; c \<noteq> 0; 0 < e\<rbrakk> \<Longrightarrow> \<exists>\<delta>. gauge {a..b} \<delta> \<and> (\<forall>D. fine \<delta> (a, b) D \<longrightarrow> \<bar>rsum D (\<lambda>x. c * f x) - c * k\<bar> < e) [PROOF STEP] apply (erule_tac e="e / \<bar>c\<bar>" in IntegralE, simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>e \<delta>. \<lbrakk>a < b; c \<noteq> 0; 0 < e; gauge {a..b} \<delta>; \<forall>D. fine \<delta> (a, b) D \<longrightarrow> \<bar>rsum D f - k\<bar> < e / \<bar>c\<bar>\<rbrakk> \<Longrightarrow> \<exists>\<delta>. gauge {a..b} \<delta> \<and> (\<forall>D. fine \<delta> (a, b) D \<longrightarrow> \<bar>rsum D (\<lambda>x. c * f x) - c * k\<bar> < e) [PROOF STEP] apply (rule_tac x="\<delta>" in exI, clarify) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>e \<delta> D. \<lbrakk>a < b; c \<noteq> 0; 0 < e; gauge {a..b} \<delta>; \<forall>D. fine \<delta> (a, b) D \<longrightarrow> \<bar>rsum D f - k\<bar> < e / \<bar>c\<bar>; fine \<delta> (a, b) D\<rbrakk> \<Longrightarrow> \<bar>rsum D (\<lambda>x. c * f x) - c * k\<bar> < e [PROOF STEP] apply (drule_tac x="D" in spec, clarify) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>e \<delta> D. \<lbrakk>a < b; c \<noteq> 0; 0 < e; gauge {a..b} \<delta>; fine \<delta> (a, b) D; \<bar>rsum D f - k\<bar> < e / \<bar>c\<bar>\<rbrakk> \<Longrightarrow> \<bar>rsum D (\<lambda>x. c * f x) - c * k\<bar> < e [PROOF STEP] apply (simp add: pos_less_divide_eq abs_mult [symmetric] algebra_simps rsum_right_distrib) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
section\<open>The Axiom of Infinity in $M[G]$\<close> theory Infinity_Axiom imports Pairing_Axiom Union_Axiom Separation_Axiom begin context G_generic begin interpretation mg_triv: M_trivial"##M[G]" using transitivity_MG zero_in_MG generic Union_MG pairing_in_MG by unfold_locales auto lemma infinity_in_MG : "infinity_ax(##M[G])" proof - from infinity_ax obtain I where Eq1: "I\<in>M" "0 \<in> I" "\<forall>y\<in>M. y \<in> I \<longrightarrow> succ(y) \<in> I" unfolding infinity_ax_def by auto then have "check(I) \<in> M" using check_in_M by simp then have "I\<in> M[G]" using valcheck generic one_in_G one_in_P GenExtI[of "check(I)" G] by simp with \<open>0\<in>I\<close> have "0\<in>M[G]" using transitivity_MG by simp with \<open>I\<in>M\<close> have "y \<in> M" if "y \<in> I" for y using transitivity[OF _ \<open>I\<in>M\<close>] that by simp with \<open>I\<in>M[G]\<close> have "succ(y) \<in> I \<inter> M[G]" if "y \<in> I" for y using that Eq1 transitivity_MG by blast with Eq1 \<open>I\<in>M[G]\<close> \<open>0\<in>M[G]\<close> show ?thesis unfolding infinity_ax_def by auto qed end (* G_generic' *) end
[STATEMENT] lemma s_id_om [simp]: "1\<^sub>\<sigma>\<^sup>\<omega> = U" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 1\<^sub>\<sigma>\<^sup>\<omega> = U [PROOF STEP] by (simp add: local.U_def order.eq_iff local.om_coinduct)
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_srotg (float *a, float *b, float *c, float *s) { #define BASE float #include "source_rotg.h" #undef BASE }
<!-- dom:TITLE: PHY321: More on Motion and Forces, begin Work and Energy discussion --> # PHY321: More on Motion and Forces, begin Work and Energy discussion <!-- dom:AUTHOR: [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/) at Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA & Department of Physics, University of Oslo, Norway --> <!-- Author: --> **[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway Date: **Feb 3, 2021** Copyright 1999-2021, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license ## Aims and Overarching Motivation ### Monday We discuss various forces and their pertinent equations of motion Recommended reading: Taylor 2.1-2.4. Malthe-SΓΈrenssen chapter 6-7 contains many examples. We will cover in particular a falling object in two dimensions with linear air resistance relevant for homework 3. ### Wednesday We discuss other force models with examples such as the gravitational force and a spring force. See Malthe-SΓΈrenssen chapter 7.3-7.5. We start our discussion of energy and work, see Taylor 4.1 We discuss also exercise 5 from homework 2. ### Friday We discuss several examples of energy and work. Taylor 4.1-4.3. ## Air Resistance in One Dimension Last week we considered the motion of a falling object with air resistance. Here we look at both a quadratic in velocity resistance and linear in velocity. But first we give a qualitative argument about the mathematical expression for the air resistance we used last Friday. Air resistance tends to scale as the square of the velocity. This is in contrast to many problems chosen for textbooks, where it is linear in the velocity. The choice of a linear dependence is motivated by mathematical simplicity (it keeps the differential equation linear) rather than by physics. One can see that the force should be quadratic in velocity by considering the momentum imparted on the air molecules. If an object sweeps through a volume $dV$ of air in time $dt$, the momentum imparted on the air is <!-- Equation labels as ordinary links --> <div id="_auto1"></div> $$ \begin{equation} dP=\rho_m dV v, \label{_auto1} \tag{1} \end{equation} $$ where $v$ is the velocity of the object and $\rho_m$ is the mass density of the air. If the molecules bounce back as opposed to stop you would double the size of the term. The opposite value of the momentum is imparted onto the object itself. Geometrically, the differential volume is <!-- Equation labels as ordinary links --> <div id="_auto2"></div> $$ \begin{equation} dV=Avdt, \label{_auto2} \tag{2} \end{equation} $$ where $A$ is the cross-sectional area and $vdt$ is the distance the object moved in time $dt$. ## Resulting Acceleration Plugging this into the expression above, <!-- Equation labels as ordinary links --> <div id="_auto3"></div> $$ \begin{equation} \frac{dP}{dt}=-\rho_m A v^2. \label{_auto3} \tag{3} \end{equation} $$ This is the force felt by the particle, and is opposite to its direction of motion. Now, because air doesn't stop when it hits an object, but flows around the best it can, the actual force is reduced by a dimensionless factor $c_W$, called the drag coefficient. <!-- Equation labels as ordinary links --> <div id="_auto4"></div> $$ \begin{equation} F_{\rm drag}=-c_W\rho_m Av^2, \label{_auto4} \tag{4} \end{equation} $$ and the acceleration is $$ \begin{eqnarray} \frac{dv}{dt}=-\frac{c_W\rho_mA}{m}v^2. \end{eqnarray} $$ For a particle with initial velocity $v_0$, one can separate the $dt$ to one side of the equation, and move everything with $v$s to the other side. We did this in our discussion of simple motion and will not repeat it here. On more general terms, for many systems, e.g. an automobile, there are multiple sources of resistance. In addition to wind resistance, where the force is proportional to $v^2$, there are dissipative effects of the tires on the pavement, and in the axel and drive train. These other forces can have components that scale proportional to $v$, and components that are independent of $v$. Those independent of $v$, e.g. the usual $f=\mu_K N$ frictional force you consider in your first Physics courses, only set in once the object is actually moving. As speeds become higher, the $v^2$ components begin to dominate relative to the others. For automobiles at freeway speeds, the $v^2$ terms are largely responsible for the loss of efficiency. To travel a distance $L$ at fixed speed $v$, the energy/work required to overcome the dissipative forces are $fL$, which for a force of the form $f=\alpha v^n$ becomes $$ \begin{eqnarray} W=\int dx~f=\alpha v^n L. \end{eqnarray} $$ For $n=0$ the work is independent of speed, but for the wind resistance, where $n=2$, slowing down is essential if one wishes to reduce fuel consumption. It is also important to consider that engines are designed to be most efficient at a chosen range of power output. Thus, some cars will get better mileage at higher speeds (They perform better at 50 mph than at 5 mph) despite the considerations mentioned above. ## Going Ballistic, Projectile Motion or a Softer Approach, Falling Raindrops As an example of Newton's Laws we consider projectile motion (or a falling raindrop or a ball we throw up in the air) with a drag force. Even though air resistance is largely proportional to the square of the velocity, we will consider the drag force to be linear to the velocity, $\boldsymbol{F}=-m\gamma\boldsymbol{v}$, for the purposes of this exercise. Such a dependence can be extracted from experimental data for objects moving at low velocities, see for example Malthe-SΓΈrenssen chapter 5.6. We will here focus on a two-dimensional problem. ## Two-dimensional falling object The acceleration for a projectile moving upwards, $\boldsymbol{a}=\boldsymbol{F}/m$, becomes $$ \begin{eqnarray} \frac{dv_x}{dt}=-\gamma v_x,\\ \nonumber \frac{dv_y}{dt}=-\gamma v_y-g, \end{eqnarray} $$ and $\gamma$ has dimensions of inverse time. If you on the other hand have a falling raindrop, how do these equations change? See for example Figure 2.1 in Taylor. Let us stay with a ball which is thrown up in the air at $t=0$. ## Ways of solving these equations We will go over two different ways to solve this equation. The first by direct integration, and the second as a differential equation. To do this by direct integration, one simply multiplies both sides of the equations above by $dt$, then divide by the appropriate factors so that the $v$s are all on one side of the equation and the $dt$ is on the other. For the $x$ motion one finds an easily integrable equation, $$ \begin{eqnarray} \frac{dv_x}{v_x}&=&-\gamma dt,\\ \nonumber \int_{v_{0x}}^{v_{x}}\frac{dv_x}{v_x}&=&-\gamma\int_0^{t}dt,\\ \nonumber \ln\left(\frac{v_{x}}{v_{0x}}\right)&=&-\gamma t,\\ \nonumber v_{x}(t)&=&v_{0x}e^{-\gamma t}. \end{eqnarray} $$ This is very much the result you would have written down by inspection. For the $y$-component of the velocity, $$ \begin{eqnarray} \frac{dv_y}{v_y+g/\gamma}&=&-\gamma dt\\ \nonumber \ln\left(\frac{v_{y}+g/\gamma}{v_{0y}-g/\gamma}\right)&=&-\gamma t_f,\\ \nonumber v_{fy}&=&-\frac{g}{\gamma}+\left(v_{0y}+\frac{g}{\gamma}\right)e^{-\gamma t}. \end{eqnarray} $$ Whereas $v_x$ starts at some value and decays exponentially to zero, $v_y$ decays exponentially to the terminal velocity, $v_t=-g/\gamma$. ## Solving as differential equations Although this direct integration is simpler than the method we invoke below, the method below will come in useful for some slightly more difficult differential equations in the future. The differential equation for $v_x$ is straight-forward to solve. Because it is first order there is one arbitrary constant, $A$, and by inspection the solution is <!-- Equation labels as ordinary links --> <div id="_auto5"></div> $$ \begin{equation} v_x=Ae^{-\gamma t}. \label{_auto5} \tag{5} \end{equation} $$ The arbitrary constants for equations of motion are usually determined by the initial conditions, or more generally boundary conditions. By inspection $A=v_{0x}$, the initial $x$ component of the velocity. ## Differential Equations, contn The differential equation for $v_y$ is a bit more complicated due to the presence of $g$. Differential equations where all the terms are linearly proportional to a function, in this case $v_y$, or to derivatives of the function, e.g., $v_y$, $dv_y/dt$, $d^2v_y/dt^2\cdots$, are called linear differential equations. If there are terms proportional to $v^2$, as would happen if the drag force were proportional to the square of the velocity, the differential equation is not longer linear. Because this expression has only one derivative in $v$ it is a first-order linear differential equation. If a term were added proportional to $d^2v/dt^2$ it would be a second-order differential equation. In this case we have a term completely independent of $v$, the gravitational acceleration $g$, and the usual strategy is to first rewrite the equation with all the linear terms on one side of the equal sign, <!-- Equation labels as ordinary links --> <div id="_auto6"></div> $$ \begin{equation} \frac{dv_y}{dt}+\gamma v_y=-g. \label{_auto6} \tag{6} \end{equation} $$ ## Splitting into two parts Now, the solution to the equation can be broken into two parts. Because this is a first-order differential equation we know that there will be one arbitrary constant. Physically, the arbitrary constant will be determined by setting the initial velocity, though it could be determined by setting the velocity at any given time. Like most differential equations, solutions are not "solved". Instead, one guesses at a form, then shows the guess is correct. For these types of equations, one first tries to find a single solution, i.e. one with no arbitrary constants. This is called the {\it particular} solution, $y_p(t)$, though it should really be called "a" particular solution because there are an infinite number of such solutions. One then finds a solution to the {\it homogenous} equation, which is the equation with zero on the right-hand side, <!-- Equation labels as ordinary links --> <div id="_auto7"></div> $$ \begin{equation} \frac{dv_{y,h}}{dt}+\gamma v_{y,h}=0. \label{_auto7} \tag{7} \end{equation} $$ Homogenous solutions will have arbitrary constants. The particular solution will solve the same equation as the original general equation <!-- Equation labels as ordinary links --> <div id="_auto8"></div> $$ \begin{equation} \frac{dv_{y,p}}{dt}+\gamma v_{y,p}=-g. \label{_auto8} \tag{8} \end{equation} $$ However, we don't need find one with arbitrary constants. Hence, it is called a **particular** solution. The sum of the two, <!-- Equation labels as ordinary links --> <div id="_auto9"></div> $$ \begin{equation} v_y=v_{y,p}+v_{y,h}, \label{_auto9} \tag{9} \end{equation} $$ is a solution of the total equation because of the linear nature of the differential equation. One has now found a *general* solution encompassing all solutions, because it both satisfies the general equation (like the particular solution), and has an arbitrary constant that can be adjusted to fit any initial condition (like the homogeneous solution). If the equations were not linear, that is if there were terms such as $v_y^2$ or $v_y\dot{v}_y$, this technique would not work. ## More details Returning to the example above, the homogenous solution is the same as that for $v_x$, because there was no gravitational acceleration in that case, <!-- Equation labels as ordinary links --> <div id="_auto10"></div> $$ \begin{equation} v_{y,h}=Be^{-\gamma t}. \label{_auto10} \tag{10} \end{equation} $$ In this case a particular solution is one with constant velocity, <!-- Equation labels as ordinary links --> <div id="_auto11"></div> $$ \begin{equation} v_{y,p}=-g/\gamma. \label{_auto11} \tag{11} \end{equation} $$ Note that this is the terminal velocity of a particle falling from a great height. The general solution is thus, <!-- Equation labels as ordinary links --> <div id="_auto12"></div> $$ \begin{equation} v_y=Be^{-\gamma t}-g/\gamma, \label{_auto12} \tag{12} \end{equation} $$ and one can find $B$ from the initial velocity, <!-- Equation labels as ordinary links --> <div id="_auto13"></div> $$ \begin{equation} v_{0y}=B-g/\gamma,~~~B=v_{0y}+g/\gamma. \label{_auto13} \tag{13} \end{equation} $$ Plugging in the expression for $B$ gives the $y$ motion given the initial velocity, <!-- Equation labels as ordinary links --> <div id="_auto14"></div> $$ \begin{equation} v_y=(v_{0y}+g/\gamma)e^{-\gamma t}-g/\gamma. \label{_auto14} \tag{14} \end{equation} $$ It is easy to see that this solution has $v_y=v_{0y}$ when $t=0$ and $v_y=-g/\gamma$ when $t\rightarrow\infty$. One can also integrate the two equations to find the coordinates $x$ and $y$ as functions of $t$, $$ \begin{eqnarray} x&=&\int_0^t dt'~v_{0x}(t')=\frac{v_{0x}}{\gamma}\left(1-e^{-\gamma t}\right),\\ \nonumber y&=&\int_0^t dt'~v_{0y}(t')=-\frac{gt}{\gamma}+\frac{v_{0y}+g/\gamma}{\gamma}\left(1-e^{-\gamma t}\right). \end{eqnarray} $$ If the question was to find the position at a time $t$, we would be finished. However, the more common goal in a projectile equation problem is to find the range, i.e. the distance $x$ at which $y$ returns to zero. For the case without a drag force this was much simpler. The solution for the $y$ coordinate would have been $y=v_{0y}t-gt^2/2$. One would solve for $t$ to make $y=0$, which would be $t=2v_{0y}/g$, then plug that value for $t$ into $x=v_{0x}t$ to find $x=2v_{0x}v_{0y}/g=v_0\sin(2\theta_0)/g$. One follows the same steps here, except that the expression for $y(t)$ is more complicated. Searching for the time where $y=0$, and we get <!-- Equation labels as ordinary links --> <div id="_auto15"></div> $$ \begin{equation} 0=-\frac{gt}{\gamma}+\frac{v_{0y}+g/\gamma}{\gamma}\left(1-e^{-\gamma t}\right). \label{_auto15} \tag{15} \end{equation} $$ This cannot be inverted into a simple expression $t=\cdots$. Such expressions are known as "transcendental equations", and are not the rare instance, but are the norm. In the days before computers, one might plot the right-hand side of the above graphically as a function of time, then find the point where it crosses zero. Now, the most common way to solve for an equation of the above type would be to apply Newton's method numerically. This involves the following algorithm for finding solutions of some equation $F(t)=0$. 1. First guess a value for the time, $t_{\rm guess}$. 2. Calculate $F$ and its derivative, $F(t_{\rm guess})$ and $F'(t_{\rm guess})$. 3. Unless you guessed perfectly, $F\ne 0$, and assuming that $\Delta F\approx F'\Delta t$, one would choose 4. $\Delta t=-F(t_{\rm guess})/F'(t_{\rm guess})$. 5. Now repeat step 1, but with $t_{\rm guess}\rightarrow t_{\rm guess}+\Delta t$. If the $F(t)$ were perfectly linear in $t$, one would find $t$ in one step. Instead, one typically finds a value of $t$ that is closer to the final answer than $t_{\rm guess}$. One breaks the loop once one finds $F$ within some acceptable tolerance of zero. A program to do this will be added shortly. ## Motion in a Magnetic Field Another example of a velocity-dependent force is magnetism, $$ \begin{eqnarray} \boldsymbol{F}&=&q\boldsymbol{v}\times\boldsymbol{B},\\ \nonumber F_i&=&q\sum_{jk}\epsilon_{ijk}v_jB_k. \end{eqnarray} $$ For a uniform field in the $z$ direction $\boldsymbol{B}=B\hat{z}$, the force can only have $x$ and $y$ components, $$ \begin{eqnarray} F_x&=&qBv_y\\ \nonumber F_y&=&-qBv_x. \end{eqnarray} $$ The differential equations are $$ \begin{eqnarray} \dot{v}_x&=&\omega_c v_y,\omega_c= qB/m\\ \nonumber \dot{v}_y&=&-\omega_c v_x. \end{eqnarray} $$ One can solve the equations by taking time derivatives of either equation, then substituting into the other equation, $$ \begin{eqnarray} \ddot{v}_x=\omega_c\dot{v_y}=-\omega_c^2v_x,\\ \nonumber \ddot{v}_y&=&-\omega_c\dot{v}_x=-\omega_cv_y. \end{eqnarray} $$ The solution to these equations can be seen by inspection, $$ \begin{eqnarray} v_x&=&A\sin(\omega_ct+\phi),\\ \nonumber v_y&=&A\cos(\omega_ct+\phi). \end{eqnarray} $$ One can integrate the equations to find the positions as a function of time, $$ \begin{eqnarray} x-x_0&=&\int_{x_0}^x dx=\int_0^t dt v(t)\\ \nonumber &=&\frac{-A}{\omega_c}\cos(\omega_ct+\phi),\\ \nonumber y-y_0&=&\frac{A}{\omega_c}\sin(\omega_ct+\phi). \end{eqnarray} $$ The trajectory is a circle centered at $x_0,y_0$ with amplitude $A$ rotating in the clockwise direction. The equations of motion for the $z$ motion are <!-- Equation labels as ordinary links --> <div id="_auto16"></div> $$ \begin{equation} \dot{v_z}=0, \label{_auto16} \tag{16} \end{equation} $$ which leads to <!-- Equation labels as ordinary links --> <div id="_auto17"></div> $$ \begin{equation} z-z_0=V_zt. \label{_auto17} \tag{17} \end{equation} $$ Added onto the circle, the motion is helical. Note that the kinetic energy, <!-- Equation labels as ordinary links --> <div id="_auto18"></div> $$ \begin{equation} T=\frac{1}{2}m(v_x^2+v_y^2+v_z^2)=\frac{1}{2}m(\omega_c^2A^2+V_z^2), \label{_auto18} \tag{18} \end{equation} $$ is constant. This is because the force is perpendicular to the velocity, so that in any differential time element $dt$ the work done on the particle $\boldsymbol{F}\cdot{dr}=dt\boldsymbol{F}\cdot{v}=0$. One should think about the implications of a velocity dependent force. Suppose one had a constant magnetic field in deep space. If a particle came through with velocity $v_0$, it would undergo cyclotron motion with radius $R=v_0/\omega_c$. However, if it were still its motion would remain fixed. Now, suppose an observer looked at the particle in one reference frame where the particle was moving, then changed their velocity so that the particle's velocity appeared to be zero. The motion would change from circular to fixed. Is this possible? The solution to the puzzle above relies on understanding relativity. Imagine that the first observer believes $\boldsymbol{B}\ne 0$ and that the electric field $\boldsymbol{E}=0$. If the observer then changes reference frames by accelerating to a velocity $\boldsymbol{v}$, in the new frame $\boldsymbol{B}$ and $\boldsymbol{E}$ both change. If the observer moved to the frame where the charge, originally moving with a small velocity $v$, is now at rest, the new electric field is indeed $\boldsymbol{v}\times\boldsymbol{B}$, which then leads to the same acceleration as one had before. If the velocity is not small compared to the speed of light, additional $\gamma$ factors come into play, $\gamma=1/\sqrt{1-(v/c)^2}$. Relativistic motion will not be considered in this course. ## Sliding Block tied to a Wall Another classical case is that of simple harmonic oscillations, here represented by a block sliding on a horizontal frictionless surface. The block is tied to a wall with a spring. If the spring is not compressed or stretched too far, the force on the block at a given position $x$ is $$ F=-kx. $$ ## Back and Forth, Sliding Block with no friction The negative sign means that the force acts to restore the object to an equilibrium position. Newton's equation of motion for this idealized system is then $$ m\frac{d^2x}{dt^2}=-kx, $$ or we could rephrase it as <!-- Equation labels as ordinary links --> <div id="eq:newton1"></div> $$ \frac{d^2x}{dt^2}=-\frac{k}{m}x=-\omega_0^2x, \label{eq:newton1} \tag{19} $$ with the angular frequency $\omega_0^2=k/m$. We will derive the above force when we start studying **harmonic oscillations**. ## Final rewrite With the position $x(t)$ and the velocity $v(t)=dx/dt$ we can reformulate Newton's equation in the following way $$ \frac{dx(t)}{dt}=v(t), $$ and $$ \frac{dv(t)}{dt}=-\omega_0^2x(t). $$ With initial conditions $x(t_0)=x_0$ and $v(t_0)=v_0$ we can in turn solve the differential equations. ## Analytical Solution The above differential equation has the advantage that it can be solved analytically with general solutions on the form $$ x(t)=A\cos{\omega_0t}+B\sin{\omega_0t}, $$ and $$ v(t)=-\omega_0 A\sin{\omega_0t}+\omega_0 B\cos{\omega_0t}, $$ where $A$ and $B$ are constants to be determined from the initial conditions. This provides in turn an important test for the numerical solution and the development of a program for more complicated cases which cannot be solved analytically. We will discuss the above equations in more detail when we discuss harmonic oscillations. ## Summarizing the various motion problems 1 The examples we have discussed above were included in order to illustrate various methods (which depend on the specific problem) to find the solutions of the equations of motion. We have solved the equations of motion in the following ways: **Solve the differential equations analytically.** We did this for example with the following object in one or two dimensions or the sliding block. Here we had for example an equation set like $$ \frac{dv_x}{dt}=-\gamma v_x, $$ and $$ \frac{dv_y}{dt}=-\gamma v_y-g, $$ and $\gamma$ has dimension of inverse time. ## Summarizing the various motion problems 2 **Integrate the equations.** We could also in case we can separate the degrees of freedom integrate. Take for example one of the equations in the previous slide $$ \frac{dv_x}{dt}=-\gamma v_x, $$ which we can rewrite in terms of a left-hand side which depends only on the velocity and a right-hand side which depends only on time $$ \frac{dv_x}{v_x}=-\gamma dt. $$ Integrating we have (since we can separate $v_x$ and $t$) $$ \int_{v_0}^{v_t}\frac{dv_x}{v_x}=-\int_{t_0}^{t_f}\gamma dt, $$ where $v_f$ is the velocity at a final time and $t_f$ is the final time. In this case we found, after having integrated the above two sides that $$ v_f(t)=v_0\exp{-\gamma t}. $$ ## Summarizing the various motion problems 3 **Solve the differential equations numerically.** Finally, using for example Euler's method, we can solve the differential equations numerically. If we can compare our numerical solutions with analytical solutions, we have an extra check of our numerical approaches. The example code on the next slide is relevant for homework 3. Here we deal with a falling object in two dimensions. Except for the derivations above with an air resistance which is linear in the velocity, homework 3 uses a quadratic velocity dependence. ## Code example using Euler's methods **Note**: this code needs some additional expressions and will not run ```python %matplotlib inline # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' #define the gravitational acceleration g = 9.80655 #m/s^2 # The mass and the drag constant D D = 0.00245 #mass/length kg/m m = 0.2 #kg, mass of falling object DeltaT = 0.001 #set up final time, here just a number we have chosen tfinal = 1.0 # set up number of points for all variables n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and y and arrays for analytical results # Note the brute force setting up of arrays for x and y, vx, vy, ax and ay # For hw3 you should think of using the 2-dim vectors you used in homework 2 t = np.zeros(n) vy = np.zeros(n) y = np.zeros(n) vx = np.zeros(n) x = np.zeros(n) # Initial conditions vx[0] = 10.0 #m/s vy[0] = 0.0 #m/s y[0] = 10.0 #m x[0] = 0.0 #m # Start integrating using Euler's method for i in range(n-1): # expression for acceleration, you need to set them up # ax = You need to set up the expression for force and thereby the acceleration in the x-direction # ay = You need to set up the expression for force and thereby the acceleration in the y-direction # update velocity and position vx[i+1] = vx[i] + DeltaT*ax x[i+1] = x[i] + DeltaT*vx[i] vy[i+1] = vy[i] + DeltaT*ay y[i+1] = y[i] + DeltaT*vy[i] # update time to next time step and compute analytical answer t[i+1] = t[i] + DeltaT # Here you need to set up the analytical solution for y(t) and x(t) if ( y[i+1] < 0.0): break data = {'t[s]': t, 'Relative error in y': abs((y-yanalytic)/yanalytic), 'vy[m/s]': vy, 'Relative error in x': abs((x-xanalytic)/xanalytic), 'vx[m/s]': vx } NewData = pd.DataFrame(data) display(NewData) # save to file NewData.to_csv(outfile, index=False) #then plot fig, axs = plt.subplots(4, 1) axs[0].plot(t, y) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('y') axs[1].plot(t, vy) axs[1].set_ylabel('vy[m/s]') axs[1].set_xlabel('time[s]') axs[2].plot(t, x) axs[2].set_xlim(0, tfinal) axs[2].set_ylabel('x') axs[3].plot(t, vx) axs[3].set_ylabel('vx[m/s]') axs[3].set_xlabel('time[s]') fig.tight_layout() plt.show() ``` ## Work, Energy, Momentum and Conservation laws The previous three cases have shown us how to use Newton’s laws of motion to determine the motion of an object based on the forces acting on it. For two of the cases there is an underlying assumption that we can find an analytical solution to a continuous problem. With a continuous problem we mean a problem where the various variables can take any value within a finite or infinite interval. Unfortunately, in many cases we cannot find an exact solution to the equations of motion we get from Newton’s second law. The numerical approach, where we discretize the continuous problem, allows us however to study a much richer set of problems. For problems involving Newton's laws and the various equations of motion we encounter, solving the equations numerically, is the standard approach. It allows us to focus on the underlying forces. Often we end up using the same numerical algorithm for different problems. Here we introduce a commonly used technique that allows us to find the velocity as a function of position without finding the position as a function of timeβ€”an alternate form of Newton’s second law. The method is based on a simple principle: Instead of solving the equations of motion directly, we integrate the equations of motion. Such a method is called an integration method. This allows us also to introduce the **work-energy** theorem. This theorem allows us to find the velocity as a function of position for an object even in cases when we cannot solve the equations of motion. This introduces us to the concept of work and kinetic energy, an energy related to the motion of an object. And finally, we will link the work-energy theorem with the principle of conservation of energy. ## The Work-Energy Theorem Let us define the kinetic energy $K$ with a given velocity $\boldsymbol{v}$ $$ K=\frac{1}{2}mv^2, $$ where $m$ is the mass of the object we are considering. We assume also that there is a force $\boldsymbol{F}$ acting on the given object $$ \boldsymbol{F}=\boldsymbol{F}(\boldsymbol{r},\boldsymbol{v},t), $$ with $\boldsymbol{r}$ the position and $t$ the time. In general we assume the force is a function of all these variables. Many of the more central forces in Nature however, depende only on the position. Examples are the gravitational force and the force derived from the Coulomb potential in electromagnetism. ## Rewriting the Kinetic Energy Let us study the derivative of the kinetic energy with respect to time $t$. Its continuous form is $$ \frac{dK}{dt}=\frac{1}{2}m\frac{d\boldsymbol{v}\cdot\boldsymbol{v}}{dt}. $$ Using our results from exercise 3 of homework 1, we can write the derivative of a vector dot product as $$ \frac{dK}{dt}=\frac{1}{2}m\frac{d\boldsymbol{v}\cdot\boldsymbol{v}}{dt}= \frac{1}{2}m\left(\frac{d\boldsymbol{v}}{dt}\cdot\boldsymbol{v}+\boldsymbol{v}\cdot\frac{d\boldsymbol{v}}{dt}\right)=m\frac{d\boldsymbol{v}}{dt}\cdot\boldsymbol{v}. $$ We know also that the acceleration is defined as $$ \boldsymbol{a}=\frac{\boldsymbol{F}}{m}=\frac{d\boldsymbol{v}}{dt}. $$ We can then rewrite the equation for the derivative of the kinetic energy as $$ \frac{dK}{dt}=m\frac{d\boldsymbol{v}}{dt}\boldsymbol{v}=\boldsymbol{F}\frac{d\boldsymbol{r}}{dt}, $$ where we defined the velocity as the derivative of the position with respect to time. ## Discretizing Let us now discretize the above equation by letting the instantenous terms be replaced by a discrete quantity, that is we let $dK\rightarrow \Delta K$, $dt\rightarrow \Delta t$, $d\boldsymbol{r}\rightarrow \Delta \boldsymbol{r}$ and $d\boldsymbol{v}\rightarrow \Delta \boldsymbol{v}$. We have then $$ \frac{\Delta K}{\Delta t}=m\frac{\Delta \boldsymbol{v}}{\Delta t}\boldsymbol{v}=\boldsymbol{F}\frac{\Delta \boldsymbol{r}}{\Delta t}, $$ or by multiplying out $\Delta t$ we have $$ \Delta K=\boldsymbol{F}\Delta \boldsymbol{r}. $$ We define this quantity as the **work** done by the force $\boldsymbol{F}$ during the displacement $\Delta \boldsymbol{r}$. If study the dimensionality of this problem we have mass times length squared divided by time squared, or just dimension energy. ## Difference in kinetic energy If we now a series of such displacements $\Delta \boldsymbol{r}$ $i=0,1,\dots,n$, we have a difference in kinetic energy at a final position $\boldsymbol{r}_n$ and an initial position $\boldsymbol{r}_0$ given by $$ \Delta K=\frac{1}{2}mv_n^2-\frac{1}{2}mv_0^2=\sum_{i=0}^n\boldsymbol{F}_i\Delta \boldsymbol{r}, $$ where $\boldsymbol{F}_i$ are the forces acting at every position $\boldsymbol{r}_i$. The work done by acting with a force on a set of displacements can then be as expressed as the difference between the initial and final kinetic energies. This defines the **work-energy** theorem. ## From the discrete version to the continuous version If we take the limit $\Delta \boldsymbol{r}\rightarrow 0$, we can rewrite the sum over the various displacements in terms of an integral, that is $$ \Delta K=\frac{1}{2}mv_n^2-\frac{1}{2}mv_0^2=\sum_{i=0}^n\boldsymbol{F}_i\Delta \boldsymbol{r}\rightarrow \int_{\boldsymbol{r}_0}^{\boldsymbol{r}_n}\boldsymbol{F}(\boldsymbol{r},\boldsymbol{v},t)d\boldsymbol{r}. $$ This integral defines a path integral since it will depend on the given path we take between the two end points. We will replace the limits with the symbol $c$ in order to indicate that we take a specific countour in space when the force acts on the system. That is the work $W_{n0}$ between two points $\boldsymbol{r}_n$ and $\boldsymbol{r}_0$ is labeled as $$ W_{n0}=\frac{1}{2}mv_n^2-\frac{1}{2}mv_0^2=\int_{c}\boldsymbol{F}(\boldsymbol{r},\boldsymbol{v},t)d\boldsymbol{r}. $$ Note that if the force is perpendicular to the displacement, then the force does not affect the kinetic energy. Let us now study some examples of forces and how to find the velocity from the integration over a given path.
Formal statement is: lemma emeasure_Un': assumes "A \<in> sets M" "B \<in> sets M" "A \<inter> B \<in> null_sets M" shows "emeasure M (A \<union> B) = emeasure M A + emeasure M B" Informal statement is: If $A$ and $B$ are measurable sets and $A \cap B$ is a null set, then $A \cup B$ is measurable and $\mu(A \cup B) = \mu(A) + \mu(B)$.
(* Title: HOL/Groebner_Basis.thy Author: Amine Chaieb, TU Muenchen *) section \<open>Groebner bases\<close> theory Groebner_Basis imports Semiring_Normalization Parity begin subsection \<open>Groebner Bases\<close> lemmas bool_simps = simp_thms(1-34) \<comment> \<open>FIXME move to @{theory HOL}\<close> lemma nnf_simps: \<comment> \<open>FIXME shadows fact binding in @{theory HOL}\<close> "(\<not>(P \<and> Q)) = (\<not>P \<or> \<not>Q)" "(\<not>(P \<or> Q)) = (\<not>P \<and> \<not>Q)" "(P \<longrightarrow> Q) = (\<not>P \<or> Q)" "(P = Q) = ((P \<and> Q) \<or> (\<not>P \<and> \<not> Q))" "(\<not> \<not>(P)) = P" by blast+ lemma dnf: "(P & (Q | R)) = ((P&Q) | (P&R))" "((Q | R) & P) = ((Q&P) | (R&P))" "(P \<and> Q) = (Q \<and> P)" "(P \<or> Q) = (Q \<or> P)" by blast+ lemmas weak_dnf_simps = dnf bool_simps lemma PFalse: "P \<equiv> False \<Longrightarrow> \<not> P" "\<not> P \<Longrightarrow> (P \<equiv> False)" by auto named_theorems algebra "pre-simplification rules for algebraic methods" ML_file "Tools/groebner.ML" method_setup algebra = \<open> let fun keyword k = Scan.lift (Args.$$$ k -- Args.colon) >> K () val addN = "add" val delN = "del" val any_keyword = keyword addN || keyword delN val thms = Scan.repeats (Scan.unless any_keyword Attrib.multi_thm); in Scan.optional (keyword addN |-- thms) [] -- Scan.optional (keyword delN |-- thms) [] >> (fn (add_ths, del_ths) => fn ctxt => SIMPLE_METHOD' (Groebner.algebra_tac add_ths del_ths ctxt)) end \<close> "solve polynomial equations over (semi)rings and ideal membership problems using Groebner bases" declare dvd_def[algebra] declare mod_eq_0_iff_dvd[algebra] declare mod_div_trivial[algebra] declare mod_mod_trivial[algebra] declare div_by_0[algebra] declare mod_by_0[algebra] declare mult_div_mod_eq[algebra] declare div_minus_minus[algebra] declare mod_minus_minus[algebra] declare div_minus_right[algebra] declare mod_minus_right[algebra] declare div_0[algebra] declare mod_0[algebra] declare mod_by_1[algebra] declare div_by_1[algebra] declare mod_minus1_right[algebra] declare div_minus1_right[algebra] declare mod_mult_self2_is_0[algebra] declare mod_mult_self1_is_0[algebra] declare zmod_eq_0_iff[algebra] declare dvd_0_left_iff[algebra] declare zdvd1_eq[algebra] declare zmod_eq_dvd_iff[algebra] declare nat_mod_eq_iff[algebra] context semiring_parity begin declare even_times_iff [algebra] declare even_power [algebra] end context ring_parity begin declare even_minus [algebra] end declare even_Suc [algebra] declare even_diff_nat [algebra] end
module GRIN.Opts.CaseSimplify import GRIN.AST import GRIN.GrinM patToVal : CasePat name -> Val name patToVal (NodePat tag args) = ConstTagNode tag (SVar <$> args) patToVal (TagPat tag) = ConstTag tag patToVal (LitPat lit) = VUnit patToVal DefaultPat = VUnit simplify : Exp name -> Exp name simplify (SimpleExp exp) = SimpleExp $ mapExpSExp simplify exp simplify (Bind val exp rest) = Bind val (mapExpSExp simplify exp) (simplify rest) simplify (Case val alts) = case alts of [MkAlt DefaultPat exp] => simplify exp [MkAlt pat exp] => Bind (patToVal pat) (Pure val) (simplify exp) _ => Case val $ map (mapExpAlt simplify) alts export caseSimplify : Monad m => GrinT name m () caseSimplify = do mapProg $ mapExpProg simplify invalidate CallGraphs
The trial of Jasmine Williams, who was charged with murder in the September 2017 fatal shooting of Greg Swinson, 25, will begin Tuesday, Oct. 23, 2018 at the Coffee County Courthouse. Attorneys selected the jury today and both sides are set to start tomorrow. At 3 a.m. on Saturday, Sept. 16, 2017, Swinson was shot in the head in his home on the 300 block of East Walker Street. Swinson initially survived the shooting and was transported to Savannah Memorial Hospital for further treatment. However, he died a short time later.
module Test.Sodium import Crypto.Sodium key : IO Key key = do k <- newSymmKey setKeyChars k 0 [1..26] pure k where setKeyChars : Key -> Int -> List Int -> IO () setKeyChars k i [] = pure () setKeyChars k i (c :: cs) = do setKeyIdx k i ((c * 42) `mod` 255) setKeyChars k (i + 1) cs nonce : IO Nonce nonce = newNonceFromString "sdlfkjsdlkfjacvbnm,vbnmvhghjvbnasdasdm" export test : IO () test = do -- first, symmetric key hello world encrypted <- cryptoSecretBox "Hello world!" !nonce !key print (getBytes encrypted) decrypted <- cryptoSecretBoxOpen encrypted !nonce !key putStrLn (readBox decrypted) --- Now some public/private key stuff (alice_pub, alice_sec) <- newKeyPair -- generated by libsodium (bob_pub, bob_sec) <- newKeyPair -- generated by libsodium encrypted <- cryptoBox "Hello Bob!" !nonce alice_pub bob_sec print (getBytes encrypted) decrypted <- cryptoBoxOpen encrypted !nonce bob_pub alice_sec if (validOpenBox decrypted) then putStrLn (readBox decrypted) else putStrLn "Error"
% data.tex % % computational data processing section % % Samuel Rohrer \subsection{Prerequisites} \subsubsection{Programming experience in a few languages} \subsubsection{Data structures and algorithms experience} \subsubsection{Understanding of computer organization} \subsubsection{Understanding of discrete math and complexity measures} \subsection{Types of Databases: relational, key value, document} \subsection{SQL vs. NoSQL} \subsection{SQL: Redis, MariaDB, MySQL, PostgreSQL, SQLite} \subsection{SQL Queries} \subsection{Database indexes} \subsection{NoSQL: CouchDB, Cassandra, MongoDB, Elasticsearch, PouchDB} \subsection{Linux kernel and drivers, Operating System Threads, Mutexes \& Locks} \subsection{Hardware Parallel Processing} \subsection{Hyperthreading} \subsection{Multicore Systems} \subsection{Programming Multicore Systems \& Compilers} \subsection{Filesystems \& Server Architectures} \subsection{Networking and the Seven Layer Internet} \subsection{Application Specific Hardware: FPGA, GPU, GPGPU, TPU, ASIC} \subsection{Software Parallel Processing Libraries: OpenMP, CUDA, cuDNN} \subsection{Distributed Computing Paradigms} \subsection{Software Libraries for Distributed Computing} \subsection{Orchestration: Virtual Machine, Docker, Kubernetes, Mesos} \subsection{Cold Storage: Object Storage, NFS, HDFS} \subsection{Data Pipeline: Kafka, RabbitMQ, Pub/Sub, Flume (logs)} \subsection{Stream Processing: Hadoop, Flink, Storm} \subsection{Data Analysis: Hive, Spark, SparkML, Pig, Sawzall (logs)} \subsection{Workflow Automation Tools: cron, AirFlow, MLFlow} \subsection{Developer Operations, Continuous Integration, Continuous Deployment} \subsection{Cloud Infrastructure as a Service: GCP, AWS, Azure} \subsection{Deploying a simple application to a cloud infrastructure provider} \subsection{Asymptotic Performance, Performance Tuning (IO, memory, CPU)}
[STATEMENT] lemma split_at_take_drop_conv: "split_at n xs = (take n xs, drop n xs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. split_at n xs = (take n xs, drop n xs) [PROOF STEP] by (induction xs arbitrary: n) (auto simp: split: nat.split)
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov, YaΓ«l Dillies -/ import algebra.order.module import analysis.convex.star import linear_algebra.affine_space.affine_subspace /-! # Convex sets and functions in vector spaces In a π•œ-vector space, we define the following objects and properties. * `convex π•œ s`: A set `s` is convex if for any two points `x y ∈ s` it includes `segment π•œ x y`. * `std_simplex π•œ ΞΉ`: The standard simplex in `ΞΉ β†’ π•œ` (currently requires `fintype ΞΉ`). It is the intersection of the positive quadrant with the hyperplane `s.sum = 1`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex. ## TODO Generalize all this file to affine spaces. -/ variables {π•œ E F Ξ² : Type*} open linear_map set open_locale big_operators classical convex pointwise /-! ### Convexity of sets -/ section ordered_semiring variables [ordered_semiring π•œ] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_smul variables (π•œ) [has_smul π•œ E] [has_smul π•œ F] (s : set E) {x : E} /-- Convexity of sets. -/ def convex : Prop := βˆ€ ⦃x : E⦄, x ∈ s β†’ star_convex π•œ x s variables {π•œ s} lemma convex.star_convex (hs : convex π•œ s) (hx : x ∈ s) : star_convex π•œ x s := hs hx lemma convex_iff_segment_subset : convex π•œ s ↔ βˆ€ ⦃x⦄, x ∈ s β†’ βˆ€ ⦃y⦄, y ∈ s β†’ [x -[π•œ] y] βŠ† s := forallβ‚‚_congr $ Ξ» x hx, star_convex_iff_segment_subset lemma convex.segment_subset (h : convex π•œ s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x -[π•œ] y] βŠ† s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex π•œ s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment π•œ x y βŠ† s := (open_segment_subset_segment π•œ x y).trans (h.segment_subset hx hy) /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset : convex π•œ s ↔ βˆ€ ⦃a b : π•œβ¦„, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ s + b β€’ s βŠ† s := iff.intro begin rintro hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (Ξ» h x hx y hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) alias convex_iff_pointwise_add_subset ↔ convex.set_combo_subset _ lemma convex_empty : convex π•œ (βˆ… : set E) := Ξ» x, false.elim lemma convex_univ : convex π•œ (set.univ : set E) := Ξ» _ _, star_convex_univ _ lemma convex.inter {t : set E} (hs : convex π•œ s) (ht : convex π•œ t) : convex π•œ (s ∩ t) := Ξ» x hx, (hs hx.1).inter (ht hx.2) lemma convex_sInter {S : set (set E)} (h : βˆ€ s ∈ S, convex π•œ s) : convex π•œ (β‹‚β‚€ S) := Ξ» x hx, star_convex_sInter $ Ξ» s hs, h _ hs $ hx _ hs lemma convex_Inter {ΞΉ : Sort*} {s : ΞΉ β†’ set E} (h : βˆ€ i, convex π•œ (s i)) : convex π•œ (β‹‚ i, s i) := (sInter_range s) β–Έ convex_sInter $ forall_range_iff.2 h lemma convex_Interβ‚‚ {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} {s : Ξ  i, ΞΊ i β†’ set E} (h : βˆ€ i j, convex π•œ (s i j)) : convex π•œ (β‹‚ i j, s i j) := convex_Inter $ Ξ» i, convex_Inter $ h i lemma convex.prod {s : set E} {t : set F} (hs : convex π•œ s) (ht : convex π•œ t) : convex π•œ (s Γ—Λ’ t) := Ξ» x hx, (hs hx.1).prod (ht hx.2) lemma convex_pi {ΞΉ : Type*} {E : ΞΉ β†’ Type*} [Ξ  i, add_comm_monoid (E i)] [Ξ  i, has_smul π•œ (E i)] {s : set ΞΉ} {t : Ξ  i, set (E i)} (ht : βˆ€ ⦃i⦄, i ∈ s β†’ convex π•œ (t i)) : convex π•œ (s.pi t) := Ξ» x hx, star_convex_pi $ Ξ» i hi, ht hi $ hx _ hi lemma directed.convex_Union {ΞΉ : Sort*} {s : ΞΉ β†’ set E} (hdir : directed (βŠ†) s) (hc : βˆ€ ⦃i : ι⦄, convex π•œ (s i)) : convex π•œ (⋃ i, s i) := begin rintro x hx y hy a b ha hb hab, rw mem_Union at ⊒ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on (βŠ†) c) (hc : βˆ€ ⦃A : set E⦄, A ∈ c β†’ convex π•œ A) : convex π•œ (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (Ξ» A, hc A.2), end end has_smul section module variables [module π•œ E] [module π•œ F] {s : set E} {x : E} lemma convex_iff_open_segment_subset : convex π•œ s ↔ βˆ€ ⦃x⦄, x ∈ s β†’ βˆ€ ⦃y⦄, y ∈ s β†’ open_segment π•œ x y βŠ† s := forallβ‚‚_congr $ Ξ» x, star_convex_iff_open_segment_subset lemma convex_iff_forall_pos : convex π•œ s ↔ βˆ€ ⦃x⦄, x ∈ s β†’ βˆ€ ⦃y⦄, y ∈ s β†’ βˆ€ ⦃a b : π•œβ¦„, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s := forallβ‚‚_congr $ Ξ» x, star_convex_iff_forall_pos lemma convex_iff_pairwise_pos : convex π•œ s ↔ s.pairwise (Ξ» x y, βˆ€ ⦃a b : π•œβ¦„, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s) := begin refine convex_iff_forall_pos.trans ⟨λ h x hx y hy _, h hx hy, _⟩, intros h x hx y hy a b ha hb hab, obtain rfl | hxy := eq_or_ne x y, { rwa convex.combo_self hab }, { exact h hx hy hxy ha hb hab }, end lemma convex.star_convex_iff (hs : convex π•œ s) (h : s.nonempty) : star_convex π•œ x s ↔ x ∈ s := ⟨λ hxs, hxs.mem h, hs.star_convex⟩ protected lemma set.subsingleton.convex {s : set E} (h : s.subsingleton) : convex π•œ s := convex_iff_pairwise_pos.mpr (h.pairwise _) lemma convex_singleton (c : E) : convex π•œ ({c} : set E) := subsingleton_singleton.convex lemma convex_segment (x y : E) : convex π•œ [x -[π•œ] y] := begin rintro p ⟨ap, bp, hap, hbp, habp, rfl⟩ q ⟨aq, bq, haq, hbq, habq, rfl⟩ a b ha hb hab, refine ⟨a * ap + b * aq, a * bp + b * bq, add_nonneg (mul_nonneg ha hap) (mul_nonneg hb haq), add_nonneg (mul_nonneg ha hbp) (mul_nonneg hb hbq), _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add], exact add_add_add_comm _ _ _ _ } end lemma convex.linear_image (hs : convex π•œ s) (f : E β†’β‚—[π•œ] F) : convex π•œ (f '' s) := begin intros x hx y hy a b ha hb hab, obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx, obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy, exact ⟨a β€’ x' + b β€’ y', hs hx' hy' ha hb hab, by rw [f.map_add, f.map_smul, f.map_smul]⟩, end lemma convex.is_linear_image (hs : convex π•œ s) {f : E β†’ F} (hf : is_linear_map π•œ f) : convex π•œ (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex π•œ s) (f : E β†’β‚—[π•œ] F) : convex π•œ (f ⁻¹' s) := begin intros x hx y hy a b ha hb hab, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy ha hb hab, end lemma convex.is_linear_preimage {s : set F} (hs : convex π•œ s) {f : E β†’ F} (hf : is_linear_map π•œ f) : convex π•œ (f ⁻¹' s) := hs.linear_preimage $ hf.mk' f lemma convex.add {t : set E} (hs : convex π•œ s) (ht : convex π•œ t) : convex π•œ (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.vadd (hs : convex π•œ s) (z : E) : convex π•œ (z +α΅₯ s) := by { simp_rw [←image_vadd, vadd_eq_add, ←singleton_add], exact (convex_singleton _).add hs } lemma convex.translate (hs : convex π•œ s) (z : E) : convex π•œ ((Ξ» x, z + x) '' s) := hs.vadd _ /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex π•œ s) (z : E) : convex π•œ ((Ξ» x, z + x) ⁻¹' s) := begin intros x hx y hy a b ha hb hab, have h := hs hx hy ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex π•œ s) (z : E) : convex π•œ ((Ξ» x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right z section ordered_add_comm_monoid variables [ordered_add_comm_monoid Ξ²] [module π•œ Ξ²] [ordered_smul π•œ Ξ²] lemma convex_Iic (r : Ξ²) : convex π•œ (Iic r) := Ξ» x hx y hy a b ha hb hab, calc a β€’ x + b β€’ y ≀ a β€’ r + b β€’ r : add_le_add (smul_le_smul_of_nonneg hx ha) (smul_le_smul_of_nonneg hy hb) ... = r : convex.combo_self hab _ lemma convex_Ici (r : Ξ²) : convex π•œ (Ici r) := @convex_Iic π•œ Ξ²α΅’α΅ˆ _ _ _ _ r lemma convex_Icc (r s : Ξ²) : convex π•œ (Icc r s) := Ici_inter_Iic.subst ((convex_Ici r).inter $ convex_Iic s) lemma convex_halfspace_le {f : E β†’ Ξ²} (h : is_linear_map π•œ f) (r : Ξ²) : convex π•œ {w | f w ≀ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_ge {f : E β†’ Ξ²} (h : is_linear_map π•œ f) (r : Ξ²) : convex π•œ {w | r ≀ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E β†’ Ξ²} (h : is_linear_map π•œ f) (r : Ξ²) : convex π•œ {w | f w = r} := begin simp_rw le_antisymm_iff, exact (convex_halfspace_le h r).inter (convex_halfspace_ge h r), end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid Ξ²] [module π•œ Ξ²] [ordered_smul π•œ Ξ²] lemma convex_Iio (r : Ξ²) : convex π•œ (Iio r) := begin intros x hx y hy a b ha hb hab, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [zero_smul, zero_add, hab, one_smul] }, rw mem_Iio at hx hy, calc a β€’ x + b β€’ y < a β€’ r + b β€’ r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb) ... = r : convex.combo_self hab _ end lemma convex_Ioi (r : Ξ²) : convex π•œ (Ioi r) := @convex_Iio π•œ Ξ²α΅’α΅ˆ _ _ _ _ r lemma convex_Ioo (r s : Ξ²) : convex π•œ (Ioo r s) := Ioi_inter_Iio.subst ((convex_Ioi r).inter $ convex_Iio s) lemma convex_Ico (r s : Ξ²) : convex π•œ (Ico r s) := Ici_inter_Iio.subst ((convex_Ici r).inter $ convex_Iio s) lemma convex_Ioc (r s : Ξ²) : convex π•œ (Ioc r s) := Ioi_inter_Iic.subst ((convex_Ioi r).inter $ convex_Iic s) lemma convex_halfspace_lt {f : E β†’ Ξ²} (h : is_linear_map π•œ f) (r : Ξ²) : convex π•œ {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_gt {f : E β†’ Ξ²} (h : is_linear_map π•œ f) (r : Ξ²) : convex π•œ {w | r < f w} := (convex_Ioi r).is_linear_preimage h end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid Ξ²] [module π•œ Ξ²] [ordered_smul π•œ Ξ²] lemma convex_uIcc (r s : Ξ²) : convex π•œ (uIcc r s) := convex_Icc _ _ end linear_ordered_add_comm_monoid end module end add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid E] [ordered_add_comm_monoid Ξ²] [module π•œ E] [ordered_smul π•œ E] {s : set E} {f : E β†’ Ξ²} lemma monotone_on.convex_le (hf : monotone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | f x ≀ r} := Ξ» x hx y hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab, (hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans (max_rec' _ hx.2 hy.2)⟩ lemma monotone_on.convex_lt (hf : monotone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | f x < r} := Ξ» x hx y hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab, (hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans_lt (max_rec' _ hx.2 hy.2)⟩ lemma monotone_on.convex_ge (hf : monotone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | r ≀ f x} := @monotone_on.convex_le π•œ Eα΅’α΅ˆ Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf.dual hs r lemma monotone_on.convex_gt (hf : monotone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | r < f x} := @monotone_on.convex_lt π•œ Eα΅’α΅ˆ Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf.dual hs r lemma antitone_on.convex_le (hf : antitone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | f x ≀ r} := @monotone_on.convex_ge π•œ E Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_lt (hf : antitone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | f x < r} := @monotone_on.convex_gt π•œ E Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_ge (hf : antitone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | r ≀ f x} := @monotone_on.convex_le π•œ E Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_gt (hf : antitone_on f s) (hs : convex π•œ s) (r : Ξ²) : convex π•œ {x ∈ s | r < f x} := @monotone_on.convex_lt π•œ E Ξ²α΅’α΅ˆ _ _ _ _ _ _ _ hf hs r lemma monotone.convex_le (hf : monotone f) (r : Ξ²) : convex π•œ {x | f x ≀ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma monotone.convex_lt (hf : monotone f) (r : Ξ²) : convex π•œ {x | f x ≀ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma monotone.convex_ge (hf : monotone f ) (r : Ξ²) : convex π•œ {x | r ≀ f x} := set.sep_univ.subst ((hf.monotone_on univ).convex_ge convex_univ r) lemma monotone.convex_gt (hf : monotone f) (r : Ξ²) : convex π•œ {x | f x ≀ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma antitone.convex_le (hf : antitone f) (r : Ξ²) : convex π•œ {x | f x ≀ r} := set.sep_univ.subst ((hf.antitone_on univ).convex_le convex_univ r) lemma antitone.convex_lt (hf : antitone f) (r : Ξ²) : convex π•œ {x | f x < r} := set.sep_univ.subst ((hf.antitone_on univ).convex_lt convex_univ r) lemma antitone.convex_ge (hf : antitone f) (r : Ξ²) : convex π•œ {x | r ≀ f x} := set.sep_univ.subst ((hf.antitone_on univ).convex_ge convex_univ r) lemma antitone.convex_gt (hf : antitone f) (r : Ξ²) : convex π•œ {x | r < f x} := set.sep_univ.subst ((hf.antitone_on univ).convex_gt convex_univ r) end linear_ordered_add_comm_monoid end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring π•œ] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] [module π•œ E] [module π•œ F] {s : set E} lemma convex.smul (hs : convex π•œ s) (c : π•œ) : convex π•œ (c β€’ s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (hs : convex π•œ s) (c : π•œ) : convex π•œ ((Ξ» z, c β€’ z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.affinity (hs : convex π•œ s) (z : E) (c : π•œ) : convex π•œ ((Ξ» x, z + c β€’ x) '' s) := by simpa only [←image_smul, ←image_vadd, image_image] using (hs.smul c).vadd z end add_comm_monoid end ordered_comm_semiring section strict_ordered_comm_semiring variables [strict_ordered_comm_semiring π•œ] [add_comm_group E] [module π•œ E] lemma convex_open_segment (a b : E) : convex π•œ (open_segment π•œ a b) := begin rw convex_iff_open_segment_subset, rintro p ⟨ap, bp, hap, hbp, habp, rfl⟩ q ⟨aq, bq, haq, hbq, habq, rfl⟩ z ⟨a, b, ha, hb, hab, rfl⟩, refine ⟨a * ap + b * aq, a * bp + b * bq, by positivity, by positivity, _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add, add_add_add_comm] } end end strict_ordered_comm_semiring section ordered_ring variables [ordered_ring π•œ] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module π•œ E] [module π•œ F] {s t : set E} lemma convex.add_smul_mem (hs : convex π•œ s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : π•œ} (ht : t ∈ Icc (0 : π•œ) 1) : x + t β€’ y ∈ s := begin have h : x + t β€’ y = (1 - t) β€’ x + t β€’ (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, exact hs hx hy (sub_nonneg_of_le ht.2) ht.1 (sub_add_cancel _ _), end lemma convex.smul_mem_of_zero_mem (hs : convex π•œ s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : π•œ} (ht : t ∈ Icc (0 : π•œ) 1) : t β€’ x ∈ s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.add_smul_sub_mem (h : convex π•œ s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : π•œ} (ht : t ∈ Icc (0 : π•œ) 1) : x + t β€’ (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', exact mem_image_of_mem _ ht, end /-- Affine subspaces are convex. -/ lemma affine_subspace.convex (Q : affine_subspace π•œ E) : convex π•œ (Q : set E) := begin intros x hx y hy a b ha hb hab, rw [eq_sub_of_add_eq hab, ← affine_map.line_map_apply_module], exact affine_map.line_map_mem b hx hy, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᡃ[π•œ] F) {s : set F} (hs : convex π•œ s) : convex π•œ (f ⁻¹' s) := Ξ» x hx, (hs hx).affine_preimage _ /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᡃ[π•œ] F) (hs : convex π•œ s) : convex π•œ (f '' s) := by { rintro _ ⟨x, hx, rfl⟩, exact (hs hx).affine_image _ } lemma convex.neg (hs : convex π•œ s) : convex π•œ (-s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.sub (hs : convex π•œ s) (ht : convex π•œ t) : convex π•œ (s - t) := by { rw sub_eq_add_neg, exact hs.add ht.neg } end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field π•œ] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module π•œ E] [module π•œ F] {s : set E} /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div : convex π•œ s ↔ βˆ€ ⦃x⦄, x ∈ s β†’ βˆ€ ⦃y⦄, y ∈ s β†’ βˆ€ ⦃a b : π•œβ¦„, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ (a / (a + b)) β€’ x + (b / (a + b)) β€’ y ∈ s := forallβ‚‚_congr $ Ξ» x hx, star_convex_iff_div lemma convex.mem_smul_of_zero_mem (h : convex π•œ s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : π•œ} (ht : 1 ≀ t) : x ∈ t β€’ s := begin rw mem_smul_set_iff_inv_smul_memβ‚€ (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end lemma convex.add_smul (h_conv : convex π•œ s) {p q : π•œ} (hp : 0 ≀ p) (hq : 0 ≀ q) : (p + q) β€’ s = p β€’ s + q β€’ s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty, add_empty] }, obtain rfl | hp' := hp.eq_or_lt, { rw [zero_add, zero_smul_set hs, zero_add] }, obtain rfl | hq' := hq.eq_or_lt, { rw [add_zero, zero_smul_set hs, add_zero] }, ext, split, { rintro ⟨v, hv, rfl⟩, exact ⟨p β€’ v, q β€’ v, smul_mem_smul_set hv, smul_mem_smul_set hv, (add_smul _ _ _).symm⟩ }, { rintro ⟨v₁, vβ‚‚, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, hβ‚‚β‚‚, rfl⟩, rfl⟩, have hpq := add_pos hp' hq', refine mem_smul_set.2 ⟨_, h_conv h₁₂ hβ‚‚β‚‚ _ _ (by rw [←div_self hpq.ne', add_div] : p / (p + q) + q / (p + q) = 1), by simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne']⟩; positivity } end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `ord_connected`. -/ section lemma set.ord_connected.convex_of_chain [ordered_semiring π•œ] [ordered_add_comm_monoid E] [module π•œ E] [ordered_smul π•œ E] {s : set E} (hs : s.ord_connected) (h : is_chain (≀) s) : convex π•œ s := begin refine convex_iff_segment_subset.mpr (Ξ» x hx y hy, _), obtain hxy | hyx := h.total hx hy, { exact (segment_subset_Icc hxy).trans (hs.out hx hy) }, { rw segment_symm, exact (segment_subset_Icc hyx).trans (hs.out hy hx) } end lemma set.ord_connected.convex [ordered_semiring π•œ] [linear_ordered_add_comm_monoid E] [module π•œ E] [ordered_smul π•œ E] {s : set E} (hs : s.ord_connected) : convex π•œ s := hs.convex_of_chain $ is_chain_of_trichotomous s lemma convex_iff_ord_connected [linear_ordered_field π•œ] {s : set π•œ} : convex π•œ s ↔ s.ord_connected := by simp_rw [convex_iff_segment_subset, segment_eq_uIcc, ord_connected_iff_uIcc_subset] alias convex_iff_ord_connected ↔ convex.ord_connected _ end /-! #### Convexity of submodules/subspaces -/ namespace submodule variables [ordered_semiring π•œ] [add_comm_monoid E] [module π•œ E] protected lemma convex (K : submodule π•œ E) : convex π•œ (↑K : set E) := by { repeat {intro}, refine add_mem (smul_mem _ _ _) (smul_mem _ _ _); assumption } protected lemma star_convex (K : submodule π•œ E) : star_convex π•œ (0 : E) K := K.convex K.zero_mem end submodule /-! ### Simplex -/ section simplex variables (π•œ) (ΞΉ : Type*) [ordered_semiring π•œ] [fintype ΞΉ] /-- The standard simplex in the space of functions `ΞΉ β†’ π•œ` is the set of vectors with non-negative coordinates with total sum `1`. This is the free object in the category of convex spaces. -/ def std_simplex : set (ΞΉ β†’ π•œ) := {f | (βˆ€ x, 0 ≀ f x) ∧ βˆ‘ x, f x = 1} lemma std_simplex_eq_inter : std_simplex π•œ ΞΉ = (β‹‚ x, {f | 0 ≀ f x}) ∩ {f | βˆ‘ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_iff, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex π•œ (std_simplex π•œ ΞΉ) := begin refine Ξ» f hf g hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ΞΉ} lemma ite_eq_mem_std_simplex (i : ΞΉ) : (Ξ» j, ite (i = j) (1:π•œ) 0) ∈ std_simplex π•œ ΞΉ := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ end simplex
Require Import Tutorial. (* A specification of what it means to choose a number that is not in a particular list *) Definition notInList (ls : list nat) := {n : nat | ~In n ls}%comp. (* We can use a simple property to justify a decomposition of the original spec. *) Theorem notInList_decompose : forall ls, refine (notInList ls) (upper <- {upper | forall n, In n ls -> upper >= n}; {beyond | beyond > upper}). Proof. refines. firstorder. Qed. (* A simple traversal will find the maximum list element, which is a good upper bound. *) Definition listMax := fold_right max 0. (* ...and we can prove it! *) Theorem listMax_upperBound : forall init ls, forall n, In n ls -> fold_right max init ls >= n. Proof. induction ls; simpl; intuition. arithmetic. apply IHls in H0. arithmetic. Qed. (* Now we restate that result as a computation refinement. *) Theorem listMax_refines : forall ls, refine {upper | forall n, In n ls -> upper >= n} (ret (listMax ls)). Proof. refines. apply listMax_upperBound. Qed. (* An easy way to find a number higher than another: add 1! *) Theorem increment_refines : forall n, refine {higher | higher > n} (ret (n + 1)). Proof. refines. arithmetic. Qed. (* Let's derive an efficient implementation. *) Theorem implementation : { f : list nat -> Comp nat | forall ls, refine (notInList ls) (f ls) }. Proof. begin. rewrite notInList_decompose. rewrite listMax_refines. setoid_rewrite increment_refines. (* Different tactic here to let us rewrite under a binder! *) monad_simpl. finish honing. Defined. (* We can extract the program that we found as a standlone, executable Gallina term. *) Definition impl := Eval simpl in projT1 implementation. Print impl. Eval compute in impl (1 :: 7 :: 8 :: 2 :: 13 :: 6 :: nil).
module Network.Mux.DeltaQ.TraceStatsSupport where -- This module is making use of hackage statisitical libraries. They -- are not the most efficicient approches for this particlular use -- case, and they may increase the package dependencies for the final -- binaries (they have a lot of dependencies). -- -- It may well be worthwhile constructing specialsed version for the -- specific use case, but building those and creating the associated -- test suite was not deemed a good use of time (at the time of -- creation). -- -- Definite space/time optimisation task here. import Network.Mux.DeltaQ.TraceTypes import qualified Data.Vector.Unboxed as V import Statistics.LinearRegression estimateGS :: [(Int, SISec)] -> (Double, Double, Double) estimateGS xys = let (xs', ys') = unzip xys xs = V.fromList $ map fromIntegral xs' ys = V.fromList $ map (\(S x) -> fromRational . toRational $ x) ys' in linearRegressionRSqr xs ys
{-# OPTIONS --cubical-compatible --rewriting --confluence-check #-} postulate _↦_ : {A : Set} β†’ A β†’ A β†’ Set {-# BUILTIN REWRITE _↦_ #-} data _==_ {A : Set} (a : A) : A β†’ Set where idp : a == a PathOver : {A : Set} (B : A β†’ Set) {x y : A} (p : x == y) (u : B x) (v : B y) β†’ Set PathOver B idp u v = (u == v) infix 30 PathOver syntax PathOver B p u v = u == v [ B ↓ p ] apd : {A : Set} {B : A β†’ Set} (f : (a : A) β†’ B a) {x y : A} β†’ (p : x == y) β†’ f x == f y [ B ↓ p ] apd f idp = idp module Disk where module _ where postulate -- HIT Disk : Set baseD : Disk loopD : baseD == baseD drumD : loopD == idp module DiskElim {P : Disk β†’ Set} (baseD* : P baseD ) (loopD* : baseD* == baseD* [ P ↓ loopD ] ) (drumD* : loopD* == idp [ ((Ξ» p β†’ baseD* == baseD* [ P ↓ p ] ) ) ↓ drumD ] ) where postulate f : (x : Disk) β†’ P x baseD-Ξ² : f baseD ↦ baseD* {-# REWRITE baseD-Ξ² #-} postulate loopD-ΞΉ : apd f loopD ↦ loopD* {-# REWRITE loopD-ΞΉ #-} postulate drumD-ΞΉ : apd (apd f) drumD ↦ drumD* {-# REWRITE drumD-ΞΉ #-} loopD-Ξ² : apd f loopD == loopD* loopD-Ξ² = idp drumD-Ξ² : apd (apd f) drumD == drumD* drumD-Ξ² = idp
Codium fragile ssp. fragile ( formerly reported as ssp. tomentosum ) , now well established .
%!TEX program = pdflatex \documentclass{elegantpaper} \captionsetup{belowskip=-10pt} \usepackage{multirow} \usepackage{float} \usepackage{listings} \usepackage{subfigure} \title{Doubly Robust Estimation and Causal Inference Model} \author{Weitong Yao\quad Yuwei Zheng} \date{\small\itshape Version: 0.01 \\ Last update: \today} \begin{document} \maketitle \begin{abstract} Doubly robust estimation (DR) is a combination of outcome regression (OR) and inverse propensity weighted score model (IPW). If one of these models is correctly specified, the ATE of doubly robust is the unbiased, consistent estimator of average treatment effect estimator under the assumption of no unmeasured confounders. This paper provides a conceptual overview of IPW and DR, compares different MSE and ATE from simulations under different circumstances, and discusses the possible improvements and limitations of DR. \end{abstract} %-------------------------- % 1. Introduction %-------------------------- \section{Introduction} Doubly Robust is a robust protected model to study causal inferences. The term doubly robustness is constructed based on the Augmented Inverse Probability Weighted Estimators (AIPW), proposed by Robins, Rotnitzky and Zhao (1994). They provided a method to study regression coefficients with missing regressors, which improves the efficiency of estimation. This algorithm is further extended and issues about this methodology are studied by many researchers (Robins, J. M., Van der Laan, M. J., Brookhart, M. A., etc.). In the introduction, we mainly review some related concepts and algorithms for DR estimations. This article is organized as follows: in Section 2, we begin to compare different models, including pure linear model, IPW, traditional DR, constrained weighting ensemble models, and unconstrained weighting ensemble models. In Section 3, we obtain conclusions and results from our simulation studies. The discussion of DR is illustrated in Section 4. \subsection*{Conceptual Review} We define $X = 1$ if it's treated and $X = 0$ if it's under control, Y as observed outcome and Z as observed, measurable confounders, and the full dataset is $(Y_i, X_i, Z_i)\quad i = 1,...,n $ for individuals. What we are interested in is to find the average treatment effect\quad $\tau = E(Y|X=1,Z) - E(Y|X=0,Z)$. It is a counterfactual issue because we can't see all potential outcomes $(Y_1,Y_0)$ for all individuals, instead we can only observe $Y = Y_1X+Y_0(1-X)$, which is critical. Regression is one approach to estimate $\tau$, and it requires the postulated regression model is true and identical and no unmeasurable confounders. In this situation, the ATE of outcome regression is calculated as follows, that's the marginal effect of treatment (maximum likelihood estimate)is exactly the ATE for regression method. \begin{equation} \begin{split} E(Y|X, Z) =& \beta_0 + \beta_x X + \beta_z Z\\ \tau_{reg} =& E(Y|X=1, Z) - E(Y|X=0, Z)\\ =& (\hat{\beta_0} + \hat{\beta_x} \times 1 + \hat{\beta_z} Z)- (\hat{\beta_0} + \hat{\beta_x} \times 0 + \hat{\beta_z} Z)\\ =& \hat{\beta_x} \end{split} \end{equation} Another way to estimate $\tau$ is inverse propensity weighted score model(IPW), the reason for β€œinverse propensity” is to provide even weighting for treatment group and control group: \begin{equation} \tau_{ ipw} =\frac{1}{n} \sum_{i=1}^{n} \big[\frac{X_{i} Y_{i}}{P(X=1 | Z)}-\frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}\big] \end{equation} Under assumptions that at least one of two models is correctly specified and no unmeasurable confounders, the ATE of doubly robust is defined as follows, and it's obviously a linear combination of outcome regression and inverse propensity weighted model with weighs equal $\frac{P(X | Z)-X_{i}}{P(X | Z)}$ and 1 respectively. \begin{equation} \begin{split} \tau_{D R}=&\frac{1}{n} \sum_{i=1}^{n} \big[ \frac{P(X=1 | Z)-X_{i}}{P(X=1 | Z)}\widehat{Y_1}+\frac{X_{i} Y_{i}}{P(X=1 | Z)}\big] - \\ &{\frac{1}{n} \sum_{i=1}^{n} \big[ \frac{(1-P(X=1 | Z))-(1-X_{i})}{1-P(X=1 | Z)}\widehat{Y_0}+\frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}}\big]\\ =&\tau_{1,D R} - \tau_{0,D R} \end{split} \end{equation} \begin{equation} \begin{split} where,\ \ \tau_{1,D R} =& E(Y_1) + E\big[ \frac{P(X=1 | Z)-X_{i}}{P(X=1 | Z)}(\widehat{Y_1}-Y_1)\big]\\ and,\ \ \tau_{0,D R} =& E(Y_0) + E\big[ \frac{X_{i}-P(X=1 | Z)}{1-P(X=1 | Z)}\widehat{Y_0}\big] \end{split} \end{equation} \smallskip $\tau_{1,D R}$ is the function of observed outcome $Y_1$ and predicted outcome $\widehat{Y_1}$, $\tau_{0,D R}$ depends on $\widehat{Y_0}$ only as we can't observe $Y_0$, and $P(X=1| Z)$ is derived from logistic regression. If the OR is true, $E(Y-\hat{Y})=0$; if IPW is true, we have $E(P(X=1 | Z)-X)=0$. In either scenario, ATE of DR is always $E(Y_1)-E(Y_0)$, which is an unbiased, consistent estimator for ATE. %---------------------------------------- % 2.Stacking Models and Comparison %---------------------------------------- \section{Stacking Models and Comparison} What if the weights are more flexible, will the stacking model of OR and IPW perform better than traditional doubly robust model? In this section, we apply more flexible weights with each model and compare its ATE to different traditional models with different simulations and number of observations. All simulations are conducted by using cross-validation with five folders. %---------- 2.1 Constrained Weighted ---------- \subsection{Constrained Weighted Stacking Model} The advantage of constrained weighting is that it provides better interpretation. If the weight of OR is defined as $w_1$, the weight of IPW is $w_2 = 1 - w_1$. The logic to find optimal weighting is to minimize mean squared error. Details about simulation are: \begin{equation} \begin{split} Z \sim&N(0,2), \ X \sim binomial(1,sigmoid(Z)), \ Y = X + Z + \varepsilon \\ OR =&Y \sim X+Z \quad\quad IPW= \frac{X_{i} Y_{i}}{P(X=1 | Z)} + \frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}\ \end{split} \end{equation} And the Constrained Weighted Stacking Model is defined as: \begin{equation} \begin{split} Stack_{1} =&w_1 \times \widehat{Y_1} + w_2 \times \frac{X_{i} Y_{i}}{P(X=1 | Z)}\\ Stack_{0} =&w_1 \times \widehat{Y_0} + w_2 \times \frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}\\ &w_1 + w_2 = 1 \end{split} \end{equation} The simulation contains three kinds of $P(X=1 | Z)$: gaussian, logit and probit. The mean optimal weight of OR under different number of observations and $P(X=1 | Z)$ is \bigskip \begin{table}[!htbp] \small \centering \caption{Average Optimal Weight of OR} \begin{tabular}{llll} \toprule & \multicolumn{1}{c}{Gaussian} & \multicolumn{1}{c}{Logit} & \multicolumn{1}{c}{Probit}\\ \midrule n = 500 & \multicolumn{1}{c}{ 0.5443383} & \multicolumn{1}{c}{0.6085503} & \multicolumn{1}{c}{0.5982036}\\ n = 1000 & \multicolumn{1}{c}{0.7070444} & \multicolumn{1}{c}{ 0.8213404} & \multicolumn{1}{c}{ 0.8078634}\\ n = 2000 & \multicolumn{1}{c}{0.8346533} & \multicolumn{1}{c}{0.9117676} & \multicolumn{1}{c}{0.9143612}\\ n = 5000 & \multicolumn{1}{c}{0.9505096} & \multicolumn{1}{c}{0.951561} & \multicolumn{1}{c}{0.9718606}\\ \midrule \end{tabular}% \label{tab:reg}% \end{table}% The results make sense: (1) As the number of observations increase, the simulation is more convincible and the weight of OR increases largely, according with $Y = X + Z + \varepsilon $. (2) If the independent variable is binary, there is little difference between logit regression and probit regression. (3) The speed of convergence(the fitted model converged to OR) is faster under Logit and Probit, compared with Gaussian. The vertical axis of graphs represent MSE for testing dataset. (4) Further discovery: the optimal weight of OR is larger than that of IPW until $\alpha >= 4$ in $Y = Z^\alpha + X + \varepsilon$, it seems OR is a better fitted model (however, the MSE is so large under $\alpha > 1$, which means the discovery may be unreasonable.) \begin{figure}[H] \setlength{\abovedisplayskip}{1pt} \setlength{\belowdisplayskip}{1pt} \subfigure[gaussian with n = 500]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{gaussian_500.png} \end{minipage}% }% \subfigure[gaussian with n = 1000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{gaussian_1000.png} %\caption{fig2} \end{minipage}% }% \subfigure[gaussian with n = 2000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{gaussian_2000.png} \end{minipage} } \end{figure} \begin{figure}[H] \subfigure[logit with n = 500]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{logit_500.png} \end{minipage}% }% \subfigure[logit with n = 1000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{logit_1000.png} %\caption{fig2} \end{minipage}% }% \subfigure[logit with n = 2000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{logit_2000.png} \end{minipage} } \subfigure[probit with n = 500]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{probit_500.png} \end{minipage}% }% \subfigure[probit with n = 1000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{probit_1000.png} %\caption{fig2} \end{minipage}% }% \subfigure[probit with n = 2000]{ \begin{minipage}[t]{0.36\linewidth} \includegraphics[width=2.5in]{probit_2000.png} \end{minipage} } \end{figure} \smallskip %---------- 2.2 Unconstrained Weighted ---------- \subsection{Unconstrained Weighted Stacking Model} The unconstrained weighted stacking model may provide better fitted outcome at the cost of better interpretation. Suppose $w_1, w_2$ are weights for OR and IPW respectively and keep the settings same as section 2.1. By using β€œbrute traversal” weights between 0 and 1, we obtain 3D plots for each folder : \begin{figure}[H] \setlength{\abovecaptionskip}{0.cm} \setlength{\belowcaptionskip}{0.cm} \subfigure[1st training fold with n = 1000]{ \begin{minipage}[t]{0.5\linewidth} \includegraphics[width=2.5in]{Rplot1.png} \end{minipage}% }% \subfigure[2nd training fold with n = 1000]{ \begin{minipage}[t]{0.5\linewidth} \includegraphics[width=2.5in]{Rplot2.png} %\caption{fig2} \end{minipage}% }% \end{figure} \begin{figure}[H] \subfigure[3rd training fold with n = 1000]{ \begin{minipage}[t]{0.5\linewidth} \includegraphics[width=2.5in]{Rplot3.png} \end{minipage} }% \subfigure[4th training fold with n = 1000]{ \begin{minipage}[t]{0.5\linewidth} \includegraphics[width=2.5in]{Rplot4.png} \end{minipage} } \end{figure} The optimal weights are stable at around 0.91 and 0.05 with increasing n. \smallskip %---------- 2.3 Comparison ---------- \subsection{Result Comparison} \subsubsection{Model Definition} We study and compare MSE, ATE and variance of outcome regression, IPW, Doubly Robust, OLS ensemble(lsen), constrained weighted stacking model(stack) and unconstrained weighted stacking model(Unstack). As defined earlier, \begin{equation} \begin{split} f_{1}=&w_1 \times \widehat{Y_1} + w_2 \times \frac{X_{i} Y_{i}}{P(X=1 | Z)}\\ f_{0}=&w_1 \times \widehat{Y_0} + w_2 \times \frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}\\ \tau_{stack} &= E(f_{1}) - E(f_{0}) \ \ \ \ with \ \ \ w_1 + w_2 = 1\\ \tau_{Unstack} &= E(f_{1}) - E(f_{0}) \ \ \ \ with \ \ \ w_1,w_2 \in [0,1] \end{split} \end{equation} The OLS ensemble model is obtain using the following procedure: \begin{itemize} \item Using training data set in cv, regress $\widehat{Y_1}$ and $\frac{X_{i} Y_{i}}{P(X=1 | Z)}$ on Y | X=1(observed $Y_1$) then we get $Y_1 = \hat{\beta_1} \widehat{Y_1} + \hat{\beta_2} \frac{X_{i} Y_{i}}{P(X=1 | Z)}$ \item Using training data set in cv, regress $\widehat{Y_0}$ and $\frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}$ on Y | X=0(observed $Y_0$) then we get $Y_0 = \hat{\beta_3} \widehat{Y_0} + \hat{\beta_4} \frac{\left(1-X_{i}\right) Y_{i}}{1-P(X=1 | Z)}$ \item Apply two linear regression model on testing data and get $\mathcal{Y}_1$ and $\mathcal{Y}_0$ \item $\tau_{lsen} = E(\mathcal{Y}_1) - E(\mathcal{Y}_0)$ \end{itemize} \subsubsection{Model Comparison} We compare the efficiency of six causal inference model by changing different initial settings and number of observations by spliting the dataset into 10 folders and applying cross-validation, the comparisons are shown in the following table. \bigskip % comparison with n = 500 \begin{table}[H] \small \centering \caption{Comparing Causal Inference Model with n = 500} \begin{tabular}{llllllll} \toprule Settings & \multicolumn{1}{c}{Indicator} &\multicolumn{1}{c}{Reg} & \multicolumn{1}{c}{IPW} & \multicolumn{1}{c}{DR} & \multicolumn{1}{c}{LSEN} & \multicolumn{1}{c}{Stack} & \multicolumn{1}{c}{Unstack}\\ \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{0.951430} & \multicolumn{1}{c}{1.011689} & \multicolumn{1}{c}{1.009087} & \multicolumn{1}{c}{3.444393}& \multicolumn{1}{c}{1.017201} & \multicolumn{1}{c}{0.978468}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{ 0.023993} & \multicolumn{1}{c}{1.112388} & \multicolumn{1}{c}{0.232103} & \multicolumn{1}{c}{0.033396}& \multicolumn{1}{c}{ 0.054101} & \multicolumn{1}{c}{0.058459}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{0.934337} & \multicolumn{1}{c}{85.261919} & \multicolumn{1}{c}{3.847946} & \multicolumn{1}{c}{6.811522}& \multicolumn{1}{c}{4.129348} & \multicolumn{1}{c}{3.402911}\\%%%%%%%%%%% \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{0.956788} & \multicolumn{1}{c}{1.189190} & \multicolumn{1}{c}{ 1.016797} & \multicolumn{1}{c}{ 1.340817}& \multicolumn{1}{c}{1.021133} & \multicolumn{1}{c}{ 0.918498}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.019725} & \multicolumn{1}{c}{0.148412} & \multicolumn{1}{c}{0.087840} & \multicolumn{1}{c}{0.042385}& \multicolumn{1}{c}{ 0.029081} & \multicolumn{1}{c}{0.026488}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{1.053720} & \multicolumn{1}{c}{ 3.820766} & \multicolumn{1}{c}{0.466968} & \multicolumn{1}{c}{ 5.616494}& \multicolumn{1}{c}{3.008335} & \multicolumn{1}{c}{1.738237}\\%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.061157} & \multicolumn{1}{c}{-2.275825} & \multicolumn{1}{c}{-1.665877} & \multicolumn{1}{c}{ 1.583260}& \multicolumn{1}{c}{0.908970} & \multicolumn{1}{c}{0.796402}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.177363} & \multicolumn{1}{c}{52.932163} & \multicolumn{1}{c}{27.393468} & \multicolumn{1}{c}{0.124896}& \multicolumn{1}{c}{0.374979} & \multicolumn{1}{c}{0.331102}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{39.34201} & \multicolumn{1}{c}{5026.19116} & \multicolumn{1}{c}{81.44477} & \multicolumn{1}{c}{60.19720}& \multicolumn{1}{c}{44.22266} & \multicolumn{1}{c}{37.23538}\\%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.210787} & \multicolumn{1}{c}{1.219049} & \multicolumn{1}{c}{1.184054} & \multicolumn{1}{c}{1.262922}& \multicolumn{1}{c}{1.227717} & \multicolumn{1}{c}{1.071796}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.009586} & \multicolumn{1}{c}{0.106280} & \multicolumn{1}{c}{0.105656} & \multicolumn{1}{c}{0.0164993}& \multicolumn{1}{c}{0.021225} & \multicolumn{1}{c}{0.027807}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{1.341292} & \multicolumn{1}{c}{3.283949} & \multicolumn{1}{c}{0.650278} & \multicolumn{1}{c}{1.682166}& \multicolumn{1}{c}{0.511069} & \multicolumn{1}{c}{0.466270}\\%%%%%%%%%%% \midrule \end{tabular}% \label{tab:reg}% \end{table}% % comparison with n =1000 \begin{table}[H] \small \centering \caption{Comparing Causal Inference Model with n = 1000} \begin{tabular}{llllllll} \toprule Settings & \multicolumn{1}{c}{Indicator} &\multicolumn{1}{c}{Reg} & \multicolumn{1}{c}{IPW} & \multicolumn{1}{c}{DR} & \multicolumn{1}{c}{LSEN} & \multicolumn{1}{c}{Stack} & \multicolumn{1}{c}{Unstack}\\ \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.007846} & \multicolumn{1}{c}{1.236580} & \multicolumn{1}{c}{0.952120} & \multicolumn{1}{c}{3.424797}& \multicolumn{1}{c}{1.073456} & \multicolumn{1}{c}{1.039096}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.006284} & \multicolumn{1}{c}{0.184614} & \multicolumn{1}{c}{0.024730} & \multicolumn{1}{c}{0.017164}& \multicolumn{1}{c}{0.026608} & \multicolumn{1}{c}{0.022017}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{1.025680} & \multicolumn{1}{c}{40.461838} & \multicolumn{1}{c}{2.806959} & \multicolumn{1}{c}{6.732188}& \multicolumn{1}{c}{3.618579} & \multicolumn{1}{c}{3.227080}\\%%%%%%%%%%% \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.004839} & \multicolumn{1}{c}{1.254511} & \multicolumn{1}{c}{0.995902} & \multicolumn{1}{c}{1.399795}& \multicolumn{1}{c}{1.089641} & \multicolumn{1}{c}{1.000316}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.004731} & \multicolumn{1}{c}{0.010886} & \multicolumn{1}{c}{0.016957} & \multicolumn{1}{c}{0.003589}& \multicolumn{1}{c}{ 0.006722} & \multicolumn{1}{c}{0.007132}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{0.975406} & \multicolumn{1}{c}{ 4.700372} & \multicolumn{1}{c}{0.467718} & \multicolumn{1}{c}{ 5.184206}& \multicolumn{1}{c}{ 3.158589} & \multicolumn{1}{c}{2.020850}\\%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.468347} & \multicolumn{1}{c}{ 2.108269} & \multicolumn{1}{c}{ 1.547489} & \multicolumn{1}{c}{ 1.587310}& \multicolumn{1}{c}{1.509558} & \multicolumn{1}{c}{1.364751}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.072504} & \multicolumn{1}{c}{1.945301} & \multicolumn{1}{c}{1.245016} & \multicolumn{1}{c}{0.091852}& \multicolumn{1}{c}{0.303723} & \multicolumn{1}{c}{0.312551}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{33.50649} & \multicolumn{1}{c}{624.16712} & \multicolumn{1}{c}{219.46862} & \multicolumn{1}{c}{52.80868}& \multicolumn{1}{c}{47.38703} & \multicolumn{1}{c}{40.32269}\\%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.251615} & \multicolumn{1}{c}{1.194133} & \multicolumn{1}{c}{1.173154} & \multicolumn{1}{c}{1.289442}& \multicolumn{1}{c}{1.238894} & \multicolumn{1}{c}{1.098957}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.008945} & \multicolumn{1}{c}{0.013843} & \multicolumn{1}{c}{0.013961} & \multicolumn{1}{c}{0.004397}& \multicolumn{1}{c}{0.004731} & \multicolumn{1}{c}{0.005538}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{1.4309120} & \multicolumn{1}{c}{3.7667123} & \multicolumn{1}{c}{0.6473534} & \multicolumn{1}{c}{1.8486960}& \multicolumn{1}{c}{0.5469495} & \multicolumn{1}{c}{0.5199483}\\%%%%%%%%%%% \midrule \end{tabular}% \label{tab:reg}% \end{table}% % comparison with n =2000 \begin{table}[H] \small \centering \caption{Comparing Causal Inference Model with n = 2000} \begin{tabular}{llllllll} \toprule Settings & \multicolumn{1}{c}{Indicator} &\multicolumn{1}{c}{Reg} & \multicolumn{1}{c}{IPW} & \multicolumn{1}{c}{DR} & \multicolumn{1}{c}{LSEN} & \multicolumn{1}{c}{Stack} & \multicolumn{1}{c}{Unstack}\\ \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{0.995271} & \multicolumn{1}{c}{0.940532} & \multicolumn{1}{c}{0.930769} & \multicolumn{1}{c}{3.424313}& \multicolumn{1}{c}{1.034398} & \multicolumn{1}{c}{1.007690}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.002309} & \multicolumn{1}{c}{1.156691} & \multicolumn{1}{c}{0.041513} & \multicolumn{1}{c}{0.006603}& \multicolumn{1}{c}{0.005387} & \multicolumn{1}{c}{0.005614}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{0.988404} & \multicolumn{1}{c}{358.591610} & \multicolumn{1}{c}{4.104773} & \multicolumn{1}{c}{ 7.000557}& \multicolumn{1}{c}{ 4.035834} & \multicolumn{1}{c}{3.637824}\\%%%%%%%%%%%%%%% \midrule Y = linear(X) + linear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.009137} & \multicolumn{1}{c}{1.361061} & \multicolumn{1}{c}{1.060845} & \multicolumn{1}{c}{1.429234}& \multicolumn{1}{c}{1.107688} & \multicolumn{1}{c}{1.027161}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.003655} & \multicolumn{1}{c}{0.020703} & \multicolumn{1}{c}{0.005703} & \multicolumn{1}{c}{0.008695}& \multicolumn{1}{c}{0.006180} & \multicolumn{1}{c}{0.005427}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{0.965065} & \multicolumn{1}{c}{ 5.280279} & \multicolumn{1}{c}{0.517221} & \multicolumn{1}{c}{5.552783}& \multicolumn{1}{c}{ 3.218770} & \multicolumn{1}{c}{2.166259}\\%%%%%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.363651} & \multicolumn{1}{c}{-0.938856} & \multicolumn{1}{c}{-0.354882} & \multicolumn{1}{c}{ 1.600783}& \multicolumn{1}{c}{1.207503} & \multicolumn{1}{c}{1.109078}\\ X = binomial(1,linear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.071956} & \multicolumn{1}{c}{15.757928} & \multicolumn{1}{c}{10.003057} & \multicolumn{1}{c}{0.116070}& \multicolumn{1}{c}{ 0.068612} & \multicolumn{1}{c}{0.082408}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{31.64986} & \multicolumn{1}{c}{6225.74181} & \multicolumn{1}{c}{118.98011} & \multicolumn{1}{c}{52.89056}& \multicolumn{1}{c}{45.81513} & \multicolumn{1}{c}{41.19371 }\\%%%%%%%%%%%%%%% \midrule Y = linear(X) + nonlinear(Z) & \multicolumn{1}{c}{ATE} & \multicolumn{1}{c}{1.265785} & \multicolumn{1}{c}{1.275776} & \multicolumn{1}{c}{1.238021} & \multicolumn{1}{c}{1.318620}& \multicolumn{1}{c}{1.265688} & \multicolumn{1}{c}{1.120080}\\ X = binomial(1,nonlinear(Z)) & \multicolumn{1}{c}{VAR} & \multicolumn{1}{c}{0.004881} & \multicolumn{1}{c}{0.061766} & \multicolumn{1}{c}{ 0.057562} & \multicolumn{1}{c}{0.005951}& \multicolumn{1}{c}{0.011241} & \multicolumn{1}{c}{0.012562}\\ & \multicolumn{1}{c}{MSE} & \multicolumn{1}{c}{ 1.414781} & \multicolumn{1}{c}{4.014497} & \multicolumn{1}{c}{0.679947} & \multicolumn{1}{c}{1.746575}& \multicolumn{1}{c}{0.565457} & \multicolumn{1}{c}{0.539640}\\%%%%%%%%%%%%%%% \midrule \end{tabular}% \label{tab:reg}% \end{table}% %---------------------------------------- % 3.Results and Conclusions %---------------------------------------- \section{Results and Conclusions} We study ATE and MSE of different causal inference models from Table2 to Table4 in Section 2.3 under different number of observations and settings. By comparison, we can summarize the results as follows: \smallskip \smallskip \begin{enumerate}[(i)] \item By comparing ATE, since the initial setting is $Y \sim X + nonlinear/linear(Z)$, it's straightforward that we can assume the average treatment effect of X is around 1. In either scenario, no matter what $n$ is, the best three estimations which can derive ATE about 1 are Reg, Stack and Unstack, because there's no large deviation and all ATEs are larger tha n 0. \item As sample size increases, all ATEs converge to 1. For n = 2000, the estimation can be ordered as: Unstack, Stack and Reg. For each sample size, Unstack provides best performance in nonlinear initial settings due to its flexible stacking. \item According to MSE, Reg preforms the best. DR, Stack, and Unstack also perform well, and it can be interpreted as it depends on the weighting on outcome regression model, which is also decided by the settings of simulations. \item Under each circumstance, the risk of fixed weighting in DR is presented, compared with Stack and Unstack. If the Reg is correctly defined while IPW is not, (for example, the third simulation with n=2000, in which Reg has ATE = 1.36 and IPW has IPW = -0.94) DR suffers a lot from fixed weighting and Stack and Unstack are affected far less. \end{enumerate} \smallskip \smallskip These results illustrate that the risk of poor estimation of DR does come from fixed weighting, and more flexible weightings provide better average treatment effect estimators, especially in a nonlinear situation, or said, the assumption that at least one of two models is correctly specified is violated. However, the outcome regression is more stable and also has good predictive power in linearity. %---------------------------------------- % 4. Discussion %---------------------------------------- \section{Discussion} The basic idea of doubly robust is to ensemble two basic model: OR and IPW, assuming that either $E(Y-\hat{Y})=0$ or $E(P(X=1 | Z)-X)=0$, or both of them are correct. Although the robustness works well in many aspects, it has a weakness of fixed weighting, which illustrates DR largly, directly depends on OR and IPW and lacks the ability of self-adjustment. Thus, we consider flexible weighting for DR. The constrained weighted stacking model and unconstrained weighted stacking model defined in the article show better performances compared with traditional DR when the assumption does not hold any more. And also, it presents that outcome regression is a simple but efficient method to estimate the marginal effect of treatment. Except for OLS ensemble, it's reasonable to apply machine learning to boost them one by one. For example, using random forest to fit each basic model alternately, and derive residuals to train the ensemble model, which can obtain better weights to mimic the complicated real model. \section{Bibliography} [1] \href{https://github.com/jiamingmao/data-analysis/blob/master/Lectures/Foundations_of_Causal_Inference.pdf}{Jiaming Mao, β€œFoundations of Causal Inference”} \noindent[2] \href{http://www.stat.ncsu.edu/~davidian}{Marie Davidian, β€œDoubly Robustness in Estimation of Causal Treatment Effects”, Department of Statistics, North Carolina State University} \noindent[3] Romain Neugebauer, Mark van der Laan, β€œWhy prefer double robust estimators in causal inference?”, \emph{Journal of Statistical Planning and Inference}, 129(2005) 405-426 \noindent[4] Trevor Hastie, Robert Tibshirani, Jerome Friedman , β€œThe Elements of Statistical Learning”, Springer ISBN: 9780387848570, 2009-10-01, 288-290 \noindent[5] Michele J.F., Daniel Westreich, Chris Wiesen, Til Sturmer, M. Alan Brookhart, Marie Davidian, β€œDoubly Robust Estimation of Causal Effects”, \emph{American Journal of Epidemiology}, Vol.173 No.7, DOI: 10.1093/aje/kwq439, 2011 \end{document}
module Prelude.List.Relations.Permutation where open import Prelude.List.Base open import Prelude.List.Relations.Any data Permutation {a} {A : Set a} : List A β†’ List A β†’ Set a where [] : Permutation [] [] _∷_ : βˆ€ {x xs ys} (i : x ∈ ys) β†’ Permutation xs (deleteIx ys i) β†’ Permutation (x ∷ xs) ys
The Frieze of the Dream Lords ( also known as the Frieze of the Four Suns or Frieze of the Four Eras ) was uncovered by archaeologists during excavations in 1992 . It is a stucco mural located at the east end of the 5th terrace . It represents a complex supernatural scene divided into four by a feather @-@ covered scaffold from which hang the severed heads of sacrificial victims . Among the scaffold partitions are depicted the <unk> ( spirit companions ) of the Maya elite . The most well @-@ preserved section of the sculpture depicts a skeletal supernatural way named Ak Ok Kimi ( " Turtle Foot Death " ) wearing <unk> on its feet and carrying a severed head in one hand , interpreted as the way of a lord from the site of Pipa ' . The frieze was once brightly painted in red , blue and yellow . This frieze has strong stylistic parallels with mural paintings at the great Early Classic metropolis of Teotihuacan in the distant Valley of Mexico .
{-# LANGUAGE DataKinds, GADTs, LambdaCase, NoImplicitPrelude, RankNTypes #-} {-# LANGUAGE TypeApplications, TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -Wno-type-defaults #-} {-# OPTIONS_GHC -fplugin Data.Singletons.TypeNats.Presburger #-} module Algebra.Algorithms.Groebner.ZeroDimSpec where import Algebra.Algorithms.Groebner import Algebra.Algorithms.ZeroDim import Algebra.Internal import Algebra.Internal import Algebra.Prelude.Core hiding ((%)) import Algebra.Ring.Ideal import Algebra.Ring.Polynomial import Algebra.Ring.Polynomial.Quotient import qualified Prelude as P import Control.Monad import Control.Monad.Random import Data.Complex import Data.Convertible (convert) import qualified Data.Foldable as F import qualified Data.Matrix as M import Data.Maybe import qualified Data.Sized.Builtin as SV import qualified Data.Vector as V import Numeric.Field.Fraction (Fraction, (%)) import Numeric.Natural import Test.Hspec import Test.Hspec.QuickCheck import Test.HUnit import Test.QuickCheck hiding (promote) import Utils default (Fraction Integer, Natural) asGenListOf :: Gen [a] -> a -> Gen [a] asGenListOf = const spec :: Spec spec = parallel $ do describe "solveLinear" $ do it "solves data set correctly" $ forM_ linSet $ \set -> solveLinear (M.fromLists $ inputMat set) (V.fromList $ inputVec set) `shouldBe` Just (V.fromList $ answer set) prop "solves any solvable cases" $ forAll (resize 10 arbitrary) $ \(MatrixCase ms) -> let mat = M.fromLists ms :: M.Matrix (Fraction Integer) in rank mat == M.ncols mat ==> forAll (vector (length $ head ms)) $ \v -> let ans = M.getCol 1 $ mat P.* M.colVector (V.fromList v) in solveLinear mat ans == Just (V.fromList v) it "cannot solve unsolvable cases" $ pendingWith "need example" describe "univPoly" $ modifyMaxSuccess (const 25) $ modifyMaxSize (const 4) $ prop "produces monic generators of the elimination ideal" $ checkForTypeNat [2..4] prop_univPoly describe "radical" $ it "really computes radical" $ pendingWith "We can verify correctness by comparing with singular, but it's not quite smart way..." describe "fglm" $ modifyMaxSuccess (const 25) $ modifyMaxSize (const 3) $ do prop "computes monomial basis" $ checkForTypeNat [2..4] $ \sdim -> case zeroOrSucc sdim of IsZero -> error "impossible" IsSucc k -> withWitness (lneqSucc k) $ withWitness (lneqZero k) $ withKnownNat k $ forAll (zeroDimOf sdim) $ \(ZeroDimIdeal ideal) -> let base = reifyQuotient (mapIdeal (changeOrder Lex) ideal) $ \ii -> map quotRepr $ fromJust $ standardMonomials' ii in stdReduced (snd $ fglm ideal) == stdReduced base prop "computes lex base" $ checkForTypeNat [2..4] $ \sdim -> case zeroOrSucc sdim of IsZero -> error "impossible" IsSucc k -> withKnownNat k $ withWitness (lneqSucc k) $ withWitness (lneqZero k) $ forAll (zeroDimOf sdim) $ \(ZeroDimIdeal ideal) -> stdReduced (fst $ fglm ideal) == stdReduced (calcGroebnerBasisWith Lex ideal) prop "returns lex base in descending order" $ checkForTypeNat [2..4] $ \sdim -> case zeroOrSucc sdim of IsZero -> error "impossible" IsSucc k -> withKnownNat k $ case (lneqSucc k, lneqZero k) of (Witness, Witness) -> forAll (zeroDimOf sdim) $ \(ZeroDimIdeal ideal) -> isDescending (map leadingMonomial $ fst $ fglm ideal) describe "solve'" $ modifyMaxSuccess (const 50) $ modifyMaxSize (const 4) $ do it "solves equation with admissible error" $ checkForTypeNat [2..4] $ prop_isApproximateZero 1e-5 (pure . solve' 1e-5) describe "solves regression cases correctly" $ forM_ companionRegressions $ approxZeroTestCase 1e-5 (pure . solve' 1e-5) describe "solveViaCompanion" $ modifyMaxSuccess (const 50) $ modifyMaxSize (const 4) $ do it "solves equation with admissible error" $ checkForTypeNat [2..4] $ prop_isApproximateZero 1e-5 (pure . solveViaCompanion 1e-5) describe "solves regression cases correctly" $ forM_ companionRegressions $ approxZeroTestCase 1e-5 (pure . solveViaCompanion 1e-5) describe "solveM" $ modifyMaxSuccess (const 50) $ modifyMaxSize (const 4) $ do prop "solves equation with admissible error" $ checkForTypeNat [2..4] $ prop_isApproximateZero 1e-9 solveM describe "solves regressions correctly" $ forM_ companionRegressions $ approxZeroTestCase 1e-9 solveM isDescending :: Ord a => [a] -> Bool isDescending xs = and $ zipWith (>=) xs (drop 1 xs) prop_isApproximateZero :: (KnownNat n) => Double -> (forall m. ((0 < m) ~ 'True, KnownNat m) => Ideal (Polynomial (Fraction Integer) m) -> IO [Sized m (Complex Double)]) -> SNat n -> Property prop_isApproximateZero err solver sn = case zeroOrSucc sn of IsSucc _ -> withKnownNat sn $ forAll (zeroDimOf sn) $ ioProperty . checkSolverApproxZero err solver IsZero -> error "prop_isApproximateZero must be called with non-zero typenats!" companionRegressions :: [SolverTestCase] companionRegressions = [ SolverTestCase @3 $ let [x,y,z] = vars in ZeroDimIdeal $ toIdeal [ 2*x^2 + (0.5 :: Fraction Integer) .*. x * y , -(0.5 :: Fraction Integer) .*. y ^ 2 + y * z , z^2 - z] , SolverTestCase @3 $ let [x,y,z] = vars in ZeroDimIdeal $ toIdeal [ 2*x + 1, 2*y^2,-z^2 - 1] , SolverTestCase @2 $ let [x,y] = vars in ZeroDimIdeal $ toIdeal [ x^2 - y, -2*y^2] ] approxZeroTestCase :: Double -> (forall n. ((0 < n) ~ 'True, KnownNat n) => Ideal (Polynomial (Fraction Integer) n) -> IO [Sized n (Complex Double)] ) -> SolverTestCase -> SpecWith () approxZeroTestCase err calc (SolverTestCase f@(ZeroDimIdeal i)) = it (show $ getIdeal f) $ do isZeroDimensional (F.toList i) @? "Not zero-dimensional!" checkSolverApproxZero err calc f @? "Solved correctly" checkSolverApproxZero :: ((0 < n) ~ 'True, KnownNat n) => Double -> (Ideal (Polynomial (Fraction Integer) n) -> IO [Sized n (Complex Double)]) -> ZeroDimIdeal n -> IO Bool checkSolverApproxZero err solver (ZeroDimIdeal ideal) = do anss <- solver ideal let mul r d = convert r * d pure $ all (\as -> all ((<err) . magnitude . substWith mul as) $ generators ideal) anss data SolverTestCase where SolverTestCase :: ((0 < n) ~ 'True, KnownNat n) => ZeroDimIdeal n -> SolverTestCase prop_univPoly :: KnownNat n => SNat n -> Property prop_univPoly sdim = forAll (zeroDimOf sdim) $ \(ZeroDimIdeal ideal) -> let ods = enumOrdinal sdim in conjoin $ flip map ods $ \nth -> let gen = univPoly nth ideal in forAll (unaryPoly sdim nth) $ \f -> (f `modPolynomial` [gen] == 0) == (f `isIdealMember` ideal) rank :: (Ord r, Fractional r) => M.Matrix r -> Int rank mat = let Just (u, _, _, _,_, _) = M.luDecomp' mat in V.foldr (\a acc -> if a /= 0 then acc + 1 else acc) (0 :: Int) $ M.getDiag u data TestSet = TestSet { inputMat :: [[Fraction Integer]] , inputVec :: [Fraction Integer] , answer :: [Fraction Integer] } deriving (Show, Eq, Ord) linSet :: [TestSet] linSet = [TestSet [[1 ,0 ,0 ,0 ,0 ] ,[0 ,(-2) ,(-2) ,(-2) ,(-2) ] ,[0 ,0 ,3 % 2,0 ,(-1) % 2] ,[0 ,0 ,0 ,0 ,(-5) % 2] ,[0 ,1 ,1 ,1 ,1 ] ,[0 ,0 ,(-2) ,1 ,(-1) ] ] [0 ,(-2) ,19 % 5,14 % 5,1 ,0 ] [0 ,(-81) % 25,54 % 25,16 % 5,(-28) % 25] ]
lemma simply_connected_eq_Borsukian: fixes S :: "complex set" shows "open S \<Longrightarrow> (simply_connected S \<longleftrightarrow> connected S \<and> Borsukian S)"
Require Import init. Require Export analysis_base. Require Import analysis_topology. Require Import order_minmax. Definition cauchy_seq {U} `{Metric U} (f : sequence U) := βˆ€ Ξ΅, 0 < Ξ΅ β†’ βˆƒ N, βˆ€ i j, N ≀ i β†’ N ≀ j β†’ d (f i) (f j) < Ξ΅. Definition complete U `{Metric U} := βˆ€ f, cauchy_seq f β†’ seq_converges f. Definition seq_bounded {U} `{Metric U} (f : nat β†’ U) := βˆƒ M, βˆ€ m n, d (f m) (f n) ≀ M. (* begin hide *) Section AnalysisSequence. Context {U} `{Metric U}. (* end hide *) Theorem metric_seq_lim : βˆ€ f x, seq_lim f x ↔ βˆ€ Ξ΅, 0 < Ξ΅ β†’ βˆƒ N, βˆ€ n, N ≀ n β†’ d x (f n) < Ξ΅. Proof. intros f x. rewrite basis_seq_lim. split. - intros lim Ξ΅ Ξ΅_pos. pose proof (open_ball_basis x [Ξ΅|Ξ΅_pos]) as x_basis. pose proof (open_ball_self x [Ξ΅|Ξ΅_pos]) as x_in. exact (lim _ x_basis x_in). - intros lim S S_basis Sx. destruct S_basis as [z [Ξ΅ eq]]; subst S. pose proof (open_ball_ex _ _ _ Sx) as [Ξ΄ sub]. specialize (lim [Ξ΄|] [|Ξ΄]) as [N lim]. exists N. intros n n_gt. apply sub. apply lim. exact n_gt. Qed. Theorem metric_seq_closure : βˆ€ (A : U β†’ Prop) x, (βˆƒ f, (βˆ€ n, A (f n)) ∧ seq_lim f x) ↔ closure A x. Proof. intros A x. split. - intros [f [Af lim]]. exact (seq_closure A x f Af lim). - intros Ax. assert (βˆ€ n, 0 < / from_nat (nat_suc n)) as n_pos. { intros n. apply div_pos. rewrite <- homo_zero. rewrite <- homo_lt2. apply nat_pos2. } pose (B n := open_ball x [_|n_pos n]). assert (βˆ€ n, βˆƒ a, B n a ∧ A a) as f_ex. { intros n. rewrite in_closure in Ax. assert (open (B n)) as B_open. { unfold B. apply open_ball_open. } assert (B n x) as Bnx by apply open_ball_self. specialize (Ax (B n) B_open Bnx). apply empty_neq in Ax as [a a_in]. rewrite inter_comm in a_in. exists a. exact a_in. } exists (Ξ» n, ex_val (f_ex n)). split. + intros n. rewrite_ex_val a a_in. apply a_in. + rewrite metric_seq_lim. intros Ξ΅ Ξ΅_pos. pose proof (archimedean2 _ Ξ΅_pos) as [N N_lt]. exists N. intros n n_gt. rewrite_ex_val a a_in. destruct a_in as [Bna Aa]. unfold B in Bna. apply (trans2 N_lt). rewrite <- nat_sucs_le in n_gt. rewrite (homo_le2 (f := from_nat)) in n_gt. apply le_div_pos in n_gt. 2: apply from_nat_pos. apply (lt_le_trans2 n_gt). exact Bna. Qed. Theorem metric_seq_closed : βˆ€ A, closed A ↔ (βˆ€ f x, (βˆ€ n, A (f n)) β†’ seq_lim f x β†’ A x). Proof. intros A. split. - intros A_closed f x Af fx. apply closed_if_closure in A_closed. rewrite A_closed. exact (seq_closure A x f Af fx). - intros all_f. apply closed_if_closure. apply antisym; try apply closure_sub. intros x Ax. apply metric_seq_closure in Ax. destruct Ax as [f [all_n f_seq]]. exact (all_f f x all_n f_seq). Qed. Theorem converges_cauchy : βˆ€ f, seq_converges f β†’ cauchy_seq f. Proof. intros f [x fx] Ξ΅ Ξ΅_pos. pose proof (half_pos Ξ΅_pos) as Ξ΅2_pos. rewrite metric_seq_lim in fx. specialize (fx _ Ξ΅2_pos) as [N fx]. exists N. intros i j i_gt j_gt. pose proof (lt_lrplus (fx i i_gt) (fx j j_gt)) as ltq. rewrite plus_half in ltq. apply (le_lt_trans2 ltq). rewrite (d_sym x). apply d_tri. Qed. Theorem limit_point_seq_ex : βˆ€ X x, limit_point X x β†’ βˆƒ f, (βˆ€ n, X (f n) ∧ x β‰  f n) ∧ seq_lim f x. Proof. intros X x x_lim. assert (βˆ€ n, βˆƒ a, open_ball x [_|real_n_div_pos n] a ∧ X a ∧ x β‰  a) as f_ex. { intros n. unfold limit_point in x_lim. specialize (x_lim (open_ball x [_|real_n_div_pos n])). specialize (x_lim (open_ball_open _ _) (open_ball_self _ _)). apply empty_neq in x_lim. destruct x_lim as [a [[Xa nxa] a_in]]. exists a. rewrite singleton_eq in nxa. split; [>|split]; assumption. } exists (Ξ» n, ex_val (f_ex n)). split. - intros n. rewrite_ex_val a a_H. split; apply a_H. - rewrite metric_seq_lim. intros Ξ΅ Ξ΅_pos. pose proof (archimedean2 Ξ΅ Ξ΅_pos) as [N N_lt]. exists N. intros m m_geq. rewrite_ex_val b b_H. destruct b_H as [b_in [Xb xb]]. unfold open_ball in b_in; cbn in b_in. apply (trans b_in). apply (le_lt_trans2 N_lt). apply le_div_pos. 1: apply from_nat_pos. change (1 + from_nat m) with (from_nat (U := real) (nat_suc m)). rewrite <- homo_le2. rewrite nat_sucs_le. exact m_geq. Qed. Theorem cauchy_subseq_converge : βˆ€ a b x, cauchy_seq a β†’ subsequence a b β†’ seq_lim b x β†’ seq_lim a x. Proof. intros a b x a_cauchy [f [f_sub ab_eq]] b_lim. rewrite metric_seq_lim in *. intros Ξ΅ Ξ΅_pos. pose proof (half_pos Ξ΅_pos) as Ξ΅2_pos. specialize (b_lim (Ξ΅ / 2) Ξ΅2_pos) as [N1 b_lim]. specialize (a_cauchy (Ξ΅ / 2) Ξ΅2_pos) as [N2 a_cauchy]. exists (max N1 N2). intros n n_geq. specialize (b_lim n (trans (lmax N1 N2) n_geq)). rewrite <- ab_eq in b_lim. pose proof (subsequence_seq_leq f f_sub n) as fn_leq. apply (trans n_geq) in fn_leq. apply (trans (rmax N1 N2)) in n_geq, fn_leq. specialize (a_cauchy (f n) n fn_leq n_geq). pose proof (lt_lrplus b_lim a_cauchy) as ltq. rewrite plus_half in ltq. apply (le_lt_trans2 ltq). apply d_tri. Qed. (* begin hide *) Open Scope card_scope. (* end hide *) Theorem cauchy_bounded : βˆ€ a, cauchy_seq a β†’ seq_bounded a. Proof. intros a a_cauchy. specialize (a_cauchy 1 one_pos) as [N a_cauchy]. classic_case (0 = N) as [N_z|N_nz]. { exists 1. intros i j. subst N. apply a_cauchy; apply nat_pos. } pose (S m := βˆƒ i j, i < 1 + N ∧ j < 1 + N ∧ m = d (a i) (a j)). assert (finite (|set_type S|)) as S_fin. { unfold finite. apply (le_lt_trans2 (nat_is_finite ((1 + N)*(1 + N)))). rewrite <- nat_to_card_mult. unfold mult, le, nat_to_card; equiv_simpl. pose (to_i (x : set_type S) := ex_val [|x]). pose (to_j (x : set_type S) := ex_val (ex_proof [|x])). pose (to_i_lt (x : set_type S) := land (ex_proof (ex_proof [|x]))). pose (to_j_lt (x : set_type S) := land (rand (ex_proof (ex_proof [|x])))). exists (Ξ» x : set_type S, ([to_i x|to_i_lt x], [to_j x|to_j_lt x])). split. intros x y eq. inversion eq as [[eq1 eq2]]. clear eq to_i_lt to_j_lt. unfold to_i, to_j in *. unfold ex_val in eq1 at 1; unfold ex_proof in eq2 at 1. destruct (ex_to_type _) as [i C0]; cbn in *. rewrite_ex_val j [i_lt [j_lt x_eq]]; clear C0. unfold ex_val in eq1; unfold ex_proof in eq2. destruct (ex_to_type _) as [i' C0]; cbn in *. rewrite_ex_val j' [i'_lt [j'_lt y_eq]]; clear C0. subst i' j'. apply set_type_eq. rewrite x_eq, y_eq. reflexivity. } assert (βˆƒ x, S x) as S_ex. { exists (d (a 0) (a 0)). (* Really just zero, but this is simpler. *) exists 0, 0. split. 2: split. 1, 2: split; try apply nat_pos. 1, 2: intros contr; inversion contr. reflexivity. } pose proof (finite_well_ordered_set_max S S_fin S_ex) as [M[Sm M_greatest]]. assert (βˆ€ i j, i < 1 + N β†’ j < 1 + N β†’ d (a i) (a j) < M + 1) as lem1. { intros i j i_lt j_lt. pose proof one_pos as ltq. apply lt_lplus with M in ltq. rewrite plus_rid in ltq. apply (le_lt_trans2 ltq). apply M_greatest. exists i, j. split. 2: split. - exact i_lt. - exact j_lt. - reflexivity. } assert (βˆ€ i j, 1 + N ≀ i β†’ j < 1 + N β†’ d (a i) (a j) < M + 1) as lem2. { intros i j i_ge j_lt. pose proof (trans (nat_le_suc N) i_ge) as i_ge2. specialize (a_cauchy _ _ i_ge2 (refl N)). assert (d (a N) (a j) ≀ M) as leq. { apply M_greatest. exists N, j. split. 2: split. - apply nat_lt_suc. - exact j_lt. - reflexivity. } pose proof (le_lt_lrplus leq a_cauchy) as ltq. clear - ltq. apply (le_lt_trans2 ltq). rewrite plus_comm. apply d_tri. } assert (βˆ€ i j, 1 + N ≀ i β†’ 1 + N ≀ j β†’ d (a i) (a j) < M + 1) as lem3. { intros i j i_ge j_ge. assert (N ≀ i) as i_ge2. { apply (trans2 i_ge). apply nat_le_suc. } assert (N ≀ j) as j_ge2. { apply (trans2 j_ge). apply nat_le_suc. } specialize (a_cauchy i j i_ge2 j_ge2). apply (lt_le_trans a_cauchy). rewrite <- (plus_lid 1) at 1. apply le_rplus. apply M_greatest. exists 0, 0. split. 2: split. 1, 2: apply nat_pos2. rewrite d_zero. reflexivity. } exists (M + 1). intros i j. classic_case (i < 1 + N) as [i_lt|i_ge]; classic_case (j < 1 + N) as [j_lt|j_ge]. - apply lem1; assumption. - rewrite nlt_le in j_ge. rewrite d_sym. apply lem2; assumption. - rewrite nlt_le in i_ge. apply lem2; assumption. - rewrite nlt_le in i_ge, j_ge. apply lem3; assumption. Qed. (* begin hide *) Close Scope card_scope. End AnalysisSequence. (* end hide *)
Polish culture persisted in underground education , publications , even theater . The Polish Underground State created a Department of Education and Culture ( under StanisΕ‚aw Lorentz ) which , along with a Department of Labor and Social Welfare ( under Jan StanisΕ‚aw Jankowski and , later , Stefan Mateja ) and a Department for Elimination of the Effects of War ( under Antoni Olszewski and BronisΕ‚aw <unk> ) , became underground patrons of Polish culture . These Departments oversaw efforts to save from looting and destruction works of art in state and private collections ( most notably , the giant paintings by Jan Matejko that were concealed throughout the war ) . They compiled reports on looted and destroyed works and provided artists and scholars with means to continue their work and their publications and to support their families . Thus , they sponsored the underground publication ( bibuΕ‚a ) of works by Winston Churchill and Arkady Fiedler and of 10 @,@ 000 copies of a Polish primary @-@ school primer and commissioned artists to create resistance artwork ( which was then disseminated by Operation N and like activities ) . Also occasionally sponsored were secret art exhibitions , theater performances and concerts .
/- Copyright (c) Sidharth Hariharan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Sidharth Hariharan -/ import data.polynomial.div import data.zmod.basic import logic.function.basic import ring_theory.localization.fraction_ring import tactic.field_simp import tactic.linear_combination /-! # Partial fractions These results were formalised by the Xena Project, at the suggestion of Patrick Massot. # The main theorem * `div_eq_quo_add_sum_rem_div`: General partial fraction decomposition theorem for polynomials over an integral domain R : If f, g₁, gβ‚‚, ..., gβ‚™ ∈ R[X] and the gα΅’s are all monic and pairwise coprime, then βˆƒ q, r₁, ..., rβ‚™ ∈ R[X] such that f / g₁gβ‚‚...gβ‚™ = q + r₁/g₁ + ... + rβ‚™/gβ‚™ and for all i, deg(rα΅’) < deg(gα΅’). * The result is formalized here in slightly more generality, using finsets. That is, if ΞΉ is an arbitrary index type, g denotes a map from ΞΉ to R[X], and if s is an arbitrary finite subset of ΞΉ, with g i monic for all i ∈ s and for all i,j ∈ s, i β‰  j β†’ g i is coprime to g j, then we have βˆƒ q ∈ R[X] , r : ΞΉ β†’ R[X] such that βˆ€ i ∈ s, deg(r i) < deg(g i) and f / ∏ g i = q + βˆ‘ (r i) / (g i), where the product and sum are over s. * The proof is done by proving the two-denominator case and then performing finset induction for an arbitrary (finite) number of denominators. ## Scope for Expansion * Proving uniqueness of the decomposition -/ variables (R : Type) [comm_ring R] [is_domain R] open_locale polynomial open polynomial variables (K : Type) [field K] [algebra R[X] K] [is_fraction_ring R[X] K] section two_denominators /-- Let R be an integral domain and f, g₁, gβ‚‚ ∈ R[X]. Let g₁ and gβ‚‚ be monic and coprime. Then, βˆƒ q, r₁, rβ‚‚ ∈ R[X] such that f / g₁gβ‚‚ = q + r₁/g₁ + rβ‚‚/gβ‚‚ and deg(r₁) < deg(g₁) and deg(rβ‚‚) < deg(gβ‚‚). -/ lemma div_eq_quo_add_rem_div_add_rem_div (f : R[X]) {g₁ gβ‚‚ : R[X]} (hg₁ : g₁.monic) (hgβ‚‚ : gβ‚‚.monic) (hcoprime : is_coprime g₁ gβ‚‚) : βˆƒ q r₁ rβ‚‚ : R[X], r₁.degree < g₁.degree ∧ rβ‚‚.degree < gβ‚‚.degree ∧ (↑f : K) / (↑g₁ * ↑gβ‚‚) = ↑q + ↑r₁ / ↑g₁ + ↑rβ‚‚ / ↑gβ‚‚ := begin rcases hcoprime with ⟨c, d, hcd⟩, refine ⟨(f * d) /β‚˜ g₁ + (f * c) /β‚˜ gβ‚‚, (f * d) %β‚˜ g₁, (f * c) %β‚˜ gβ‚‚, (degree_mod_by_monic_lt _ hg₁), (degree_mod_by_monic_lt _ hgβ‚‚), _⟩, have hg₁' : (↑g₁ : K) β‰  0, { norm_cast, exact hg₁.ne_zero_of_ne zero_ne_one, }, have hgβ‚‚' : (↑gβ‚‚ : K) β‰  0, { norm_cast, exact hgβ‚‚.ne_zero_of_ne zero_ne_one, }, have hfc := mod_by_monic_add_div (f * c) hgβ‚‚, have hfd := mod_by_monic_add_div (f * d) hg₁, field_simp, norm_cast, linear_combination (-1) * f * hcd + (-1) * g₁ * hfc + (-1) * gβ‚‚ * hfd, end end two_denominators section n_denominators open_locale big_operators classical /-- Let R be an integral domain and f ∈ R[X]. Let s be a finite index set. Then, a fraction of the form f / ∏ (g i) can be rewritten as q + βˆ‘ (r i) / (g i), where deg(r i) < deg(g i), provided that the g i are monic and pairwise coprime. -/ lemma div_eq_quo_add_sum_rem_div (f : R[X]) {ΞΉ : Type*} {g : ΞΉ β†’ R[X]} {s : finset ΞΉ} (hg : βˆ€ i ∈ s, (g i).monic) (hcop : set.pairwise ↑s (Ξ» i j, is_coprime (g i) (g j))) : βˆƒ (q : R[X]) (r : ΞΉ β†’ R[X]), (βˆ€ i ∈ s, (r i).degree < (g i).degree) ∧ (↑f : K) / ∏ i in s, ↑(g i) = ↑q + βˆ‘ i in s, ↑(r i) / ↑(g i) := begin induction s using finset.induction_on with a b hab Hind f generalizing f, { refine ⟨f, (Ξ» (i : ΞΉ), (0 : R[X])), Ξ» i, _, by simp⟩, rintro ⟨⟩, }, obtain ⟨qβ‚€, r₁, rβ‚‚, hdeg₁, hdegβ‚‚, (hf : (↑f : K) / _ = _)⟩ := div_eq_quo_add_rem_div_add_rem_div R K f (_ : monic (g a)) (_ : monic ∏ (i : ΞΉ) in b, (g i)) _, { obtain ⟨q, r, hrdeg, IH⟩ := Hind (Ξ» i hi, hg i (finset.mem_insert_of_mem hi)) (set.pairwise.mono ( finset.coe_subset.2 $ Ξ» i hi, finset.mem_insert_of_mem hi) hcop) rβ‚‚, refine ⟨qβ‚€ + q, Ξ» i, if i = a then r₁ else r i, _, _⟩, { intro i, split_ifs with h1, { cases h1, intro _, exact hdeg₁, }, { intro hi, exact hrdeg i (finset.mem_of_mem_insert_of_ne hi h1), }, }, norm_cast at ⊒ hf IH, rw [finset.prod_insert hab, hf, IH, finset.sum_insert hab, if_pos rfl], transitivity (↑(qβ‚€ + q : R[X]) : K) + (↑r₁ / ↑(g a) + βˆ‘ (i : ΞΉ) in b, ↑(r i) / ↑(g i)), { push_cast, ring, }, congr' 2, refine finset.sum_congr rfl (Ξ» x hxb, _), rw if_neg, rintro rfl, exact hab hxb }, { exact hg a (b.mem_insert_self a), }, { exact monic_prod_of_monic _ _ (Ξ» i hi, hg i (finset.mem_insert_of_mem hi)), }, { refine is_coprime.prod_right (Ξ» i hi, hcop (finset.mem_coe.2 (b.mem_insert_self a)) (finset.mem_coe.2 (finset.mem_insert_of_mem hi)) _), rintro rfl, exact hab hi, }, end end n_denominators
C @(#)swap_txt2.f 20.3 2/13/96 subroutine swap_txt2 (ix, jx) implicit none integer ix, jx c c This function sorts text2 by blocks and by network c data: c c "A", "I", and "B+XQR$LET" c common /difference/ numtxt1, array1, text1, numtxt2, array2, & text2, numchg, change integer MAXTEXT, MAXCHG parameter (MAXTEXT = 10000) parameter (MAXCHG = 4000) character text1(MAXTEXT)*120, text2(MAXTEXT)*120, & change(MAXCHG)*120 integer array1(MAXTEXT), numtxt1, array2(MAXTEXT), numtxt2, & numchg integer temp temp = array2(ix) array2(ix) = array2(jx) array2(jx) = temp return end
library(readxl) SP500Tickers <- read.csv("SP500Tickers.csv") library(httr) library(jsonlite) library(urltools) library(lubridate) urlrequestlist <- list("sell", "buy") repeat { for(j in 1:50){ for(i in 1:length(urlrequestlist)){ currentUrl<-paste0("https://bigdataforall.com/stocks/?key=pires&tiingo_key=2db57b4ec1957026c97b4084adb8890446c30fb7&symbol=",SP500Tickers$Ticker[j],"&quantity=1&request=",urlrequestlist[i]) res = GET(currentUrl) assign(paste0("variable_",urlrequestlist[i]),res) } Sys.sleep(60) } } # startTime <- Sys.time() # endtime <- startTime + 1*60 # differencetime <- difftime(endtime,startTime,units="secs") # if ( differencetime > 0) # { # }else # break #
State Before: a b c : Int H1 : b β‰  0 H2 : a = b * c ⊒ div a b = c State After: no goals Tactic: rw [H2, Int.mul_div_cancel_left _ H1]
#==============================================================================# # AutoScalingPlans.jl # # This file is generated from: # https://github.com/aws/aws-sdk-js/blob/master/apis/autoscaling-plans-2018-01-06.normal.json #==============================================================================# __precompile__() module AutoScalingPlans using AWSCore """ using AWSSDK.AutoScalingPlans.create_scaling_plan create_scaling_plan([::AWSConfig], arguments::Dict) create_scaling_plan([::AWSConfig]; ScalingPlanName=, ApplicationSource=, ScalingInstructions=) using AWSCore.Services.autoscaling_plans autoscaling_plans([::AWSConfig], "CreateScalingPlan", arguments::Dict) autoscaling_plans([::AWSConfig], "CreateScalingPlan", ScalingPlanName=, ApplicationSource=, ScalingInstructions=) # CreateScalingPlan Operation Creates a scaling plan. A scaling plan contains a set of instructions used to configure dynamic scaling for the scalable resources in your application. AWS Auto Scaling creates target tracking scaling policies based on the scaling instructions in your scaling plan. # Arguments ## `ScalingPlanName = ::String` -- *Required* The name of the scaling plan. Names cannot contain vertical bars, colons, or forward slashes. ## `ApplicationSource = [ ... ]` -- *Required* A CloudFormation stack or set of tags. You can create one scaling plan per application source. ``` ApplicationSource = [ "CloudFormationStackARN" => ::String, "TagFilters" => [[ "Key" => ::String, "Values" => [::String, ...] ], ...] ] ``` ## `ScalingInstructions = [[ ... ], ...]` -- *Required* The scaling instructions. ``` ScalingInstructions = [[ "ServiceNamespace" => <required> "autoscaling", "ecs", "ec2", "rds" or "dynamodb", "ResourceId" => <required> ::String, "ScalableDimension" => <required> "autoscaling:autoScalingGroup:DesiredCapacity", "ecs:service:DesiredCount", "ec2:spot-fleet-request:TargetCapacity", "rds:cluster:ReadReplicaCount", "dynamodb:table:ReadCapacityUnits", "dynamodb:table:WriteCapacityUnits", "dynamodb:index:ReadCapacityUnits" or "dynamodb:index:WriteCapacityUnits", "MinCapacity" => <required> ::Int, "MaxCapacity" => <required> ::Int, "TargetTrackingConfigurations" => <required> [[ "PredefinedScalingMetricSpecification" => [ "PredefinedScalingMetricType" => <required> "ASGAverageCPUUtilization", "ASGAverageNetworkIn", "ASGAverageNetworkOut", "DynamoDBReadCapacityUtilization", "DynamoDBWriteCapacityUtilization", "ECSServiceAverageCPUUtilization", "ECSServiceAverageMemoryUtilization", "ALBRequestCountPerTarget", "RDSReaderAverageCPUUtilization", "RDSReaderAverageDatabaseConnections", "EC2SpotFleetRequestAverageCPUUtilization", "EC2SpotFleetRequestAverageNetworkIn" or "EC2SpotFleetRequestAverageNetworkOut", "ResourceLabel" => ::String ], "CustomizedScalingMetricSpecification" => [ "MetricName" => <required> ::String, "Namespace" => <required> ::String, "Dimensions" => [[ "Name" => <required> ::String, "Value" => <required> ::String ], ...], "Statistic" => <required> "Average", "Minimum", "Maximum", "SampleCount" or "Sum", "Unit" => ::String ], "TargetValue" => <required> double, "DisableScaleIn" => ::Bool, "ScaleOutCooldown" => ::Int, "ScaleInCooldown" => ::Int, "EstimatedInstanceWarmup" => ::Int ], ...] ], ...] ``` # Returns `CreateScalingPlanResponse` # Exceptions `ValidationException`, `LimitExceededException`, `ConcurrentUpdateException` or `InternalServiceException`. See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/autoscaling-plans-2018-01-06/CreateScalingPlan) """ @inline create_scaling_plan(aws::AWSConfig=default_aws_config(); args...) = create_scaling_plan(aws, args) @inline create_scaling_plan(aws::AWSConfig, args) = AWSCore.Services.autoscaling_plans(aws, "CreateScalingPlan", args) @inline create_scaling_plan(args) = create_scaling_plan(default_aws_config(), args) """ using AWSSDK.AutoScalingPlans.delete_scaling_plan delete_scaling_plan([::AWSConfig], arguments::Dict) delete_scaling_plan([::AWSConfig]; ScalingPlanName=, ScalingPlanVersion=) using AWSCore.Services.autoscaling_plans autoscaling_plans([::AWSConfig], "DeleteScalingPlan", arguments::Dict) autoscaling_plans([::AWSConfig], "DeleteScalingPlan", ScalingPlanName=, ScalingPlanVersion=) # DeleteScalingPlan Operation Deletes the specified scaling plan. # Arguments ## `ScalingPlanName = ::String` -- *Required* The name of the scaling plan. ## `ScalingPlanVersion = ::Int` -- *Required* The version of the scaling plan. # Returns `DeleteScalingPlanResponse` # Exceptions `ValidationException`, `ObjectNotFoundException`, `ConcurrentUpdateException` or `InternalServiceException`. See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/autoscaling-plans-2018-01-06/DeleteScalingPlan) """ @inline delete_scaling_plan(aws::AWSConfig=default_aws_config(); args...) = delete_scaling_plan(aws, args) @inline delete_scaling_plan(aws::AWSConfig, args) = AWSCore.Services.autoscaling_plans(aws, "DeleteScalingPlan", args) @inline delete_scaling_plan(args) = delete_scaling_plan(default_aws_config(), args) """ using AWSSDK.AutoScalingPlans.describe_scaling_plan_resources describe_scaling_plan_resources([::AWSConfig], arguments::Dict) describe_scaling_plan_resources([::AWSConfig]; ScalingPlanName=, ScalingPlanVersion=, <keyword arguments>) using AWSCore.Services.autoscaling_plans autoscaling_plans([::AWSConfig], "DescribeScalingPlanResources", arguments::Dict) autoscaling_plans([::AWSConfig], "DescribeScalingPlanResources", ScalingPlanName=, ScalingPlanVersion=, <keyword arguments>) # DescribeScalingPlanResources Operation Describes the scalable resources in the specified scaling plan. # Arguments ## `ScalingPlanName = ::String` -- *Required* The name of the scaling plan. ## `ScalingPlanVersion = ::Int` -- *Required* The version of the scaling plan. ## `MaxResults = ::Int` The maximum number of scalable resources to return. This value can be between 1 and 50. The default value is 50. ## `NextToken = ::String` The token for the next set of results. # Returns `DescribeScalingPlanResourcesResponse` # Exceptions `ValidationException`, `InvalidNextTokenException`, `ConcurrentUpdateException` or `InternalServiceException`. See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/autoscaling-plans-2018-01-06/DescribeScalingPlanResources) """ @inline describe_scaling_plan_resources(aws::AWSConfig=default_aws_config(); args...) = describe_scaling_plan_resources(aws, args) @inline describe_scaling_plan_resources(aws::AWSConfig, args) = AWSCore.Services.autoscaling_plans(aws, "DescribeScalingPlanResources", args) @inline describe_scaling_plan_resources(args) = describe_scaling_plan_resources(default_aws_config(), args) """ using AWSSDK.AutoScalingPlans.describe_scaling_plans describe_scaling_plans([::AWSConfig], arguments::Dict) describe_scaling_plans([::AWSConfig]; <keyword arguments>) using AWSCore.Services.autoscaling_plans autoscaling_plans([::AWSConfig], "DescribeScalingPlans", arguments::Dict) autoscaling_plans([::AWSConfig], "DescribeScalingPlans", <keyword arguments>) # DescribeScalingPlans Operation Describes the specified scaling plans or all of your scaling plans. # Arguments ## `ScalingPlanNames = [::String, ...]` The names of the scaling plans (up to 10). If you specify application sources, you cannot specify scaling plan names. ## `ScalingPlanVersion = ::Int` The version of the scaling plan. If you specify a scaling plan version, you must also specify a scaling plan name. ## `ApplicationSources = [[ ... ], ...]` The sources for the applications (up to 10). If you specify scaling plan names, you cannot specify application sources. ``` ApplicationSources = [[ "CloudFormationStackARN" => ::String, "TagFilters" => [[ "Key" => ::String, "Values" => [::String, ...] ], ...] ], ...] ``` ## `MaxResults = ::Int` The maximum number of scalable resources to return. This value can be between 1 and 50. The default value is 50. ## `NextToken = ::String` The token for the next set of results. # Returns `DescribeScalingPlansResponse` # Exceptions `ValidationException`, `InvalidNextTokenException`, `ConcurrentUpdateException` or `InternalServiceException`. See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/autoscaling-plans-2018-01-06/DescribeScalingPlans) """ @inline describe_scaling_plans(aws::AWSConfig=default_aws_config(); args...) = describe_scaling_plans(aws, args) @inline describe_scaling_plans(aws::AWSConfig, args) = AWSCore.Services.autoscaling_plans(aws, "DescribeScalingPlans", args) @inline describe_scaling_plans(args) = describe_scaling_plans(default_aws_config(), args) """ using AWSSDK.AutoScalingPlans.update_scaling_plan update_scaling_plan([::AWSConfig], arguments::Dict) update_scaling_plan([::AWSConfig]; ScalingPlanName=, ScalingPlanVersion=, <keyword arguments>) using AWSCore.Services.autoscaling_plans autoscaling_plans([::AWSConfig], "UpdateScalingPlan", arguments::Dict) autoscaling_plans([::AWSConfig], "UpdateScalingPlan", ScalingPlanName=, ScalingPlanVersion=, <keyword arguments>) # UpdateScalingPlan Operation Updates the scaling plan for the specified scaling plan. You cannot update a scaling plan if it is in the process of being created, updated, or deleted. # Arguments ## `ApplicationSource = [ ... ]` A CloudFormation stack or set of tags. ``` ApplicationSource = [ "CloudFormationStackARN" => ::String, "TagFilters" => [[ "Key" => ::String, "Values" => [::String, ...] ], ...] ] ``` ## `ScalingPlanName = ::String` -- *Required* The name of the scaling plan. ## `ScalingInstructions = [[ ... ], ...]` The scaling instructions. ``` ScalingInstructions = [[ "ServiceNamespace" => <required> "autoscaling", "ecs", "ec2", "rds" or "dynamodb", "ResourceId" => <required> ::String, "ScalableDimension" => <required> "autoscaling:autoScalingGroup:DesiredCapacity", "ecs:service:DesiredCount", "ec2:spot-fleet-request:TargetCapacity", "rds:cluster:ReadReplicaCount", "dynamodb:table:ReadCapacityUnits", "dynamodb:table:WriteCapacityUnits", "dynamodb:index:ReadCapacityUnits" or "dynamodb:index:WriteCapacityUnits", "MinCapacity" => <required> ::Int, "MaxCapacity" => <required> ::Int, "TargetTrackingConfigurations" => <required> [[ "PredefinedScalingMetricSpecification" => [ "PredefinedScalingMetricType" => <required> "ASGAverageCPUUtilization", "ASGAverageNetworkIn", "ASGAverageNetworkOut", "DynamoDBReadCapacityUtilization", "DynamoDBWriteCapacityUtilization", "ECSServiceAverageCPUUtilization", "ECSServiceAverageMemoryUtilization", "ALBRequestCountPerTarget", "RDSReaderAverageCPUUtilization", "RDSReaderAverageDatabaseConnections", "EC2SpotFleetRequestAverageCPUUtilization", "EC2SpotFleetRequestAverageNetworkIn" or "EC2SpotFleetRequestAverageNetworkOut", "ResourceLabel" => ::String ], "CustomizedScalingMetricSpecification" => [ "MetricName" => <required> ::String, "Namespace" => <required> ::String, "Dimensions" => [[ "Name" => <required> ::String, "Value" => <required> ::String ], ...], "Statistic" => <required> "Average", "Minimum", "Maximum", "SampleCount" or "Sum", "Unit" => ::String ], "TargetValue" => <required> double, "DisableScaleIn" => ::Bool, "ScaleOutCooldown" => ::Int, "ScaleInCooldown" => ::Int, "EstimatedInstanceWarmup" => ::Int ], ...] ], ...] ``` ## `ScalingPlanVersion = ::Int` -- *Required* The version number. # Returns `UpdateScalingPlanResponse` # Exceptions `ValidationException`, `ConcurrentUpdateException`, `InternalServiceException` or `ObjectNotFoundException`. See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/autoscaling-plans-2018-01-06/UpdateScalingPlan) """ @inline update_scaling_plan(aws::AWSConfig=default_aws_config(); args...) = update_scaling_plan(aws, args) @inline update_scaling_plan(aws::AWSConfig, args) = AWSCore.Services.autoscaling_plans(aws, "UpdateScalingPlan", args) @inline update_scaling_plan(args) = update_scaling_plan(default_aws_config(), args) end # module AutoScalingPlans #==============================================================================# # End of file #==============================================================================#
When the world of Rayman is threatened by a devastating invasion of crazed, out-of-control bunnies, Rayman must rise up against his furry foes to foil their wicked plans. Draw your weapons and engage in plunger-shooting action madness! Run tumultuous races on animals such as warthogs or bats to outrun the evil rabbids! Please Note! GeForce 4 MX, GeForce Go and any integrated graphics controllers (for example, Intel) are not supported. Want to know when Rayman Raving Rabbids Game PC - ozgameshop.com drops below a certain price? Enter your email address and price below and we'll let you know when it drops below that price!
Formal statement is: lemma compact_empty[simp]: "compact {}" Informal statement is: The empty set is compact.
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark ! This file was ported from Lean 3 source module algebra.polynomial.big_operators ! leanprover-community/mathlib commit 47adfab39a11a072db552f47594bf8ed2cf8a722 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.Order.WithZero import Mathlib.Data.Polynomial.Monic /-! # Lemmas for the interaction between polynomials and `βˆ‘` and `∏`. Recall that `βˆ‘` and `∏` are notation for `Finset.sum` and `Finset.prod` respectively. ## Main results - `Polynomial.natDegree_prod_of_monic` : the degree of a product of monic polynomials is the product of degrees. We prove this only for `[CommSemiring R]`, but it ought to be true for `[Semiring R]` and `List.prod`. - `Polynomial.natDegree_prod` : for polynomials over an integral domain, the degree of the product is the sum of degrees. - `Polynomial.leadingCoeff_prod` : for polynomials over an integral domain, the leading coefficient is the product of leading coefficients. - `Polynomial.prod_X_sub_C_coeff_card_pred` carries most of the content for computing the second coefficient of the characteristic polynomial. -/ open Finset open Multiset open BigOperators Polynomial universe u w variable {R : Type u} {ΞΉ : Type w} namespace Polynomial variable (s : Finset ΞΉ) section Semiring variable {S : Type _} [Semiring S] theorem natDegree_list_sum_le (l : List S[X]) : natDegree l.sum ≀ (l.map natDegree).foldr max 0 := List.sum_le_foldr_max natDegree (by simp) natDegree_add_le _ #align polynomial.nat_degree_list_sum_le Polynomial.natDegree_list_sum_le theorem natDegree_multiset_sum_le (l : Multiset S[X]) : natDegree l.sum ≀ (l.map natDegree).foldr max max_left_comm 0 := Quotient.inductionOn l (by simpa using natDegree_list_sum_le) #align polynomial.nat_degree_multiset_sum_le Polynomial.natDegree_multiset_sum_le theorem natDegree_sum_le (f : ΞΉ β†’ S[X]) : natDegree (βˆ‘ i in s, f i) ≀ s.fold max 0 (natDegree ∘ f) := by simpa using natDegree_multiset_sum_le (s.val.map f) #align polynomial.nat_degree_sum_le Polynomial.natDegree_sum_le theorem degree_list_sum_le (l : List S[X]) : degree l.sum ≀ (l.map natDegree).maximum := by by_cases h : l.sum = 0 Β· simp [h] Β· rw [degree_eq_natDegree h] suffices (l.map natDegree).maximum = ((l.map natDegree).foldr max 0 : β„•) by rw [this] simpa [this, Nat.cast_withBot] using natDegree_list_sum_le l rw [← List.foldr_max_of_ne_nil] Β· congr contrapose! h rw [List.map_eq_nil] at h simp [h] #align polynomial.degree_list_sum_le Polynomial.degree_list_sum_le theorem natDegree_list_prod_le (l : List S[X]) : natDegree l.prod ≀ (l.map natDegree).sum := by induction' l with hd tl IH Β· simp Β· simpa using natDegree_mul_le.trans (add_le_add_left IH _) #align polynomial.nat_degree_list_prod_le Polynomial.natDegree_list_prod_le theorem degree_list_prod_le (l : List S[X]) : degree l.prod ≀ (l.map degree).sum := by induction' l with hd tl IH Β· simp Β· simpa using (degree_mul_le _ _).trans (add_le_add_left IH _) #align polynomial.degree_list_prod_le Polynomial.degree_list_prod_le theorem coeff_list_prod_of_natDegree_le (l : List S[X]) (n : β„•) (hl : βˆ€ p ∈ l, natDegree p ≀ n) : coeff (List.prod l) (l.length * n) = (l.map fun p => coeff p n).prod := by induction' l with hd tl IH Β· simp Β· have hl' : βˆ€ p ∈ tl, natDegree p ≀ n := fun p hp => hl p (List.mem_cons_of_mem _ hp) simp only [List.prod_cons, List.map, List.length] rw [add_mul, one_mul, add_comm, ← IH hl', mul_comm tl.length] have h : natDegree tl.prod ≀ n * tl.length := by refine' (natDegree_list_prod_le _).trans _ rw [← tl.length_map natDegree, mul_comm] refine' List.sum_le_card_nsmul _ _ _ simpa using hl' have hdn : natDegree hd ≀ n := hl _ (List.mem_cons_self _ _) rcases hdn.eq_or_lt with (rfl | hdn') Β· cases' h.eq_or_lt with h' h' Β· rw [← h', coeff_mul_degree_add_degree, leadingCoeff, leadingCoeff] Β· rw [coeff_eq_zero_of_natDegree_lt, coeff_eq_zero_of_natDegree_lt h', mul_zero] exact natDegree_mul_le.trans_lt (add_lt_add_left h' _) Β· rw [coeff_eq_zero_of_natDegree_lt hdn', coeff_eq_zero_of_natDegree_lt, zero_mul] exact natDegree_mul_le.trans_lt (add_lt_add_of_lt_of_le hdn' h) #align polynomial.coeff_list_prod_of_nat_degree_le Polynomial.coeff_list_prod_of_natDegree_le end Semiring section CommSemiring variable [CommSemiring R] (f : ΞΉ β†’ R[X]) (t : Multiset R[X]) theorem natDegree_multiset_prod_le : t.prod.natDegree ≀ (t.map natDegree).sum := Quotient.inductionOn t (by simpa using natDegree_list_prod_le) #align polynomial.nat_degree_multiset_prod_le Polynomial.natDegree_multiset_prod_le theorem natDegree_prod_le : (∏ i in s, f i).natDegree ≀ βˆ‘ i in s, (f i).natDegree := by simpa using natDegree_multiset_prod_le (s.1.map f) #align polynomial.nat_degree_prod_le Polynomial.natDegree_prod_le /-- The degree of a product of polynomials is at most the sum of the degrees, where the degree of the zero polynomial is βŠ₯. -/ theorem degree_prod_le : (∏ i in s, f i).degree ≀ βˆ‘ i in s, (f i).degree := by simpa only [Multiset.map_map] using degree_multiset_prod_le (s.1.map f) #align polynomial.degree_prod_le Polynomial.degree_prod_le /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `Polynomial.leadingCoeff_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ theorem leadingCoeff_multiset_prod' (h : (t.map leadingCoeff).prod β‰  0) : t.prod.leadingCoeff = (t.map leadingCoeff).prod := by induction' t using Multiset.induction_on with a t ih; Β· simp simp only [Multiset.map_cons, Multiset.prod_cons] at h ⊒ rw [Polynomial.leadingCoeff_mul'] <;> Β· rw [ih] simp [*] apply right_ne_zero_of_mul h #align polynomial.leading_coeff_multiset_prod' Polynomial.leadingCoeff_multiset_prod' /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `Polynomial.leadingCoeff_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ theorem leadingCoeff_prod' (h : (∏ i in s, (f i).leadingCoeff) β‰  0) : (∏ i in s, f i).leadingCoeff = ∏ i in s, (f i).leadingCoeff := by simpa using leadingCoeff_multiset_prod' (s.1.map f) (by simpa using h) #align polynomial.leading_coeff_prod' Polynomial.leadingCoeff_prod' /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `Polynomial.natDegree_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ theorem natDegree_multiset_prod' (h : (t.map fun f => leadingCoeff f).prod β‰  0) : t.prod.natDegree = (t.map fun f => natDegree f).sum := by revert h refine' Multiset.induction_on t _ fun a t ih ht => _; Β· simp rw [Multiset.map_cons, Multiset.prod_cons] at ht⊒ rw [Multiset.sum_cons, Polynomial.natDegree_mul', ih] Β· apply right_ne_zero_of_mul ht Β· rwa [Polynomial.leadingCoeff_multiset_prod'] apply right_ne_zero_of_mul ht #align polynomial.nat_degree_multiset_prod' Polynomial.natDegree_multiset_prod' /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `Polynomial.natDegree_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ theorem natDegree_prod' (h : (∏ i in s, (f i).leadingCoeff) β‰  0) : (∏ i in s, f i).natDegree = βˆ‘ i in s, (f i).natDegree := by simpa using natDegree_multiset_prod' (s.1.map f) (by simpa using h) #align polynomial.nat_degree_prod' Polynomial.natDegree_prod' theorem natDegree_multiset_prod_of_monic (h : βˆ€ f ∈ t, Monic f) : t.prod.natDegree = (t.map natDegree).sum := by nontriviality R apply natDegree_multiset_prod' suffices (t.map fun f => leadingCoeff f).prod = 1 by rw [this] simp convert prod_replicate (Multiset.card t) (1 : R) Β· simp only [eq_replicate, Multiset.card_map, eq_self_iff_true, true_and_iff] rintro i hi obtain ⟨i, hi, rfl⟩ := Multiset.mem_map.mp hi apply h assumption Β· simp #align polynomial.nat_degree_multiset_prod_of_monic Polynomial.natDegree_multiset_prod_of_monic theorem natDegree_prod_of_monic (h : βˆ€ i ∈ s, (f i).Monic) : (∏ i in s, f i).natDegree = βˆ‘ i in s, (f i).natDegree := by simpa using natDegree_multiset_prod_of_monic (s.1.map f) (by simpa using h) #align polynomial.nat_degree_prod_of_monic Polynomial.natDegree_prod_of_monic theorem coeff_multiset_prod_of_natDegree_le (n : β„•) (hl : βˆ€ p ∈ t, natDegree p ≀ n) : coeff t.prod ((Multiset.card t) * n) = (t.map fun p => coeff p n).prod := by induction t using Quotient.inductionOn simpa using coeff_list_prod_of_natDegree_le _ _ hl #align polynomial.coeff_multiset_prod_of_nat_degree_le Polynomial.coeff_multiset_prod_of_natDegree_le theorem coeff_prod_of_natDegree_le (f : ΞΉ β†’ R[X]) (n : β„•) (h : βˆ€ p ∈ s, natDegree (f p) ≀ n) : coeff (∏ i in s, f i) (s.card * n) = ∏ i in s, coeff (f i) n := by cases' s with l hl convert coeff_multiset_prod_of_natDegree_le (l.map f) n ?_ Β· simp Β· simp Β· simpa using h #align polynomial.coeff_prod_of_nat_degree_le Polynomial.coeff_prod_of_natDegree_le theorem coeff_zero_multiset_prod : t.prod.coeff 0 = (t.map fun f => coeff f 0).prod := by refine' Multiset.induction_on t _ fun a t ht => _; Β· simp rw [Multiset.prod_cons, Multiset.map_cons, Multiset.prod_cons, Polynomial.mul_coeff_zero, ht] #align polynomial.coeff_zero_multiset_prod Polynomial.coeff_zero_multiset_prod theorem coeff_zero_prod : (∏ i in s, f i).coeff 0 = ∏ i in s, (f i).coeff 0 := by simpa using coeff_zero_multiset_prod (s.1.map f) #align polynomial.coeff_zero_prod Polynomial.coeff_zero_prod end CommSemiring section CommRing variable [CommRing R] open Monic -- Eventually this can be generalized with Vieta's formulas -- plus the connection between roots and factorization. theorem multiset_prod_X_sub_C_nextCoeff (t : Multiset R) : nextCoeff (t.map fun x => X - C x).prod = -t.sum := by rw [nextCoeff_multiset_prod] Β· simp only [nextCoeff_X_sub_C] exact t.sum_hom (-AddMonoidHom.id R) Β· intros apply monic_X_sub_C set_option linter.uppercaseLean3 false in #align polynomial.multiset_prod_X_sub_C_next_coeff Polynomial.multiset_prod_X_sub_C_nextCoeff theorem prod_x_sub_c_nextCoeff {s : Finset ΞΉ} (f : ΞΉ β†’ R) : nextCoeff (∏ i in s, (X - C (f i))) = -βˆ‘ i in s, f i := by simpa using multiset_prod_X_sub_C_nextCoeff (s.1.map f) set_option linter.uppercaseLean3 false in #align polynomial.prod_X_sub_C_next_coeff Polynomial.prod_x_sub_c_nextCoeff theorem multiset_prod_X_sub_C_coeff_card_pred (t : Multiset R) (ht : 0 < Multiset.card t) : (t.map fun x => X - C x).prod.coeff ((Multiset.card t) - 1) = -t.sum := by nontriviality R convert multiset_prod_X_sub_C_nextCoeff (by assumption) rw [nextCoeff]; split_ifs with h Β· rw [natDegree_multiset_prod_of_monic] at h <;> simp only [Multiset.mem_map] at * swap Β· rintro _ ⟨_, _, rfl⟩ apply monic_X_sub_C simp_rw [Multiset.sum_eq_zero_iff, Multiset.mem_map] at h contrapose! h obtain ⟨x, hx⟩ := card_pos_iff_exists_mem.mp ht exact ⟨_, ⟨_, ⟨x, hx, rfl⟩, natDegree_X_sub_C _⟩, one_ne_zero⟩ congr ; rw [natDegree_multiset_prod_of_monic] <;> Β· simp [natDegree_X_sub_C, monic_X_sub_C] set_option linter.uppercaseLean3 false in #align polynomial.multiset_prod_X_sub_C_coeff_card_pred Polynomial.multiset_prod_X_sub_C_coeff_card_pred theorem prod_X_sub_C_coeff_card_pred (s : Finset ΞΉ) (f : ΞΉ β†’ R) (hs : 0 < s.card) : (∏ i in s, (X - C (f i))).coeff (s.card - 1) = -βˆ‘ i in s, f i := by simpa using multiset_prod_X_sub_C_coeff_card_pred (s.1.map f) (by simpa using hs) set_option linter.uppercaseLean3 false in #align polynomial.prod_X_sub_C_coeff_card_pred Polynomial.prod_X_sub_C_coeff_card_pred end CommRing section NoZeroDivisors section Semiring variable [Semiring R] [NoZeroDivisors R] /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is βŠ₯. `[Nontrivial R]` is needed, otherwise for `l = []` we have `βŠ₯` in the LHS and `0` in the RHS. -/ theorem degree_list_prod [Nontrivial R] (l : List R[X]) : l.prod.degree = (l.map degree).sum := map_list_prod (@degreeMonoidHom R _ _ _) l #align polynomial.degree_list_prod Polynomial.degree_list_prod end Semiring section CommSemiring variable [CommSemiring R] [NoZeroDivisors R] (f : ΞΉ β†’ R[X]) (t : Multiset R[X]) /-- The degree of a product of polynomials is equal to the sum of the degrees. See `Polynomial.natDegree_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ theorem natDegree_prod (h : βˆ€ i ∈ s, f i β‰  0) : (∏ i in s, f i).natDegree = βˆ‘ i in s, (f i).natDegree := by nontriviality R apply natDegree_prod' rw [prod_ne_zero_iff] intro x hx; simp [h x hx] #align polynomial.nat_degree_prod Polynomial.natDegree_prod theorem natDegree_multiset_prod (h : (0 : R[X]) βˆ‰ t) : natDegree t.prod = (t.map natDegree).sum := by nontriviality R rw [natDegree_multiset_prod'] simp_rw [Ne.def, Multiset.prod_eq_zero_iff, Multiset.mem_map, leadingCoeff_eq_zero] rintro ⟨_, h, rfl⟩ contradiction #align polynomial.nat_degree_multiset_prod Polynomial.natDegree_multiset_prod /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is βŠ₯. -/ theorem degree_multiset_prod [Nontrivial R] : t.prod.degree = (t.map fun f => degree f).sum := map_multiset_prod (@degreeMonoidHom R _ _ _) _ #align polynomial.degree_multiset_prod Polynomial.degree_multiset_prod /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is βŠ₯. -/ theorem degree_prod [Nontrivial R] : (∏ i in s, f i).degree = βˆ‘ i in s, (f i).degree := map_prod (@degreeMonoidHom R _ _ _) _ _ #align polynomial.degree_prod Polynomial.degree_prod /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `Polynomial.leadingCoeff_multiset_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ theorem leadingCoeff_multiset_prod : t.prod.leadingCoeff = (t.map fun f => leadingCoeff f).prod := by rw [← leadingCoeffHom_apply, MonoidHom.map_multiset_prod] rfl #align polynomial.leading_coeff_multiset_prod Polynomial.leadingCoeff_multiset_prod /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `Polynomial.leadingCoeff_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ theorem leadingCoeff_prod : (∏ i in s, f i).leadingCoeff = ∏ i in s, (f i).leadingCoeff := by simpa using leadingCoeff_multiset_prod (s.1.map f) #align polynomial.leading_coeff_prod Polynomial.leadingCoeff_prod end CommSemiring end NoZeroDivisors end Polynomial
#Data Source: Pulickamadhom Sreedhar, Sreehari, 2021, #"Student and Educator Perceptions of Online Classes" #https://doi.org/10.7910/DVN/2AAVSX, Harvard Dataverse, V1 #@michaelGRU library(stringr) library(utils) mode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } #find the length of a particular string pattern count_pattern <- function(str, vector) { return(length(vector[stringr::str_detect(vector, str)])) } df <- read.csv("data/Student and Educator Perceptions of Online Classes - Base data.csv") #quick summary of the df num_subjects <- dim(df) feature <- colnames(df) #student vs. educator analysis #number of students students <- subset(df, df$Are.you.a.student.or.an.educator. == "Student") count_studnets <- nrow(students) #number of professors and their experience educators<- subset(df, df$Are.you.a.student.or.an.educator. == "Educator") count_educator <- nrow(educators) exp_boxplot <- boxplot(educators$If.an.educator..for.how.many.years.have.you.been.an.educator.) #where are you currently employed at unique_employee_loc_count <- length(unique(df$Where.are.you.currently.employed.enrolled)) #How many are at university vs school uni_count <- length(df$Where.are.you.currently.employed.enrolled[stringr::str_detect(df$Where.are.you.currently.employed.enrolled, "/")]) school_count <- length(df$Where.are.you.currently.employed.enrolled[stringr::str_detect(df$Where.are.you.currently.employed.enrolled, "oo")]) #extract the last 2 chars last_two_letters_extract <- stringr::str_sub(df$Where.are.you.currently.employed.enrolled, start = -2) ### #group by students vs educators tapply(df$How.do.you.rate.yourself.on.your.ability.to.use.virtual.meeting.platforms..on.a.scale.of.1.10., df$Are.you.a.student.or.an.educator., mean) tapply(df$How.would.you.rate.your.internet.connectivity.on.a.scale.of.1.10., df$Are.you.a.student.or.an.educator., mean) tapply(df$How.effective.do.you.think.online.classes.are.in.communicating.content.and.intent.in.a.classroom..on.a.scale.of.1.10., df$Are.you.a.student.or.an.educator., mean) tapply(df$How.would.you.rate.your.ability.to.concentrate.during.online.classes..on.a.scale.of.1.10., df$Are.you.a.student.or.an.educator., mean) #answer to do long hours in a virtual classroom cause discomfort pain_count <- length(df$Do.long.hours.in.a.virtual.classroom.cause.discomfort.such.as.headaches..sleep.disturbances..back.pain.[stringr::str_detect(df$Do.long.hours.in.a.virtual.classroom.cause.discomfort.such.as.headaches..sleep.disturbances..back.pain., "Yes")]) no_pain_count <- length(df$Do.long.hours.in.a.virtual.classroom.cause.discomfort.such.as.headaches..sleep.disturbances..back.pain.[stringr::str_detect(df$Do.long.hours.in.a.virtual.classroom.cause.discomfort.such.as.headaches..sleep.disturbances..back.pain., "No")]) #add a column that converts the binary pain ans df$pain_binary <- ifelse(df$Do.long.hours.in.a.virtual.classroom.cause.discomfort.such.as.headaches..sleep.disturbances..back.pain.== "Yes", 1, 0) #percentage of people who reported pain percentage_pain <- mean(df$pain_binary) #group by students vs. educator tapply(df$pain_binary, df$Are.you.a.student.or.an.educator., mean) ##create type df$type <- NA df$type[df$How.would.you.identify.yourself. == "Female" & df$Are.you.a.student.or.an.educator. == "Student"] <- "FemaleStudent" df$type[df$How.would.you.identify.yourself. == "Female" & df$Are.you.a.student.or.an.educator. == "Educator"] <- "FemaleEducator" df$type[df$How.would.you.identify.yourself. == "Male" & df$Are.you.a.student.or.an.educator. == "Student"] <- "MaleStudent" df$type[df$How.would.you.identify.yourself. == "Male" & df$Are.you.a.student.or.an.educator. == "Educator"] <- "MaleEducator" df$type[df$How.would.you.identify.yourself. != "Male" & df$How.would.you.identify.yourself. != "Female" & df$Are.you.a.student.or.an.educator. == "Educator"] <- "OtherEducator" df$type[df$How.would.you.identify.yourself. != "Male" & df$How.would.you.identify.yourself. != "Female" & df$Are.you.a.student.or.an.educator. == "Student"] <- "OtherStudent" table(df$type) tapply(df$How.do.you.rate.yourself.on.your.ability.to.use.virtual.meeting.platforms..on.a.scale.of.1.10., df$type, mean) tapply(df$How.would.you.rate.your.internet.connectivity.on.a.scale.of.1.10., df$type, mean) tapply(df$How.effective.do.you.think.online.classes.are.in.communicating.content.and.intent.in.a.classroom..on.a.scale.of.1.10., df$type, mean) tapply(df$How.would.you.rate.your.ability.to.concentrate.during.online.classes..on.a.scale.of.1.10., df$type, mean)
{-# LANGUAGE CPP #-} module Control.Instances.Package.Haskell2010 () where #ifdef MIN_VERSION_haskell2010 #if MIN_VERSION_haskell2010(1,1,2) import Prelude () import Control.Monad () import Data.Array () import Data.Bits () import Data.Char () import Data.Complex () import Data.Int () import Data.Ix () import Data.List () import Data.Maybe () import Data.Ratio () import Data.Word () import Foreign () import Foreign.C () import Foreign.C.Error () import Foreign.C.String () import Foreign.C.Types () import Foreign.ForeignPtr () import Foreign.Marshal () import Foreign.Marshal.Alloc () import Foreign.Marshal.Array () import Foreign.Marshal.Error () import Foreign.Marshal.Utils () import Foreign.Ptr () import Foreign.StablePtr () import Foreign.Storable () import Numeric () import System.Environment () import System.Exit () import System.IO () import System.IO.Error () #elif MIN_VERSION_haskell2010(1,1,1) import Data.Array () import Data.Char () import Data.Complex () import System.IO () import System.IO.Error () import Data.Ix () import Data.List () import Data.Maybe () import Control.Monad () import Data.Ratio () import System.Environment () import System.Exit () import Numeric () import Prelude () import Data.Int () import Data.Word () import Data.Bits () import Foreign () import Foreign.Ptr () import Foreign.ForeignPtr () import Foreign.StablePtr () import Foreign.Storable () import Foreign.C () import Foreign.C.Error () import Foreign.C.String () import Foreign.C.Types () import Foreign.Marshal () import Foreign.Marshal.Alloc () import Foreign.Marshal.Array () import Foreign.Marshal.Error () import Foreign.Marshal.Utils () #elif MIN_VERSION_haskell2010(1,1,0) import Data.Array () import Data.Char () import Data.Complex () import System.IO () import System.IO.Error () import Data.Ix () import Data.List () import Data.Maybe () import Control.Monad () import Data.Ratio () import System.Environment () import System.Exit () import Numeric () import Prelude () import Data.Int () import Data.Word () import Data.Bits () import Foreign () import Foreign.Ptr () import Foreign.ForeignPtr () import Foreign.StablePtr () import Foreign.Storable () import Foreign.C () import Foreign.C.Error () import Foreign.C.String () import Foreign.C.Types () import Foreign.Marshal () import Foreign.Marshal.Alloc () import Foreign.Marshal.Array () import Foreign.Marshal.Error () import Foreign.Marshal.Utils () #elif MIN_VERSION_haskell2010(1,1,0) import Data.Array () import Data.Char () import Data.Complex () import System.IO () import System.IO.Error () import Data.Ix () import Data.List () import Data.Maybe () import Control.Monad () import Data.Ratio () import System.Environment () import System.Exit () import Numeric () import Prelude () import Data.Int () import Data.Word () import Data.Bits () import Foreign () import Foreign.Ptr () import Foreign.ForeignPtr () import Foreign.StablePtr () import Foreign.Storable () import Foreign.C () import Foreign.C.Error () import Foreign.C.String () import Foreign.C.Types () import Foreign.Marshal () import Foreign.Marshal.Alloc () import Foreign.Marshal.Array () import Foreign.Marshal.Error () import Foreign.Marshal.Utils () #elif MIN_VERSION_haskell2010(1,0,0) import Data.Array () import Data.Char () import Data.Complex () import System.IO () import System.IO.Error () import Data.Ix () import Data.List () import Data.Maybe () import Control.Monad () import Data.Ratio () import System.Environment () import System.Exit () import Numeric () import Prelude () import Data.Int () import Data.Word () import Data.Bits () import Foreign () import Foreign.Ptr () import Foreign.ForeignPtr () import Foreign.StablePtr () import Foreign.Storable () import Foreign.C () import Foreign.C.Error () import Foreign.C.String () import Foreign.C.Types () import Foreign.Marshal () import Foreign.Marshal.Alloc () import Foreign.Marshal.Array () import Foreign.Marshal.Error () import Foreign.Marshal.Utils () #endif #endif
[GOAL] V : SemiNormedGroupCat v : ↑V ⊒ β€–(fun v => ↑↑V v) vβ€– ≀ 1 * β€–vβ€– [PROOFSTEP] simp [GOAL] V : SemiNormedGroupCat W : SemiNormedGroupCat ⊒ βˆ€ (P Q R : SemiNormedGroupCat) (f f' : P ⟢ Q) (g : Q ⟢ R), (f + f') ≫ g = f ≫ g + f' ≫ g [PROOFSTEP] intros _ Q _ f f' g [GOAL] V : SemiNormedGroupCat W : SemiNormedGroupCat P✝ Q R✝ : SemiNormedGroupCat f f' : P✝ ⟢ Q g : Q ⟢ R✝ ⊒ (f + f') ≫ g = f ≫ g + f' ≫ g [PROOFSTEP] ext x [GOAL] case h V : SemiNormedGroupCat W : SemiNormedGroupCat P✝ Q R✝ : SemiNormedGroupCat f f' : P✝ ⟢ Q g : Q ⟢ R✝ x : ↑P✝ ⊒ ↑((f + f') ≫ g) x = ↑(f ≫ g + f' ≫ g) x [PROOFSTEP] rw [NormedAddGroupHom.add_apply, CategoryTheory.comp_apply, CategoryTheory.comp_apply, CategoryTheory.comp_apply, @NormedAddGroupHom.add_apply _ _ (_) (_)] [GOAL] case h V : SemiNormedGroupCat W : SemiNormedGroupCat P✝ Q R✝ : SemiNormedGroupCat f f' : P✝ ⟢ Q g : Q ⟢ R✝ x : ↑P✝ ⊒ ↑g (↑f x + ↑f' x) = ↑g (↑f x) + ↑g (↑f' x) [PROOFSTEP] convert map_add g (f x) (f' x) [GOAL] V : SemiNormedGroupCat W : SemiNormedGroupCat ⊒ βˆ€ (P Q R : SemiNormedGroupCat) (f : P ⟢ Q) (g g' : Q ⟢ R), f ≫ (g + g') = f ≫ g + f ≫ g' [PROOFSTEP] intros [GOAL] V : SemiNormedGroupCat W : SemiNormedGroupCat P✝ Q✝ R✝ : SemiNormedGroupCat f✝ : P✝ ⟢ Q✝ g✝ g'✝ : Q✝ ⟢ R✝ ⊒ f✝ ≫ (g✝ + g'✝) = f✝ ≫ g✝ + f✝ ≫ g'✝ [PROOFSTEP] ext -- Porting note: failing simps probably due to instance synthesis issues with concrete -- cats; see the gymnastics below for what used to be -- simp only [add_apply, comp_apply. map_add] [GOAL] case h V : SemiNormedGroupCat W : SemiNormedGroupCat P✝ Q✝ R✝ : SemiNormedGroupCat f✝ : P✝ ⟢ Q✝ g✝ g'✝ : Q✝ ⟢ R✝ x✝ : ↑P✝ ⊒ ↑(f✝ ≫ (g✝ + g'✝)) x✝ = ↑(f✝ ≫ g✝ + f✝ ≫ g'✝) x✝ [PROOFSTEP] rw [NormedAddGroupHom.add_apply, CategoryTheory.comp_apply, CategoryTheory.comp_apply, CategoryTheory.comp_apply, @NormedAddGroupHom.add_apply _ _ (_) (_)]
(* Title: OAodv.thy License: BSD 2-Clause. See LICENSE. Author: Timothy Bourke, Inria *) section "The `open' AODV model" theory OAodv imports Aodv AWN.OAWN_SOS_Labels AWN.OAWN_Convert begin text \<open>Definitions for stating and proving global network properties over individual processes.\<close> definition \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V' :: "((ip \<Rightarrow> state) \<times> ((state, msg, pseqp, pseqp label) seqp)) set" where "\<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V' \<equiv> {(\<lambda>i. aodv_init i, \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V PAodv)}" abbreviation opaodv :: "ip \<Rightarrow> ((ip \<Rightarrow> state) \<times> (state, msg, pseqp, pseqp label) seqp, msg seq_action) automaton" where "opaodv i \<equiv> \<lparr> init = \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V', trans = oseqp_sos \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V i \<rparr>" lemma initiali_aodv [intro!, simp]: "initiali i (init (opaodv i)) (init (paodv i))" unfolding \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V_def \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_def by rule simp_all lemma oaodv_control_within [simp]: "control_within \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (init (opaodv i))" unfolding \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_def by (rule control_withinI) (auto simp del: \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V_simps) lemma \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_labels [simp]: "(\<sigma>, p) \<in> \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V' \<Longrightarrow> labels \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V p = {PAodv-:0}" unfolding \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_def by simp lemma oaodv_init_kD_empty [simp]: "(\<sigma>, p) \<in> \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V' \<Longrightarrow> kD (rt (\<sigma> i)) = {}" unfolding \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_def kD_def by simp lemma oaodv_init_vD_empty [simp]: "(\<sigma>, p) \<in> \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V' \<Longrightarrow> vD (rt (\<sigma> i)) = {}" unfolding \<sigma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V'_def vD_def by simp lemma oaodv_trans: "trans (opaodv i) = oseqp_sos \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V i" by simp declare oseq_invariant_ctermsI [OF aodv_wf oaodv_control_within aodv_simple_labels oaodv_trans, cterms_intros] oseq_step_invariant_ctermsI [OF aodv_wf oaodv_control_within aodv_simple_labels oaodv_trans, cterms_intros] end
(* Title: Isomorphism Classes of Groups Author: Jakob von Raumer, Karlsruhe Institute of Technology Maintainer: Jakob von Raumer <[email protected]> *) theory GroupIsoClasses imports "Groups" "List" "Coset" begin section {* Isomorphism Classes of Groups *} text {* We construct a quotient type for isomorphism classes of groups. *} typedef 'a group = "{G :: 'a monoid. group G}" proof show "\<And>a. \<lparr>carrier = {a}, mult = (\<lambda>x y. x), one = a\<rparr> \<in> {G. group G}" unfolding group_def group_axioms_def monoid_def Units_def by auto qed definition group_iso_rel :: "'a group \<Rightarrow> 'a group \<Rightarrow> bool" where "group_iso_rel G H = (\<exists>\<phi>. \<phi> \<in> Rep_group G \<cong> Rep_group H)" quotient_type 'a group_iso_class = "'a group" / group_iso_rel morphisms Rep_group_iso Abs_group_iso proof (rule equivpI) show "reflp group_iso_rel" proof (rule reflpI) fix G :: "'b group" show "group_iso_rel G G" unfolding group_iso_rel_def using Rep_group iso_refl by auto qed next show "symp group_iso_rel" proof (rule sympI) fix G H :: "'b group" assume "group_iso_rel G H" then obtain \<phi> where "\<phi> \<in> Rep_group G \<cong> Rep_group H" unfolding group_iso_rel_def by auto then obtain \<phi>' where "\<phi>' \<in> Rep_group H \<cong> Rep_group G" using group.iso_sym Rep_group by fastforce thus "group_iso_rel H G" unfolding group_iso_rel_def by auto qed next show "transp group_iso_rel" proof (rule transpI) fix G H I :: "'b group" assume "group_iso_rel G H" "group_iso_rel H I" then obtain \<phi> \<psi> where "\<phi> \<in> Rep_group G \<cong> Rep_group H" "\<psi> \<in> Rep_group H \<cong> Rep_group I" unfolding group_iso_rel_def by auto then obtain \<pi> where "\<pi> \<in> Rep_group G \<cong> Rep_group I" using group.iso_trans Rep_group by fastforce thus "group_iso_rel G I" unfolding group_iso_rel_def by auto qed qed text {* This assigns to a given group the group isomorphism class *} definition (in group) iso_class :: "'a group_iso_class" where "iso_class = Abs_group_iso (Abs_group (monoid.truncate G))" text {* Two isomorphic groups do indeed have the same isomorphism class: *} lemma iso_classes_iff: assumes "group G" assumes "group H" shows "(\<exists>\<phi>. \<phi> \<in> G \<cong> H) = (group.iso_class G = group.iso_class H)" proof - from assms(1,2) have groups:"group (monoid.truncate G)" "group (monoid.truncate H)" unfolding monoid.truncate_def group_def group_axioms_def Units_def monoid_def by auto have "(\<exists>\<phi>. \<phi> \<in> G \<cong> H) = (\<exists>\<phi>. \<phi> \<in> (monoid.truncate G) \<cong> (monoid.truncate H))" unfolding iso_def hom_def monoid.truncate_def by auto also have "\<dots> = group_iso_rel (Abs_group (monoid.truncate G)) (Abs_group (monoid.truncate H))" unfolding group_iso_rel_def using groups group.Abs_group_inverse by (metis mem_Collect_eq) also have "\<dots> = (group.iso_class G = group.iso_class H)" using group.iso_class_def assms group_iso_class.abs_eq_iff by metis finally show ?thesis. qed end
/** * * Copyright 2018, Planet Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multifit.h> #include <math.h> void wrap_gsl_multifit_robust(double *x, double *y, double *c, double *adj_Rsqrd, int *numIter, double *rmse, int method, int perPixelX, int numRows, int numCols, int numImages, int numParams, int numRowsX, int numColsX, double nullVal);
In the 1988 – 89 season , Jordan again led the league in scoring , averaging 32 @.@ 5 ppg on 53 @.@ 8 % shooting from the field , along with 8 rpg and 8 assists per game ( apg ) . The Bulls finished with a 47 – 35 record , and advanced to the Eastern Conference Finals , defeating the Cavaliers and New York Knicks along the way . The Cavaliers series included a career highlight for Jordan when he hit The Shot over Craig <unk> at the buzzer in the fifth and final game of the series . However , the Pistons again defeated the Bulls , this time in six games , by utilizing their " Jordan Rules " method of guarding Jordan , which consisted of double and triple teaming him every time he touched the ball .
import tactic -- Let X be the set {A,B,C} inductive X | A : X | B : X | C : X open X def R (x y : X) : Prop := (x = A ∧ y = B) ∨ (x = A ∧ y = C) -- R(A,B) and R(A,C) both true, everything else false theorem R_fst {x y : X} : R x y β†’ x = A := begin intro h, cases h, cases h, assumption, cases h, assumption, end example : transitive R := begin intros x y z, intro hxy, intro hyz, have h1 := R_fst hxy, have h2 := R_fst hyz, subst h1, subst h2, assumption, end example (P Q : Prop) : (P β†’ Q) β†’ (Β¬ Q β†’ Β¬ P) := begin intro hPQ, intro hnQ, intro hP, apply hnQ, exact hPQ hP, end
From mathcomp.ssreflect Require Import ssreflect ssrfun ssrbool ssrnat eqtype fintype. Set Implicit Arguments. Require Import compcert.lib.Axioms. Record pos := mkPos { n :> nat ; N_pos : (0 < n)%coq_nat }. Lemma is_pos (p : pos) : 0 < p. Proof. by case: p=> m pf; apply/ltP. Qed. Definition i0 (p : pos) : 'I_p := Ordinal (is_pos p). Require Import Omega. Lemma is_pos_incr (n : nat) : (0 < n.+1)%coq_nat. Proof. omega. Qed. Definition pos_incr (p : pos) : pos := mkPos (is_pos_incr p). Lemma pos_incr_lt (p : pos) : p < pos_incr p. Proof. by []. Qed. Definition ordinal_pos_incr (p : pos) : 'I_(pos_incr p) := Ordinal (pos_incr_lt p). Section PosEqType. Definition pos_eq := [rel u v : pos | n u == n v]. Lemma pos_eqP : Equality.axiom pos_eq. Proof. move=> /=; case=> n0 pf0; case=> n1 pf1. case Heq: (n0 == n1). { move: (eqP Heq) pf0 pf1=> -> pf0 pf1. have ->: pf0 = pf1 by apply: proof_irr. by apply: ReflectT. } { apply: ReflectF; case=> Heq1. by move: Heq; rewrite Heq1; move/eqP; apply. } Qed. Definition pos_eqMixin := EqMixin pos_eqP. Canonical pos_eqType := Eval hnf in EqType pos pos_eqMixin. Lemma pos_eqE : pos_eq = eq_op :> rel _. Proof. by []. Qed. End PosEqType.
-- This file is imported by Issue1597.Main module Issue1597 where module A where module M where -- needs to be module postulate Nat : Set
lemma measure_lborel_singleton[simp]: "measure lborel {x} = 0"
[STATEMENT] lemma freeIn_substInfinitesimalQuadratic_fm : assumes "var \<notin> vars a" "var \<notin> vars b" "var \<notin> vars c" "var \<notin> vars d" shows"freeIn var (substInfinitesimalQuadratic_fm var a b c d F)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] fix z [PROOF STATE] proof (state) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] have "freeIn (var+z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z) [PROOF STEP] apply(induction F arbitrary:z) [PROOF STATE] proof (prove) goal (10 subgoals): 1. \<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) TrueF z) 2. \<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) FalseF z) 3. \<And>x z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (fm.Atom x) z) 4. \<And>F1 F2 z. \<lbrakk>\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F1 z); \<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F2 z)\<rbrakk> \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (And F1 F2) z) 5. \<And>F1 F2 z. \<lbrakk>\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F1 z); \<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F2 z)\<rbrakk> \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (Or F1 F2) z) 6. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (Neg F) z) 7. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (ExQ F) z) 8. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (AllQ F) z) 9. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (ExN x1 F) z) 10. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) (AllN x1 F) z) [PROOF STEP] apply auto [PROOF STATE] proof (prove) goal (5 subgoals): 1. \<And>x z. freeIn (var + z) (substInfinitesimalQuadratic (var + z) (liftPoly 0 z a) (liftPoly 0 z b) (liftPoly 0 z c) (liftPoly 0 z d) x) 2. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 3. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 4. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) 5. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] apply(rule freeIn_substInfinitesimalQuadratic) [PROOF STATE] proof (prove) goal (8 subgoals): 1. \<And>x z. var + z \<notin> vars (liftPoly 0 z a) 2. \<And>x z. var + z \<notin> vars (liftPoly 0 z b) 3. \<And>x z. var + z \<notin> vars (liftPoly 0 z c) 4. \<And>x z. var + z \<notin> vars (liftPoly 0 z d) 5. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 6. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 7. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) 8. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] apply (simp_all add: assms not_in_lift) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 2. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 3. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) 4. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] apply (metis (no_types, lifting) add_Suc_right) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (Suc (var + z)) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (Suc z)) 2. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) 3. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] apply (metis (mono_tags, lifting) add_Suc_right) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) 2. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] apply (simp add: ab_semigroup_add_class.add_ac(1)) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x1 F z. (\<And>z. freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z)) \<Longrightarrow> freeIn (var + z + x1) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F (z + x1)) [PROOF STEP] by (simp add: add.assoc) [PROOF STATE] proof (state) this: freeIn (var + z) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F z) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] } [PROOF STATE] proof (state) this: freeIn (var + ?z2) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F ?z2) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: freeIn (var + ?z2) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F ?z2) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: freeIn (var + ?z2) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F ?z2) goal (1 subgoal): 1. freeIn var (substInfinitesimalQuadratic_fm var a b c d F) [PROOF STEP] unfolding substInfinitesimalQuadratic_fm.simps [PROOF STATE] proof (prove) using this: freeIn (var + ?z2) (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F ?z2) goal (1 subgoal): 1. freeIn var (liftmap (\<lambda>x. substInfinitesimalQuadratic (var + x) (liftPoly 0 x a) (liftPoly 0 x b) (liftPoly 0 x c) (liftPoly 0 x d)) F 0) [PROOF STEP] by (metis (no_types, lifting) add.right_neutral) [PROOF STATE] proof (state) this: freeIn var (substInfinitesimalQuadratic_fm var a b c d F) goal: No subgoals! [PROOF STEP] qed
Formal statement is: lemma compact_imp_fip: assumes "compact S" and "\<And>T. T \<in> F \<Longrightarrow> closed T" and "\<And>F'. finite F' \<Longrightarrow> F' \<subseteq> F \<Longrightarrow> S \<inter> (\<Inter>F') \<noteq> {}" shows "S \<inter> (\<Inter>F) \<noteq> {}" Informal statement is: If $S$ is compact and each $T \in F$ is closed, then $S \cap \bigcap F \neq \emptyset$.
import numpy as np import pytest from deslib.util.instance_hardness import hardness_region_competence from deslib.util.instance_hardness import kdn_score # ------Test routines for the Instance Hardness calculation------------------ @pytest.mark.parametrize('index, expected', [(0, 0.42), (1, 0.28), (2, 0.28)]) def test_instance_hardness_region(index, expected, example_estimate_competence): y, neighbors = example_estimate_competence[1:3] k = 7 neighbors = neighbors[index, :] IH = hardness_region_competence(neighbors, y, k) assert np.isclose(IH, expected, atol=0.01) def test_instance_hardness_region_batch(example_estimate_competence): expected = np.array([0.42, 0.28, 0.28]) y, neighbors = example_estimate_competence[1:3] k = 7 IH = hardness_region_competence(neighbors, y, k) assert np.allclose(IH, expected, atol=0.01) def test_instance_hardness_region_all_same(example_estimate_competence): y = example_estimate_competence[1] k = 7 neighbors = np.array([0, 1, 2, 6, 7, 8, 13]) IH = hardness_region_competence(neighbors, y, k) assert IH == 0.0 def test_kdn_score(example_estimate_competence): X, y, neigh, dist, _, _ = example_estimate_competence X, y = X[0:6, :], y[0:6] score, _ = kdn_score(X, y, 3) assert np.allclose(score, 0.3333333)
import cv2 import matplotlib.pyplot as plt import numpy as np def create_montage_image(image_list, image_shape=(640, 480), grid_shape=(3, 1)) -> np.ndarray: height, width = image_shape[1], image_shape[0] montage = np.zeros((image_shape[1] * grid_shape[1], image_shape[0] * grid_shape[0], 3), dtype="uint8") x_shift = 0 y_shift = 0 for n in range(len(image_list)): image = cv2.resize(image_list[n], (width, height), interpolation=cv2.INTER_NEAREST) montage[y_shift * height: (y_shift + 1) * height, x_shift * width: (x_shift + 1) * width] = image x_shift += 1 if x_shift % (grid_shape[0]) == 0 and x_shift > 0: y_shift += 1 x_shift = 0 return montage def colorize(image, vmin=None, vmax=None, cmap='turbo'): vmin = image.min() if vmin is None else vmin vmax = image.max() if vmax is None else vmax if vmin != vmax: image = (image - vmin) / (vmax - vmin) else: image = image * 0. cmapper = plt.cm.get_cmap(cmap) image = cmapper(image, bytes=True) img = image[:, :, :3] return img
{-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOT.FOTC.Program.McCarthy91.WF-Relation.Induction.NonAcc.TerminationCheckIssue where data β„• : Set where zero : β„• succ : β„• β†’ β„• {-# BUILTIN NATURAL β„• #-} postulate someβ„• : β„• {-# TERMINATING #-} foo : β„• β†’ β„• β†’ β„• foo n zero = 10 foo zero (succ m) = foo zero someβ„• foo (succ n) (succ m) = foo n (succ m) {-# TERMINATING #-} bar : β„• β†’ β„• β†’ β„• bar n zero = 10 bar zero (succ m) = bar m someβ„• bar (succ n) (succ m) = bar n (succ m) {-# TERMINATING #-} foobar : β„• β†’ β„• β†’ β„• foobar n zero = 10 foobar zero (succ m) with someβ„• ... | zero = 10 ... | succ o = foobar m (succ o) foobar (succ n) (succ m) = foobar n (succ m)
corollary Cauchy_theorem_global_outside: assumes "open S" "f holomorphic_on S" "valid_path \<gamma>" "pathfinish \<gamma> = pathstart \<gamma>" "path_image \<gamma> \<subseteq> S" "\<And>w. w \<notin> S \<Longrightarrow> w \<in> outside(path_image \<gamma>)" shows "(f has_contour_integral 0) \<gamma>"
module Extensions.ListFirstFunctional where open import Prelude hiding (_βŠ”_) open import Level private lemma : βˆ€ {a b} {A : Set a} {P : A β†’ Set b} (decP : βˆ€ a β†’ (Dec $ P a)) v {x y} β†’ any decP (x List.∷ v) ≑ yes (there {x = x} y) β†’ Β¬ P x lemma decP v {x} {y} eq p with decP x lemma decP v () p | yes _ lemma decP v eq p | no Β¬p = Β¬p p -- first is functionally defined as the element matched by 'any' First : βˆ€ {a b} {A : Set a} {P : A β†’ Set b} (decP : βˆ€ a β†’ (Dec $ P a)) β†’ List A β†’ Set (a βŠ” b) First f v = βˆƒ Ξ» m β†’ any f v ≑ yes m private There : βˆ€ {a b} {A : Set a} {P : A β†’ Set b} {f v} β†’ (f : First {P = P} f v) β†’ Set There (here px , _) = βŠ₯ There (there _ , _) = ⊀ head-first : βˆ€ {a b} {A : Set a} {P : A β†’ Set b} {f v} β†’ First {P = P} f v β†’ A head-first (here {x} _ , _) = x head-first (there {x} _ , _) = x -- we can recover the negative evidence even though Any does not "save it" for there-instances there⟢¬x' : βˆ€ {a b} {A : Set a} {P : A β†’ Set b} {decP v} β†’ (f : First {P = P} decP v) β†’ {x : There f} β†’ Β¬ P (head-first f) there⟢¬x' (here px , projβ‚‚) {x = ()} there⟢¬x' {P = P} {decP = decP} (there {x = x'} {xs = xs} tail , projβ‚‚) px with lemma decP xs there⟢¬x' {P = P} {decP = decP} (there {x = x'} {xs = xs} tail , projβ‚‚) px | Β¬px = Β¬px projβ‚‚ px
#include <stan/math/rev/scal.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/scal/fun/nan_util.hpp> #include <test/unit/math/rev/scal/util.hpp> #include <boost/math/special_functions/erf.hpp> TEST(AgradRev, erf) { AVAR a = 1.3; AVAR f = erf(a); EXPECT_FLOAT_EQ(stan::math::erf(1.3), f.val()); AVEC x = createAVEC(a); VEC grad_f; f.grad(x, grad_f); EXPECT_FLOAT_EQ(2.0 / std::sqrt(boost::math::constants::pi<double>()) * std::exp(-1.3 * 1.3), grad_f[0]); } struct erf_fun { template <typename T0> inline T0 operator()(const T0& arg1) const { return erf(arg1); } }; TEST(AgradRev, erf_NaN) { erf_fun erf_; test_nan(erf_, false, true); } TEST(AgradRev, check_varis_on_stack) { AVAR a = 1.3; test::check_varis_on_stack(stan::math::erf(a)); }
/- Copyright (c) 2022 by the authors listed in the file AUTHORS and their institutional affiliations. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Meta.Basic import Lean.Meta.Eqns import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.Term import Smt.Tactic.WHNFSmt /-! Utilities for handling "equational definitions". An equational definition is an equation of the form `βˆ€ x₁ β‹― xβ‚™, c x₁ β‹― xβ‚™ = body[x₁,β‹―,xβ‚™]` in the local context, where `c` is either a global constant or a local variable. The LHS should be fully applied so that the equality is not at a universally quantified (aka function) type. These usually start off as copied equational theorems of global constants but are then transformed to an SMT-compatible form. Note that equational definitions have an advantage over let-bindings in that we do not need to justify the termination of `body`. This does however imply that rewriting by an equational definition may never reach a fixpoint. ## Representation The equational definition for `foo` is stored as `foo.def` in the local context. TODO(WN): We could have a custom `smt` tactic mode which provides explicit storage for eqn-defs and displays them more nicely. -/ namespace Smt open Lean Meta Elab Term Tactic /-- The user name of an equational definition for 'nm'. -/ def eqnDefName (nm : Name) : Name := nm ++ `def def throwNotEqnDef [Monad m] [MonadError m] (e : Expr) : m Ξ± := throwError "expected equational definition, got{indentD e}" /-- Get the head symbol `c` of an equational definition. -/ def getEqnDefHead (eqn : Expr) : MetaM Expr := forallTelescopeReducing eqn fun _ eqn => do let some (_, lhs, _) := eqn.eq? | throwNotEqnDef eqn return lhs.getAppFn /-- Get the body of an equational definition as a lambda `fun x₁ β‹― xβ‚™ => body[x₁,β‹―,xβ‚™]`. -/ def getEqnDefLam (eqn : Expr) : MetaM Expr := forallTelescopeReducing eqn fun args eqn => do let some (_, _, body) := eqn.eq? | throwNotEqnDef eqn mkLambdaFVars args body /-- If `nm` has an equational definition, `getEqnDefLam` it. -/ def getEqnDefLamFor? (nm : Name) : MetaM (Option Expr) := do let some ld := (← getLCtx).findFromUserName? (eqnDefName nm) | return none getEqnDefLam ld.type /-- Add an equational definition `$nm.def : βˆ€ x₁ β‹― xβ‚™, $nm x₁ β‹― xβ‚™ = body[x₁,β‹―,xβ‚™]` for a constant and return the equation's fvar. -/ def addEqnDefForConst (nm : Name) : TacticM FVarId := do let some eqnThm ← getUnfoldEqnFor? (nonRec := true) nm | throwError "failed to retrieve equation theorem for '{nm}'" let eqnInfo ← getConstInfo eqnThm let (eqn, pf) ← forallTelescopeReducing eqnInfo.type fun args eqn => do let some (_, lhs, body) := eqn.eq? | throwNotEqnDef eqn let pf ← mkAppOptM eqnInfo.name (args.map some) /- Consider the curried definition ```lean def baw (a : Int) : Int β†’ Int := Int.add a ``` For this, Lean generates the equational theorem ```lean βˆ€ (a : Int), baw a = Int.add a ``` which is transformed by the first `forallTelescope` into `baw a = Int.add a`, an equality at a function type. Since we want equational definitions to be fully applied, we need to apply a second `forallTelescope` on the type of this equality in order to get `baw a b = Int.add a b`, which then gets abstracted into `βˆ€ (a b : Int), baw a b = Int.add a b`. -/ forallTelescopeReducing (← inferType lhs) fun args' _ => do let lhs' ← mkAppOptM' lhs (args'.map some) let body' ← mkAppOptM' body (args'.map some) let eq ← mkEq lhs' body' let pf ← args'.foldlM (init := pf) (mkCongrFun Β· Β·) -- Abstract the proof into a lambda with a forall type let eqAbstracted ← mkForallFVars (args ++ args') eq let pfAbstracted ← mkLambdaFVars (args ++ args') pf let pfAbstracted ← ensureHasType (some eqAbstracted) pfAbstracted return (eqAbstracted, pfAbstracted) liftMetaTacticAux fun mvarId => do let (fv, mvarId) ← (← mvarId.assert (nm ++ `def) eqn pf).intro1P return (fv, [mvarId]) /-- Given `e : tp`, make a local constant `$nm : tp := e` and add an equational definition `$nm.def : βˆ€ x₁ β‹― xβ‚™, $nm x₁ β‹― xβ‚™ = e x₁ β‹― xβ‚™` for it. Return fvar ids of the constant and the equation. `e` is expected to be fully abstracted, i.e. of the form `fun x₁ β‹― xβ‚™ => body` where `body` does not have a forall type. -/ def addEqnDefWithBody (nm : Name) (e : Expr) : TacticM (FVarId Γ— FVarId) := do let tp ← inferType e let fvVar ← liftMetaTacticAux fun mvarId => do -- TODO: We have to `define` in order for the proofs to go through, but ideally -- we would hide the actual `let` body in the goal state as it's already shown -- in the equational definition. let (fvVar, mvarId) ← (← mvarId.define nm tp e).intro1P return (fvVar, [mvarId]) let (eqn, pf) ← withMainContext <| lambdaTelescope e fun args body => do let lhs ← mkAppOptM' (mkFVar fvVar) (args.map some) let eqn ← mkEq lhs body let pf ← mkEqRefl lhs -- Abstract the proof into a lambda with a forall type let eqAbstracted ← mkForallFVars args eqn let pfAbstracted ← mkLambdaFVars args pf let pfAbstracted ← ensureHasType (some eqAbstracted) pfAbstracted return (eqAbstracted, pfAbstracted) liftMetaTacticAux fun mvarId => do let (fvEq, mvarId) ← (← mvarId.assert (nm ++ `def) eqn pf).intro1P return ((fvVar, fvEq), [mvarId]) open Lean Meta Elab Tactic in /-- Place an equational definition for a constant in the local context. -/ elab "extract_def" i:ident : tactic => do let nm ← resolveGlobalConstNoOverloadWithInfo i let _ ← addEqnDefForConst nm /-- Specialize an equational definition via partial evaluation. See `specialize_def`. -/ def specializeEqnDef (x : FVarId) (args : Array Expr) (opaqueConsts : HashSet Name := {}) : TacticM FVarId := do withMainContext do let eqn ← inferType (mkFVar x) -- Compute specialized body let newEqn ← instantiateForall eqn args let newLamBody ← getEqnDefLam newEqn let newLamBody ← smtOpaqueReduce newLamBody opaqueConsts -- Compute specialization name let ld ← x.getDecl let some nm := ld.userName.eraseSuffix? `def | throwError "{mkFVar x} is not an eqn def!" let nm ← args.foldlM (init := nm) fun nm arg => do let txt := toString (← ppExpr arg) -- let txt := txt.replace " " "_" return nm ++ Name.mkSimple txt -- Define the specialization let (fvVar, _fvEq) ← addEqnDefWithBody nm newLamBody -- TODO: these nested withContexts are a bit wonky, can we get a nicer api? `withAddEqnDefForLocal` or something withMainContext do -- Compute the rewrite helper let (eqnRw, pfRw) ← forallTelescope newEqn fun fvArgs newEqn => do let some (_, specializedHead, _) := newEqn.eq? | throwNotEqnDef newEqn let rhs ← mkAppOptM' (mkFVar fvVar) (fvArgs.map some) let eqnRw ← mkEq specializedHead rhs -- TODO: Typechecking partial evaluations is currently a fundamental performance bottleneck let pf ← mkSorry eqnRw false -- let pf ← mkAppOptM' (mkFVar fvEq) (fvArgs.map some) -- let pf ← mkEqSymm pf let eqAbstracted ← mkForallFVars fvArgs eqnRw let pfAbstracted ← mkLambdaFVars fvArgs pf --let pfAbstracted ← ensureHasType (some eqAbstracted) pfAbstracted return (eqAbstracted, pfAbstracted) liftMetaTacticAux fun mvarId => do let (fvEq, mvarId) ← (← mvarId.assert (nm ++ `specialization) eqnRw pfRw).intro1P return (fvEq, [mvarId]) syntax blockingConsts := "blocking [" term,* "]" /-- `specialize_def foo [arg₁, β‹―, argβ‚™]` introduces a new equational definition `foo.arg₁.β‹―.argβ‚™` whose body is the partial evaluation of `foo arg₁ β‹― argβ‚™`. During reduction, all SMT-LIB builtins are blocked from unfolding and `let_opaque` bindings are not zeta-eliminated. It also introduces a `foo.arg₁.β‹―.argβ‚™.specialization` equation which can be used to rewrite other expressions. You can block additional constants from unfolding during evaluation using `specialize_def foo [arg₁, β‹―, argβ‚™] blocking [bar₁, barβ‚‚]`. See `Playground/WHNFExamples.lean` for examples of partially evaluating definitions. **WARNING**: This is currently extremely slow! On any sizeable expression the evaluator, typechecker, or kernel is likely to time out. -/ syntax (name := specializeDef) "specialize_def" ident "[" term,* "]" optional(blockingConsts) : tactic open Lean Meta Elab Tactic in @[tactic specializeDef] def elabSpecializeDef : Tactic | `(tactic|specialize_def $i [ $ts,* ]) => go i ts {} | `(tactic|specialize_def $i [ $ts,* ] blocking [ $bs,* ]) => withMainContext do let opaqueConsts ← bs.getElems.foldlM (init := HashSet.empty) fun cs b => do match ← elabTerm b none with | .const nm _ => return cs.insert nm | .fvar fv => return cs.insert (← fv.getDecl).userName | _ => throwError "expected a (local) constant, got{indentD b}" go i ts opaqueConsts | stx => throwError "unexpected syntax {stx}" where go (i : TSyntax `ident) (ts : TSyntaxArray `term) (opaqueConsts : HashSet Name) : TacticM Unit := withMainContext do let nm := i.getId let ld ← getLocalDeclFromUserName (eqnDefName nm) let args ← forallTelescopeReducing (← inferType (mkFVar ld.fvarId)) fun args _ => do let mut ret : Array Expr := #[] for (stx, arg) in ts.zip args do let e ← elabTerm stx (some (← inferType arg)) ret := ret.push e return ret -- Block the function being specialized from unfolding in recursive definitions let opaqueConsts := opaqueConsts.insert nm let _ ← specializeEqnDef ld.fvarId args opaqueConsts end Smt
[GOAL] a : β„• ha : a ≀ pred a ⊒ IsMin a [PROOFSTEP] cases a [GOAL] case zero ha : zero ≀ pred zero ⊒ IsMin zero [PROOFSTEP] exact isMin_bot [GOAL] case succ n✝ : β„• ha : succ n✝ ≀ pred (succ n✝) ⊒ IsMin (succ n✝) [PROOFSTEP] exact (not_succ_le_self _ ha).elim [GOAL] a b : β„• h : a < b ⊒ a ≀ pred b [PROOFSTEP] cases b [GOAL] case zero a : β„• h : a < zero ⊒ a ≀ pred zero [PROOFSTEP] exact (a.not_lt_zero h).elim [GOAL] case succ a n✝ : β„• h : a < succ n✝ ⊒ a ≀ pred (succ n✝) [PROOFSTEP] exact le_of_succ_le_succ h [GOAL] a b : β„• h : pred a < b ⊒ a ≀ b [PROOFSTEP] cases a [GOAL] case zero b : β„• h : pred zero < b ⊒ zero ≀ b [PROOFSTEP] exact b.zero_le [GOAL] case succ b n✝ : β„• h : pred (succ n✝) < b ⊒ succ n✝ ≀ b [PROOFSTEP] exact h [GOAL] a n : β„• ⊒ succ^[n + 1] a = a + (n + 1) [PROOFSTEP] rw [Function.iterate_succ', add_succ] [GOAL] a n : β„• ⊒ (succ ∘ succ^[n]) a = succ (a + n) [PROOFSTEP] exact congr_arg _ (succ_iterate a n) [GOAL] a n : β„• ⊒ pred^[n + 1] a = a - (n + 1) [PROOFSTEP] rw [Function.iterate_succ', sub_succ] [GOAL] a n : β„• ⊒ (pred ∘ pred^[n]) a = pred (a - n) [PROOFSTEP] exact congr_arg _ (pred_iterate a n) [GOAL] a b : β„• h : a ≀ b ⊒ Order.succ^[b - a] a = b [PROOFSTEP] rw [succ_eq_succ, succ_iterate, add_tsub_cancel_of_le h] [GOAL] a b : β„• h : a ≀ b ⊒ Order.pred^[b - a] b = a [PROOFSTEP] rw [pred_eq_pred, pred_iterate, tsub_tsub_cancel_of_le h]
/* *Author:GeneralSandman *Code:https://github.com/GeneralSandman/TinyWeb *E-mail:[email protected] *Web:www.generalsandman.cn */ /*---XXX--- * **************************************** * */ #include <tiny_core/accepter.h> #include <tiny_core/eventloop.h> #include <tiny_core/netaddress.h> #include <tiny_base/api.h> #include <iostream> #include <unistd.h> #include <boost/bind.hpp> using namespace std; int number = 0; EventLoop *g_loop = nullptr; void ConnectionCallback(int connectfd, const NetAddress &peer) { string info = to_string(++number); cout << "new Connection:" << peer.getIpPort() << endl; cout << "write to:" << peer.getIpPort() << endl; writeString(connectfd, info); close(connectfd); } void fun1() { cout << "invoke per second\n"; } void timeout() { cout << "Timeout!\n"; g_loop->quit(); } int main() { g_loop = new EventLoop(); g_loop->runEvery(1, boost::bind(fun1)); g_loop->runAfter(200, boost::bind(timeout)); NetAddress server("127.0.0.1:9898"); Accepter accept(g_loop, server,createNoBlockSocket()); accept.setConnectionCallback(ConnectionCallback); accept.listen(); g_loop->loop(); delete g_loop; return 0; }
% Example script showcasing the functionality of slocstat % % @author B. Schauerte % @date 2012 %% % You can call it on a filename call = 'slocstat.m'; [sloc,stat] = slocstat(call); fprintf('Total number of lines %d for ''%s''\n',sloc,call); %% % You can call it on a function name call = 'slocstat'; [sloc,stat] = slocstat(call); fprintf('Total number of lines %d for ''%s''\n',sloc,call); % ... and of course of any (non-builtin) function in Matlab's search path, % e.g., "dct" call = 'dct'; [sloc,stat] = slocstat(call); fprintf('Total number of lines %d for ''%s''\n',sloc,call); %% % You can call it on a folder name and then it also makes sense to use % printslocstat call = '.'; [sloc,stat] = slocstat(call); fprintf('Total number of lines %d for ''%s''\n',sloc,call); printslocstat(stat);