Datasets:
AI4M
/

text
stringlengths
0
3.34M
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details RulesFor(DFT, rec( DFT_CT_Inplace := rec( info := "DFT(mn,k) -> DFT(m, k%m), DFT(n, k%n)", maxCodeletSize := 16, isApplicable := (self, P) >> P[1] > 2 and not IsPrime(P[1]), allChildren := (self, P) >> Map2( Filtered(DivisorPairs(P[1]), d -> d[1] <= self.maxCodeletSize), (m,n) -> [ DFT(m, P[2] mod m), DFT(n, P[2] mod n) ]), rule := (self,P,C) >> let(mn := P[1], m := Rows(C[1]), n := Rows(C[2]), di := fPrecompute(Tw1(mn, n, P[2])), When(mn > self.maxCodeletSize, # why BB? Inplace(Tensor(C[1], I(n)) * Diag(di)), Tensor(C[1], I(n)) * Diag(di)) * Tensor(I(m), C[2]) * L(mn, m)) ), DFT_SplitRadix_Inplace := rec( info := "DFT_n -> DFT_n/2, DFT_n/4, DFT_n/4", forTransposition := true, maxSize := 64, isApplicable := (self, P) >> let(N := P[1], N >= 8 and N mod 4 = 0 and N <= self.maxSize), allChildren := P -> let(N := P[1], w := P[2], [[ DFT(N/2, w), DFT(N/4, w) ]]), rule := (P, C) -> let(N := P[1], w := P[2], Inplace(Tensor(F(2), I(N/2))) * DirectSum( C[1], Inplace(BB( Tensor(Diag(1, E(4)^w) * F(2), I(N/4)) * Diag(Concat(List([0..N/4-1], i->E(N)^(w*i))), List([0..N/4-1], i->E(N)^(3*w*i))))) * Tensor(I(2), C[2])*L(N/2,2) ) * L(N, 2)) ), ));
hamming <- function(n) { a <- numeric(n) a[1] <- 1 for (i in 2:n) { a[i] <- nextn(a[i-1]+1) } a }
If $X$ is empty, then any two maps $f, g: X \to X'$ are homotopic.
[STATEMENT] lemma cat_simplicial_Cod_app'[cat_simplicial_cs_simps]: assumes "f : cat_ordinal m \<le>\<^sub>C\<^sub>.\<^sub>P\<^sub>E\<^sub>O\<^bsub>\<alpha>\<^esub> cat_ordinal n" and "m \<in>\<^sub>\<circ> A" and "n \<in>\<^sub>\<circ> A" shows "cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n [PROOF STEP] interpret f: is_preorder_functor \<alpha> \<open>cat_ordinal m\<close> \<open>cat_ordinal n\<close> f [PROOF STATE] proof (prove) goal (1 subgoal): 1. f : cat_ordinal m \<le>\<^sub>C\<^sub>.\<^sub>P\<^sub>E\<^sub>O\<^bsub>\<alpha>\<^esub> cat_ordinal n [PROOF STEP] by (rule assms(1)) [PROOF STATE] proof (state) goal (1 subgoal): 1. cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: f : cat_ordinal m \<le>\<^sub>C\<^sub>.\<^sub>P\<^sub>E\<^sub>O\<^bsub>\<alpha>\<^esub> cat_ordinal n m \<in>\<^sub>\<circ> A n \<in>\<^sub>\<circ> A [PROOF STEP] show "cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n" [PROOF STATE] proof (prove) using this: f : cat_ordinal m \<le>\<^sub>C\<^sub>.\<^sub>P\<^sub>E\<^sub>O\<^bsub>\<alpha>\<^esub> cat_ordinal n m \<in>\<^sub>\<circ> A n \<in>\<^sub>\<circ> A goal (1 subgoal): 1. cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n [PROOF STEP] by ( cs_concl cs_shallow cs_simp: cat_cs_simps cat_simplicial_Cod_app cs_intro: cat_simplicial_cs_intros ) [PROOF STATE] proof (state) this: cat_simplicial \<alpha> A\<lparr>Cod\<rparr>\<lparr>f\<rparr> = cat_ordinal n goal: No subgoals! [PROOF STEP] qed
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Data.Bool where open import Cubical.Data.Bool.Base public open import Cubical.Data.Bool.Properties public
{-# OPTIONS --without-K #-} open import Base open import Homotopy.PushoutDef open import Homotopy.PushoutUP as PushoutUP open import Homotopy.Truncation open import Homotopy.PullbackDef open import Homotopy.PullbackInvariantEquiv module Homotopy.TruncationRightExact {i} (n : ℕ₋₂) (d : pushout-diag i) where open pushout-diag d open import Homotopy.PushoutIsPushout d τd : pushout-diag i τd = diag (τ n A), (τ n B), (τ n C), (τ-fmap f), (τ-fmap g) module H = PushoutUP d (cst unit) module τH = PushoutUP τd (is-truncated n) -- I want to prove that [τ n d.pushout] is a pushout in [is-truncated n]. It -- first needs to be equipped with a cocone cocone-τpushout : τH.cocone (τ n (pushout d)) cocone-τpushout = (τ-fmap left , τ-fmap right , τ-extend ⦃ λ _ → ≡-is-truncated _ (τ-is-truncated _ _) ⦄ (ap proj ◯ glue)) -- We have a map [(τ n (pushout d) → E) → τH.cocone E] with [E] in [P] given by -- [τH.compose-cocone-map] and we want to prove that it’s an equivalence -- The idea is that it’s the composite of five equivalences: -- [equiv1 : τ n (pushout d) → E ≃ (pushout d) → E] -- by the universal property of truncations -- [equiv2 : (pushout d) → E ≃ H.cocone E] -- by the universal property of pushout in Type -- [equiv3 : H.cocone E ≃ pullback … (without truncations)] -- via [cocone-is-pullback] -- [equiv4 : pullback … (without truncations) ≃ pullback … (with truncations)] -- by the universal property of truncations and invariance of pullback wrt -- equivalence of diagrams -- [equiv5 : pullback … (with truncations) ≃ τH.cocone E] -- via [cocone-is-pullback] module _ (E : Set i) ⦃ P-E : is-truncated n E ⦄ where private ≡E-is-truncated#instance : {x y : E} → is-truncated n (x ≡ y) ≡E-is-truncated#instance = ≡-is-truncated n P-E λ-≡E-is-truncated#instance : {A : Set i} {u v : A → E} → ((x : A) → is-truncated n (u x ≡ v x)) λ-≡E-is-truncated#instance = λ _ → ≡E-is-truncated#instance ≡≡E-is-truncated#instance : {x y : E} {p q : x ≡ y} → is-truncated n (p ≡ q) ≡≡E-is-truncated#instance = ≡-is-truncated n (≡-is-truncated n P-E) λ-≡≡E-is-truncated#instance : {A : Set i} {x y : A → E} {p q : (a : A) → x a ≡ y a} → ((a : A) → is-truncated n (p a ≡ q a)) λ-≡≡E-is-truncated#instance = λ _ → ≡≡E-is-truncated#instance equiv1 : (τ n (pushout d) → E) ≃ (pushout d → E) equiv1 = ((λ u → u ◯ proj) , τ-up n _ _) equiv2 : (pushout d → E) ≃ H.cocone E equiv2 = ((λ f → ((f ◯ left) , (f ◯ right) , (ap f ◯ glue))) , pushout-is-pushout E) -- (could be defined more generally somewhere else) diag-hom : pullback-diag i diag-hom = diag (A → E), (B → E), (C → E), (λ u → u ◯ f), (λ u → u ◯ g) τdiag-hom : pullback-diag i τdiag-hom = diag (τ n A → E), (τ n B → E), (τ n C → E), (λ u → u ◯ τ-fmap f) , (λ u → u ◯ τ-fmap g) equiv3 : H.cocone E ≃ pullback diag-hom equiv3 = H.cocone-equiv-pullback E p₀ : (a : A → E) (x : τ n C) → τ-extend-nondep a (τ-fmap f x) ≡ τ-extend-nondep (a ◯ f) x p₀ a = τ-extend (λ x → refl) p : (a : A → E) → (τ-extend-nondep a) ◯ τ-fmap f ≡ τ-extend-nondep (a ◯ f) p a = funext (p₀ a) q₀ : (b : B → E) (x : τ n C) → τ-extend-nondep (b ◯ g) x ≡ τ-extend-nondep b (τ-fmap g x) q₀ b = τ-extend (λ x → refl) q : (b : B → E) → τ-extend-nondep (b ◯ g) ≡ (τ-extend-nondep b) ◯ τ-fmap g q b = funext (q₀ b) equiv4 : pullback diag-hom ≃ pullback τdiag-hom equiv4 = pullback-invariant-equiv diag-hom τdiag-hom (τ-extend-equiv n A E) (τ-extend-equiv n B E) (τ-extend-equiv n C E) p q equiv5 : pullback τdiag-hom ≃ τH.cocone E equiv5 = τH.pullback-equiv-cocone E -- We have defined the five equivalences, now we want to prove that the -- composite is what we want. We start by computing the composite of the -- equivalences 3, 4 and 5. map-543 : H.cocone E → τH.cocone E map-543 (a , b , e) = (τ-extend-nondep a , τ-extend-nondep b , τ-extend e) map-543-correct : (x : H.cocone E) → equiv5 ☆ (equiv4 ☆ (equiv3 ☆ x)) ≡ map-543 x map-543-correct (a , b , h) = ap (λ u → _ , _ , u) (funext (τ-extend (λ x → ap-concat (λ u → u (proj x)) (p a) (ap τ-extend-nondep (funext h) ∘ q b) ∘ (whisker-right _ (happly (happly-funext (p₀ a)) (proj x)) ∘ (ap-concat (λ u → u (proj x)) (ap τ-extend-nondep (funext h)) (q b) ∘ (whisker-right _ (compose-ap (λ u → u (proj x)) τ-extend-nondep (funext h)) ∘ (whisker-right _ (happly (happly-funext h) x) ∘ (whisker-left (h x) (happly (happly-funext (q₀ b)) (proj x)) ∘ refl-right-unit (h x))))))))) -- We now study the full composite map-54321 : (τ n (pushout d) → E) → τH.cocone E map-54321 = τH.compose-cocone-map _ _ cocone-τpushout map-21-A₀ : (f : τ n (pushout d) → E) (u : τ n A) → τH.A→top (map-543 (equiv2 ☆ (equiv1 ☆ f))) u ≡ τH.A→top (map-54321 f) u map-21-A₀ f = τ-extend (λ x → refl) map-21-A : (f : τ n (pushout d) → E) → τH.A→top (map-543 (equiv2 ☆ (equiv1 ☆ f))) ≡ τH.A→top (map-54321 f) map-21-A f = funext (map-21-A₀ f) map-21-B₀ : (f : τ n (pushout d) → E) (u : τ n B) → τH.B→top (map-543 (equiv2 ☆ (equiv1 ☆ f))) u ≡ τH.B→top (map-54321 f) u map-21-B₀ f = τ-extend (λ x → refl) map-21-B : (f : τ n (pushout d) → E) → τH.B→top (map-543 (equiv2 ☆ (equiv1 ☆ f))) ≡ τH.B→top (map-54321 f) map-21-B f = funext (map-21-B₀ f) map-21-correct : (h : τ n (pushout d) → E) → map-543 (equiv2 ☆ (equiv1 ☆ h)) ≡ map-54321 h map-21-correct h = τH.cocone-eq _ (map-21-A h) (map-21-B h) (τ-extend (λ x → whisker-right _ (happly (happly-funext (map-21-A₀ h)) (proj (f x))) ∘ (compose-ap h proj _ ∘ (! (refl-right-unit (ap (h ◯ proj) (glue x))) ∘ whisker-left (ap (h ◯ proj) (glue x)) (! (happly (happly-funext (map-21-B₀ h)) (proj (g x)))))))) map-54321-correct : (f : τ n (pushout d) → E) → equiv5 ☆ (equiv4 ☆ (equiv3 ☆ (equiv2 ☆ (equiv1 ☆ f)))) ≡ map-54321 f map-54321-correct f = map-543-correct (equiv2 ☆ (equiv1 ☆ f)) ∘ map-21-correct f map-54321-is-equiv : is-equiv map-54321 map-54321-is-equiv = transport is-equiv (funext map-54321-correct) (compose-is-equiv ((λ f₁ → equiv4 ☆ (equiv3 ☆ (equiv2 ☆ (equiv1 ☆ f₁)))) , compose-is-equiv ((λ f₁ → equiv3 ☆ (equiv2 ☆ (equiv1 ☆ f₁))) , compose-is-equiv ((λ f₁ → equiv2 ☆ (equiv1 ☆ f₁)) , compose-is-equiv equiv1 equiv2) equiv3) equiv4) equiv5) abstract τpushout-is-pushout : τH.is-pushout (τ n (pushout d)) cocone-τpushout τpushout-is-pushout E = map-54321-is-equiv E
module Control.Indexed import public Control.Functor.Indexed import public Control.Applicative.Indexed import public Control.Monad.Indexed import public Control.Monad.Indexed.Do
import algebra.ordered_ring import tactic --------------------- --------------------- --------------------- -- Ex 1 variables (α : Type) (p q : α → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (λ h, have h' : (∀ x : α, p x), from (assume y : α, (h y).1), have h'' : (∀ x : α, q x), from (assume y : α, (h y).2), and.intro h' h'') (λ h y, and.intro (h.1 y) (h.2 y)) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := (λ x y, assume s : α, ((x s) (y s))) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := (λ h, assume s:α, h.elim (λ h', or.inl (h' s)) (λ h', or.inr (h' s)) ) -- Ex 2 variable r : Prop example : α → ((∀ x : α, r) ↔ r) := (λ t, iff.intro (λ f, f t) (λ s _, s) ) section LEM open classical -- Need LEM for half of this example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro (by_cases (assume s : r, λ _, or.inr s) (assume s: ¬r, λ h, or.inl (assume z : α, (h z).elim (λ w, w) (λ h', absurd h' s) )) ) (λ h, assume y : α, h.elim (λ t, or.inl (t y)) (or.inr)) end LEM example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (λ h a, assume s : α, (h s a)) (λ h, assume s:α, λ t, (h t s)) -- Ex 3 variables (men : Type) (barber : men) variable (shaves : men → men → Prop) -- Used the solver because I already solved this essentially example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := have p: (shaves barber barber ↔ ¬shaves barber barber), from h barber, (not_iff_self (shaves barber barber)).mp (iff.symm (h barber)) -- Ex 4 namespace hidden def divides (m n : ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n : ℕ) : Prop := 2 ∣ n -- You can enter the '∣' character by typing \mid section variables m n : ℕ #check m ∣ n #check m^n #check even (m^n +3) end end hidden def prime (n : ℕ) : Prop := ∀ a b : ℕ, (hidden.divides n (a*b) → (hidden.divides n a ∨ hidden.divides n b)) def infinitely_many_primes : Prop := (∀ p : ℕ, (prime p) → (∃ m : ℕ, (p < m) ∧ prime m)) def Fermat_prime (n : ℕ) : Prop := ∃ k : ℕ, (n = 2^(2^k)) ∧ prime n def infinitely_many_Fermat_primes : Prop := (∀ p : ℕ, (Fermat_prime p) → (∃ m : ℕ, (p < m) ∧ Fermat_prime m)) def goldbach_conjecture : Prop := ∀ n : ℕ, (3 ≤ n) → (∃ p q :ℕ, (prime p) ∧ (prime q) ∧ (n = p + q)) def Goldbach's_weak_conjecture : Prop := ∀ k, (2≤ k) → (∃ p q r : ℕ, (prime p) ∧ (prime q) ∧ (prime r) ∧ (2*k+1=p+q+r)) def Fermat's_last_theorem : Prop := ∀ n : ℕ, 3 ≤ n → ¬∃ a b c :ℕ, a^n+b^n=c^n -- Ex 5 section EX5 open classical variable a : α example : (∃ x : α, r) → r := assume ⟨ x, hr ⟩, hr example : r → (∃ x : α, r) := λ h, exists.intro a h example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro (λ h, exists.elim h (λ a b, and.intro ⟨a, b.1⟩ b.2)) (λ h, exists.elim h.1 (λ b h', ⟨b,and.intro h' h.2⟩)) example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := sorry example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := sorry example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := sorry example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := sorry example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := sorry example : (∀ x, p x → r) ↔ (∃ x, p x) → r := sorry example : (∃ x, p x → r) ↔ (∀ x, p x) → r := sorry example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := sorry end EX5 -- Ex 6 variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := calc log (x * y) = log (exp (log x) * exp (log y)) : by rw [exp_log_eq hx, exp_log_eq hy] ... = log (exp (log x + log y)) : by rw [exp_add (log x) (log y)] ... = log x + log y : by rw [log_exp_eq] -- Ex 7 #check sub_self example (x : ℤ) : x * 0 = 0 := calc x * 0 = x * (1 - 1) : by rw sub_self ... = x * 1 - x * 1 : by rw mul_sub ... = x - x : by rw mul_one ... = 0 : by rw sub_self
clear; gcp; % start a local cluster filename = 'demoSue2x.tif'; if ~exist(filename,'file'); url = 'https://www.dropbox.com/s/36xdfd28eone0hj/demoSue2x.tif?dl=1'; fprintf('downloading the file...'); outfilename = websave(filename,url); fprintf('done. \n'); end addpath(genpath('../../../ca_source_extraction-master')); % add packages to matlab path addpath(genpath('../../../NoRMCorre-master')); addpath(genpath('../../../ca_source_extraction')); % add packages to matlab path addpath(genpath('../../../NoRMCorre')); %% read file and determine dynamic range Y = read_file(filename); [d1,d2,T] = size(Y); % dimensions of file Y = Y - min(Y(:)); % remove negative offset minY = quantile(Y(1:1e7),0.0005); maxY = quantile(Y(1:1e7),1-0.0005); %% view data figure;play_movie({Y},{'raw data'},minY,maxY); %% perform motion correction (start with rigid) % parameters motion correction % 'd1','d2': size of FOV % 'bin_width': how often to update the template % 'max_shift': maximum allowed rigid shift options_rg = NoRMCorreSetParms('d1',size(Y,1),'d2',size(Y,2),'bin_width',100,'max_shift',15); [M_rg,shifts_rg,template_rg] = normcorre_batch(Y,options_rg); %% view data tsub = 5; % downsampling factor (only for display purposes) Y_sub = downsample_data(Y,'time',tsub); M_rgs = downsample_data(M_rg,'time',tsub); play_movie({Y_sub,M_rgs},{'raw data','rigid'},minY,maxY); %% perform non-rigid motion correction % parameters motion correction % 'd1','d2': size FOV movie % 'grid_size','overlap_pre': parameters regulating size of patch (size patch ~ (grid_size + 2*overlap_pre)) % 'mot_uf': upsampling factor of the grid for shift application % 'bin_width': how often to update the template % 'max_shift': maximum allowed rigid shift % 'max_dev': maximum deviation allowed for each patch from the rigid shift value options_nr = NoRMCorreSetParms('d1',size(Y,1),'d2',size(Y,2),... 'grid_size',[48,48],'mot_uf',4,'overlap_pre',[16,16],... 'bin_width',100,'max_shift',15,'max_dev',8); [M_nr,shifts_nr,template_nr] = normcorre_batch(Y,options_nr,template_rg); %% view (downsampled) data M_nrs = downsample_data(M_nr,'time',tsub); play_movie({Y_sub,M_rgs,M_nrs},{'raw data','rigid','pw-rigid'},minY,maxY); %% compute some metrics for motion correction quality assessment [cY,mY,vY] = motion_metrics(Y,options_rg.max_shift); [cM_rg,mM_rg,vM_rg] = motion_metrics(M_rg,options_rg.max_shift); [cM_nr,mM_nr,vM_nr] = motion_metrics(M_nr,options_rg.max_shift); %% plot shifts shifts_r = squeeze(cat(3,shifts_rg(:).shifts)); shifts_n = cat(ndims(shifts_nr(1).shifts)+1,shifts_nr(:).shifts); shifts_n = reshape(shifts_n,[],ndims(Y)-1,T); shifts_x = squeeze(shifts_n(:,2,:))'; shifts_y = squeeze(shifts_n(:,1,:))'; patch_id = 1:size(shifts_x,2); str = strtrim(cellstr(int2str(patch_id.'))); str = cellfun(@(x) ['patch # ',x],str,'un',0); figure; ax1 = subplot(311); plot(1:T,cY,1:T,cM_rg,1:T,cM_nr); legend('raw data','rigid','non-rigid'); title('correlation coefficients','fontsize',14,'fontweight','bold') set(gca,'Xtick',[]) ax2 = subplot(312); plot(shifts_x); hold on; plot(shifts_r(:,2),'--k','linewidth',2); title('displacements along x','fontsize',14,'fontweight','bold') set(gca,'Xtick',[]) ax3 = subplot(313); plot(shifts_y); hold on; plot(shifts_r(:,1),'--k','linewidth',2); title('displacements along y','fontsize',14,'fontweight','bold') xlabel('timestep','fontsize',14,'fontweight','bold') linkaxes([ax1,ax2,ax3],'x') %% plot metrics figure; ax(1) = subplot(2,3,1); imagesc(mY,[minY,maxY]); axis equal; axis tight; axis off; title('mean raw data','fontsize',14,'fontweight','bold') ax(2) = subplot(2,3,2); imagesc(mM_rg,[minY,maxY]); axis equal; axis tight; axis off; title('mean rigid corrected','fontsize',14,'fontweight','bold') ax(3) = subplot(2,3,3); imagesc(mM_nr,[minY,maxY]); axis equal; axis tight; axis off; title('mean non-rigid corrected','fontsize',14,'fontweight','bold') subplot(2,3,4); plot(1:T,cY,1:T,cM_rg,1:T,cM_nr); legend('raw data','rigid','non-rigid'); title('correlation coefficients','fontsize',14,'fontweight','bold') subplot(2,3,5); scatter(cY,cM_rg); hold on; plot([0.9*min(cY),1.05*max(cM_rg)],[0.9*min(cY),1.05*max(cM_rg)],'--r'); axis square; xlabel('raw data','fontsize',14,'fontweight','bold'); ylabel('rigid corrected','fontsize',14,'fontweight','bold'); subplot(2,3,6); scatter(cM_rg,cM_nr); hold on; plot([0.95*min(cM_rg),1.05*max(cM_nr)],[0.95*min(cM_rg),1.05*max(cM_nr)],'--r'); axis square; xlabel('rigid corrected','fontsize',14,'fontweight','bold'); ylabel('non-rigid corrected','fontsize',14,'fontweight','bold'); linkaxes(ax,'xy') %% now perform source extraction by splitting the FOV in patches sizY = size(M_nr); patch_size = [30,30]; % size of each patch along each dimension (optional, default: [32,32]) overlap = [8,8]; % amount of overlap in each dimension (optional, default: [4,4]) patches = construct_patches(sizY(1:end-1),patch_size,overlap); K = 4; % number of components to be found tau = 4; % std of gaussian kernel (half size of neuron) p = 0; % order of autoregressive system (p = 0 no dynamics, p=1 just decay, p = 2, both rise and decay) options = CNMFSetParms(... 'd1',sizY(1),'d2',sizY(2),... 'temporal_iter',2,... % number of block-coordinate descent steps 'ssub',1,... % downsample in space 'tsub',2,... % downsample in time 'merge_thr',0.8,... % merging threshold 'gSig',tau,... 'gnb',2,... % number of background components 'spatial_method','regularized'... ); %% run CNMF algorithm on patches and combine tic; [A,b,C,f,S,P,RESULTS,YrA] = run_CNMF_patches(M_nr,K,patches,tau,p,options); [ROIvars.rval_space,ROIvars.rval_time,ROIvars.max_pr,ROIvars.sizeA,keep] = classify_components(M_nr,A,C,b,f,YrA,options); toc %% a simple GUI Cn = correlation_image_max(M_nr); Coor = plot_contours(A,Cn,options,1); close; run_GUI = false; if run_GUI GUIout = ROI_GUI(A,options,Cn,Coor,keep,ROIvars); options = GUIout{2}; keep = GUIout{3}; end %% view contour plots of selected and rejected components (optional) throw = ~keep; figure; ax1 = subplot(121); plot_contours(A(:,keep),Cn,options,0,[],Coor,1,find(keep)); title('Selected components','fontweight','bold','fontsize',14); ax2 = subplot(122); plot_contours(A(:,throw),Cn,options,0,[],Coor,1,find(throw));title('Rejected components','fontweight','bold','fontsize',14); linkaxes([ax1,ax2],'xy') %% inspect components plot_components_GUI(M_nr,A(:,keep),C(keep,:),b,f,Cn,options); %% refine temporal components A_keep = A(:,keep); C_keep = C(keep,:); P.p = 0; [C2,f2,P2,S2,YrA2] = update_temporal_components(reshape(M_nr,[],T),A_keep,b,C_keep,f,P,options); %% detrend fluorescence and extract DF/F values options.df_window = 1000; [F_dff,F0] = detrend_df_f(A_keep,b,C2,f2,YrA2,options); %% deconvolve data nNeurons = size(F_dff,1); C_dec = zeros(size(F_dff)); S = zeros(size(F_dff)); kernels = cell(nNeurons,1); min_sp = 3; % find spikes resulting in transients above min_sp x noise level for i = 1:nNeurons [C_dec(i,:),S(i,:),kernels{i}] = deconvCa(F_dff(i,:), [], min_sp, true, false, [], 20, [], 0); end %% plot a random component i = randi(nNeurons); figure;plot(1:T,F_dff(i,:),'--k'); hold all; plot(1:T,C_dec(i,:),'r','linewidth',2); spt = find(S(i,:)); if spt(1) == 1; spt(1) = []; end hold on; scatter(spt,repmat(-0.25,1,length(spt)),'m*') title(['Component ',num2str(i)]); legend('Fluorescence DF/F','Deconvolved','Spikes')
lemma tendsto_at_topI_sequentially: fixes f :: "real \<Rightarrow> 'b::first_countable_topology" assumes *: "\<And>X. filterlim X at_top sequentially \<Longrightarrow> (\<lambda>n. f (X n)) \<longlonglongrightarrow> y" shows "(f \<longlongrightarrow> y) at_top"
[STATEMENT] lemma refs_of_Node[simp]: "refs_of h (Node x ps) xs = (\<exists>prs. xs = ps # prs \<and> refs_of h (Ref.get h ps) prs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. refs_of h (Node x ps) xs = (\<exists>prs. xs = ps # prs \<and> refs_of h (Ref.get h ps) prs) [PROOF STEP] by (cases xs, auto)
[STATEMENT] lemma match_matches: "match t u = Some env \<Longrightarrow> linear t \<Longrightarrow> t \<lesssim> u" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>match t u = Some env; linear t\<rbrakk> \<Longrightarrow> t \<lesssim> u [PROOF STEP] by (metis match_subst_some linear_implies_no_abs convert_term_id matchesI)
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Categories.Limits.Terminal where open import Cubical.Foundations.Prelude open import Cubical.Data.Sigma -- open import Cubical.Categories.Limits.Base open import Cubical.Categories.Category open import Cubical.Categories.Functor private variable ℓ ℓ' : Level module _ (C : Precategory ℓ ℓ') where open Precategory C isInitial : (x : ob) → Type (ℓ-max ℓ ℓ') isInitial x = ∀ (y : ob) → isContr (C [ x , y ]) isFinal : (x : ob) → Type (ℓ-max ℓ ℓ') isFinal x = ∀ (y : ob) → isContr (C [ y , x ]) hasFinalOb : Type (ℓ-max ℓ ℓ') hasFinalOb = Σ[ x ∈ ob ] isFinal x
Formal statement is: proposition distr_distr: "g \<in> measurable N L \<Longrightarrow> f \<in> measurable M N \<Longrightarrow> distr (distr M N f) L g = distr M L (g \<circ> f)" Informal statement is: If $f$ is a measurable function from $M$ to $N$ and $g$ is a measurable function from $N$ to $L$, then the composition $g \circ f$ is a measurable function from $M$ to $L$.
[STATEMENT] lemma psi_lR_is_beta: "psi_l R = \<beta>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. psi_l R = \<beta> [PROOF STEP] unfolding psi_l_def alpha_l_def beta_l_def R_and_a_half_\<theta> [PROOF STATE] proof (prove) goal (1 subgoal): 1. complex_of_real (cos (pi / 2)) \<cdot>\<^sub>v \<alpha> + complex_of_real (sin (pi / 2)) \<cdot>\<^sub>v \<beta> = \<beta> [PROOF STEP] by auto
\chapter{Input and Output Data} \label{chap:inputoutput} The script requires the following input data and folders: \begin{description} \item[configuration file] Excel file with configuration data for the graphing utility. \item[./assets] This folder houses the \ac{css} file used to format the contents of the graphing utility (by default, Dash is un-styled). It contains customized, global properties for how to display the \ac{HTML} elements. \ac{css} files can define the size, colour, font, line spacing, indentation, borders, and location of \ac{HTML} elements. An adapted style file from \url{https://codepen.io/chriddyp/pen/bWLwgP} is used. \item[./icons] The icons of the various licenses of modules used are stored in this folder. \item[./data] Optional data folder. The configuration file can be set up to read from several data files. This folder is used to store the demonstration test set of data files. \end{description} The \textbf{graphs} folder is created by the application, if it does not exist. Interactive \ac{HTML} output graphs from the graphing utility are stored in this folder. Clicking on file, the graph in opened in a browser and full interactive Plotly functionality is available.
[STATEMENT] lemma [code]: "toy_class_raw.make = co4 (\<lambda>f. f ()) toy_class_raw_ext" [PROOF STATE] proof (prove) goal (1 subgoal): 1. toy_class_raw.make = co4 (\<lambda>f. f ()) toy_class_raw_ext [PROOF STEP] by(intro ext, simp add: toy_class_raw.make_def co4_def)
Formal statement is: proposition path_connected_convex_diff_countable: fixes U :: "'a::euclidean_space set" assumes "convex U" "\<not> collinear U" "countable S" shows "path_connected(U - S)" Informal statement is: If $U$ is a convex set in $\mathbb{R}^n$ that is not contained in a line, and $S$ is a countable set, then $U - S$ is path-connected.
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) (* prefix: mgga_x_m06l_params *params; assert(p->params != NULL); params = (mgga_x_m06l_params * )(p->params); *) $define gga_x_pbe_params $include "gga_x_pbe.mpl" $include "gvt4.mpl" m06_alpha := 0.00186726: m06_coeff_d := params_a_d: (* there is a factor if 2 in the definition of z, as in Theor. Chem. Account 120, 215 (2008) *) (* A MINUS was missing in Eq. (7) of the paper *) m06_f := (x, u, t) -> + pbe_f(x)*mgga_series_w(params_a_a, 12, t) + gtv4(m06_alpha, m06_coeff_d, x, 2*(t - K_FACTOR_C)): f := (rs, z, xt, xs0, xs1, u0, u1, t0, t1) -> mgga_exchange(m06_f, rs, z, xs0, xs1, u0, u1, t0, t1):
source('ifm_func.r') # Strategy E - trend trading: # Moving Average Convergence Divergence (MACD) is used in the strategy, which is # calculated by subtracting the 90-day simple moving average (SMA) of closing p- # rice of the given stock from the 65-day counterpart. The MACD's signal line is # the 21-day SMA of itself. When the MACD crosses above its signal line (golden # cross), we buy in at opening price on the next day, and then hold to sell out # at opening price on the following day when the MACD crosses below its signal # line(death cross). strategy <- function(stock) { # Strategy. MA_TYPE <- 'SMA' SIGNAL_DAYS_N <- 21 LMA_DAYS_N <- 90 SMA_DAYS_N <- 65 M_START <- LMA_DAYS_N + SIGNAL_DAYS_N # Prepare data. opp <- Op(stock) # [op]en [p]rices clp <- Cl(stock) # [cl]ose [p]rices macd <- MACD(clp, nFast=SMA_DAYS_N, nSlow=LMA_DAYS_N, nSig=SIGNAL_DAYS_N, maType=MA_TYPE) # [m]oving [a]verage [c]onvergence [d]ivergence decision <- macd[, 'macd'] - macd[, 'signal'] yesterday <- nrow(stock) - 1 # Execute the strategy. pl <- setNames( rep( 0, length(clp) ), time(stock) ) is_bought <- FALSE for (m in M_START:yesterday) { if ( !is_bought && as.numeric( decision[m-1] ) < 0 && as.numeric( decision[m] ) >= 0 ) { bought <- long( as.numeric( opp[m+1] ) ) is_bought <- TRUE } else if ( is_bought && as.numeric( decision[m-1] ) > 0 && as.numeric( decision[m] ) <= 0 ) { pl[m] <- -bought + short( as.numeric( opp[m+1] ) ) is_bought <- FALSE } } # Return [p]rofit-[l]oss. return(pl) }
Im done with school...yay! I have to be an adult now...boo! And although I might be going up the Yolo Causeway...Ill still be addicted to the Wiki. Things to do before I leave Davis (in no particular order): Buy a Farmers Market tshirt or tote bag Perform well at Trivia Night Eat at Thai Nakorn to have eaten at ALL of the Thai Restaurants in Davis Have a midnight rendezvous in the Arboretum (oh stop thinking dirrrty) Go to the Dominoes one last time Play in the Big Kids Park one last time Play sloshball Stargazing on the roof Buy lamb from the Meat Lab One last dance to Cold Shot ...and Im sure there are more things to add. 063006 23:59:59 Karla, I havent began my time at Davis yet, but I too am addicted to DavisWiki and check it many times throughout the day. So now, when you next check it...youll get to see that your OWN page has received a hit :) Users/BobbyGray I leave that comment just as you remove the part about being addicted from your page....well anyway, good luck with your todo list. Users/BobbyGray
using ElectronDisplay using Electron using VegaLite using DataFrames using Test @testset "ElectronDisplay" begin p1 = DataFrame(x=rand(10),y=rand(10)) |> @vlplot(:point, x=:x, y=:y) f = display(p1) @test f isa Electron.Window end
(* Title: HOL/Auth/n_german_lemma_on_inv__48.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_german Protocol Case Study*} theory n_german_lemma_on_inv__48 imports n_german_base begin section{*All lemmas on causal relation between inv__48 and some rule r*} lemma n_RecvReqVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReq N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReq N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv3) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv3) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv3) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvEVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvE i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvE i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvSVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvS i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvS i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Ident ''CurCmd'')) (Const ReqS)) (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv3) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__48: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__48: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqESVsinv__48: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqES i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntSVsinv__48: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntS i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntEVsinv__48: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntE i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__48: assumes a1: "\<exists> j. j\<le>N\<and>r=n_SendReqS j" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqEIVsinv__48: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqEI i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__48 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
[STATEMENT] lemma "dom B_host_attributes \<subseteq> set (nodesL policy)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dom B_host_attributes \<subseteq> set (nodesL policy) [PROOF STEP] by(simp add: B_host_attributes_def policy_def)
module Productivity (char : Set) where open import Common.Coinduction infix 50 _⋆ _+ infixl 40 _⊛_ infixl 30 _∣_ data P : Set where ε : P sym : char -> P _⊛_ : ∞ P -> ∞ P -> P _∣_ : ∞ P -> ∞ P -> P mutual _⋆ : P -> P p ⋆ = ♯ ε ∣ ♯ (p +) _+ : P -> P p + = ♯ p ⊛ ♯ (p ⋆) _sepBy_ : P -> P -> P p sepBy sep = ♯ p ⊛ ♯ ((♯ sep ⊛ ♯ p) ⋆) postulate addOp : P mulOp : P number : P openP : char closeP : char -- Not guarded: mutual expr = term sepBy addOp term = factor sepBy mulOp factor = ♯ number ∣ ♯ (♯ (♯ sym openP ⊛ ♯ expr) ⊛ ♯ sym closeP) -- Guarded and incomprehensible: mutual expr₁ = ♯ term₁ ⊛ ♯ expr₂ expr₂ = ♯ ε ∣ ♯ expr₃ expr₃ = ♯ (♯ addOp ⊛ ♯ term₁) ⊛ ♯ expr₂ term₁ = ♯ factor₁ ⊛ ♯ term₂ term₂ = ♯ ε ∣ ♯ term₃ term₃ = ♯ (♯ mulOp ⊛ ♯ factor₁) ⊛ ♯ term₂ factor₁ = ♯ number ∣ ♯ (♯ (♯ sym openP ⊛ ♯ expr₁) ⊛ ♯ sym closeP)
(* SolidityVar is the module that immitates variable data structure and provides all the means to operate with it. *) Module SolidityVar. Definition address := nat. Definition eqb_address (x y : address) : bool := if x =? y then true else false. Inductive var_type := | VTbool | VTint | VTaddress. Definition get_type (v : var_type) : Type := match v with | VTbool => bool | VTint => nat | VTaddress => address end. Record var := build_var { v_type : var_type; v_value : get_type v_type; }. End SolidityVar.
The imaginary part of a complex number is continuous.
The imaginary part of a complex number is continuous.
The imaginary part of a complex number is continuous.
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import algebra.order.smul import data.complex.basic import data.fin.vec_notation import field_theory.tower /-! # Complex number as a vector space over `ℝ` This file contains the following instances: * Any `•`-structure (`has_scalar`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on `ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ` algebra. * any complex vector space is a real vector space; * any finite dimensional complex vector space is a finite dimensional real vector space; * the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex vector space. It also defines bundled versions of four standard maps (respectively, the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate): * `complex.re_lm` (`ℝ`-linear map); * `complex.im_lm` (`ℝ`-linear map); * `complex.of_real_am` (`ℝ`-algebra (homo)morphism); * `complex.conj_ae` (`ℝ`-algebra equivalence). It also provides a universal property of the complex numbers `complex.lift`, which constructs a `ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`. -/ namespace complex open_locale complex_conjugate variables {R : Type*} {S : Type*} section variables [has_scalar R ℝ] /- The useless `0` multiplication in `smul` is to make sure that `restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/ instance : has_scalar R ℂ := { smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ } lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)] lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)] @[simp] lemma real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl end instance [has_scalar R ℝ] [has_scalar S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ := { smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] } instance [has_scalar R S] [has_scalar R ℝ] [has_scalar S ℝ] [is_scalar_tower R S ℝ] : is_scalar_tower R S ℂ := { smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] } instance [monoid R] [mul_action R ℝ] : mul_action R ℂ := { one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul], mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] } instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ := { smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add], smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] } instance [semiring R] [module R ℝ] : module R ℂ := { add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul], zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] } instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ := { smul := (•), smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def], commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes], ..complex.of_real.comp (algebra_map R ℝ) } @[simp] lemma coe_algebra_map : (algebra_map ℝ ℂ : ℝ → ℂ) = coe := rfl section variables {A : Type*} [semiring A] [algebra ℝ A] /-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from `alg_hom.commutes`. -/ @[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) : f x = algebra_map ℝ A x := f.commutes x /-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/ @[ext] lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g := begin ext ⟨x, y⟩, simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h] end end section open_locale complex_order protected lemma ordered_smul : ordered_smul ℝ ℂ := ordered_smul.mk' $ λ a b r hab hr, ⟨by simp [hr, hab.1.le], by simp [hab.2]⟩ localized "attribute [instance] complex.ordered_smul" in complex_order end open submodule finite_dimensional /-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/ noncomputable def basis_one_I : basis (fin 2) ℝ ℂ := basis.of_equiv_fun { to_fun := λ z, ![z.re, z.im], inv_fun := λ c, c 0 + c 1 • I, left_inv := λ z, by simp, right_inv := λ c, by { ext i, fin_cases i; simp }, map_add' := λ z z', by simp, map_smul' := λ c z, by simp } @[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl @[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] := funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j, by fin_cases i; fin_cases j; simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne, matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons, nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff, one_re, one_im, I_re, I_im] instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I @[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 := by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin] @[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 := by simp [← finrank_eq_dim, finrank_real_complex] lemma {u} dim_real_complex' : cardinal.lift.{u} (module.rank ℝ ℂ) = 2 := by simp [← finrank_eq_dim, finrank_real_complex, bit0] /-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the circle. -/ lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩ end complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ @[priority 900] instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E := restrict_scalars.module ℝ ℂ E instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] : is_scalar_tower ℝ ℂ E := restrict_scalars.is_scalar_tower ℝ ℂ E @[simp, norm_cast] lemma complex.coe_smul {E : Type*} [add_comm_group E] [module ℂ E] (x : ℝ) (y : E) : (x : ℂ) • y = x • y := rfl @[priority 100] instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] [finite_dimensional ℂ E] : finite_dimensional ℝ E := finite_dimensional.trans ℝ ℂ E lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : module.rank ℝ E = 2 * module.rank ℂ E := cardinal.lift_inj.1 $ by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] } lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E := by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex] namespace complex open_locale complex_conjugate /-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.re, map_add' := add_re, map_smul' := by simp, } @[simp] lemma re_lm_coe : ⇑re_lm = re := rfl /-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/ def im_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.im, map_add' := add_im, map_smul' := by simp, } @[simp] lemma im_lm_coe : ⇑im_lm = im := rfl /-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ @[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl /-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/ def conj_ae : ℂ ≃ₐ[ℝ] ℂ := { inv_fun := conj, left_inv := star_star, right_inv := star_star, commutes' := conj_of_real, .. conj } @[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl section lift variables {A : Type*} [ring A] [algebra ℝ A] /-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`. See `complex.lift` for this as an equiv. -/ def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A := alg_hom.of_linear_map ((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm) (show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1, by rw [ring_hom.map_one, zero_smul, add_zero]) (λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I' = (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'), begin rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm], congr' 1, -- equate "real" and "imaginary" parts { rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg, ←ring_hom.map_mul, ←ring_hom.map_sub], }, { rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂, ←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] } end) @[simp] lemma lift_aux_apply (I' : A) (hI') (z : ℂ) : lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp /-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element of `A` which squares to `-1`. This can be used to embed the complex numbers in the `quaternion`s. This isomorphism is named to match the very similar `zsqrtd.lift`. -/ @[simps {simp_rhs := tt}] def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) := { to_fun := λ I', lift_aux I' I'.prop, inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩, left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop, right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, } /- When applied to `complex.I` itself, `lift` is the identity. -/ @[simp] lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ := alg_hom_ext $ lift_aux_apply_I _ _ /- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/ @[simp] end lift end complex
-- exercises in "Type-Driven Development with Idris" -- chapter 7 -- check that all functions are total %default total -- -- section 7.1 -- see Shape.idr -- -- -- section 7.2 -- see Expr.idr -- -- -- section 7.3 -- see Expr.idr -- -- we define Vect by hand because Eq and Foldable already exist for Data.Vect data Vect : (size : Nat) -> (ty : Type) -> Type where Nil : Vect Z ty (::) : (x : ty) -> (xs : Vect size ty) -> Vect (S size) ty Eq ty => Eq (Vect n ty) where (==) [] [] = True (==) (x :: xs) (y :: ys) = (x == y) && xs == ys (==) _ _ = False Foldable (Vect n) where foldr func init [] = init foldr func init (x :: xs) = func x (foldr func init xs)
(* Title: HOL/Library/Function_Division.thy Author: Florian Haftmann, TUM *) section \<open>Pointwise instantiation of functions to division\<close> theory Function_Division imports Function_Algebras begin subsection \<open>Syntactic with division\<close> instantiation "fun" :: (type, inverse) inverse begin definition "inverse f = inverse \<circ> f" definition "f div g = (\<lambda>x. f x / g x)" instance .. end lemma inverse_fun_apply [simp]: "inverse f x = inverse (f x)" by (simp add: inverse_fun_def) lemma divide_fun_apply [simp]: "(f / g) x = f x / g x" by (simp add: divide_fun_def) text \<open> Unfortunately, we cannot lift this operations to algebraic type classes for division: being different from the constant zero function \<^term>\<open>f \<noteq> 0\<close> is too weak as precondition. So we must introduce our own set of lemmas. \<close> abbreviation zero_free :: "('b \<Rightarrow> 'a::field) \<Rightarrow> bool" where "zero_free f \<equiv> \<not> (\<exists>x. f x = 0)" lemma fun_left_inverse: fixes f :: "'b \<Rightarrow> 'a::field" shows "zero_free f \<Longrightarrow> inverse f * f = 1" by (simp add: fun_eq_iff) lemma fun_right_inverse: fixes f :: "'b \<Rightarrow> 'a::field" shows "zero_free f \<Longrightarrow> f * inverse f = 1" by (simp add: fun_eq_iff) lemma fun_divide_inverse: fixes f g :: "'b \<Rightarrow> 'a::field" shows "f / g = f * inverse g" by (simp add: fun_eq_iff divide_inverse) text \<open>Feel free to extend this.\<close> text \<open> Another possibility would be a reformulation of the division type classes to user a \<^term>\<open>zero_free\<close> predicate rather than a direct \<^term>\<open>a \<noteq> 0\<close> condition. \<close> end
Require Import Coq.Logic.FunctionalExtensionality. Require Import Coq.Logic.PropExtensionality. Require Import riscv.Utility.Monads. Module free. Section WithInterface. Context {action : Type} {result : action -> Type}. Inductive free {T : Type} : Type := | act (a : action) (_ : result a -> free) | ret (x : T). Arguments free : clear implicits. Fixpoint bind {A B} (mx : free A) (fy : A -> free B) : free B := match mx with | act a k => act a (fun x => bind (k x) fy) | ret x => fy x end. (** Monad laws *) Definition bind_ret_l {A B} a b : @bind A B (ret a) b = b a := eq_refl. Lemma bind_assoc {A B C} (a : free A) (b : A -> free B) (c : B -> free C) : bind (bind a b) c = bind a (fun x => bind (b x) c). Proof. revert c; revert C; revert b; revert B; induction a; cbn [bind]; eauto using f_equal, functional_extensionality. Qed. Lemma bind_ret_r {A} (a : free A) : bind a ret = a. Proof. induction a; cbn [bind]; eauto using f_equal, functional_extensionality. Qed. Global Instance Monad_free : Monad free. Proof. esplit; eauto using bind_ret_l, bind_assoc, bind_ret_r. Defined. Section WithState. Context {state} (interp_action : forall a : action, state -> (result a -> state -> Prop) -> Prop). Section WithOutput. Context {output} (post : output -> state -> Prop). Definition interp_body interp (a : free output) (s : state) : Prop := match a with | ret x => post x s | act a k => interp_action a s (fun r => interp (k r)) end. Fixpoint interp_fix a := interp_body interp_fix a. End WithOutput. Definition interp {output} a s post := @interp_fix output post a s. Lemma interp_ret {T} (x : T) m P : interp (ret x) m P = P x m. Proof. exact eq_refl. Qed. Lemma interp_act {T} a (k : _ -> free T) s post : interp (act a k) s post = interp_action a s (fun r s => interp (k r) s post). Proof. exact eq_refl. Qed. Context (interp_action_weaken_post : forall a (post1 post2:_->_->Prop), (forall r s, post1 r s -> post2 r s) -> forall s, interp_action a s post1 -> interp_action a s post2). Lemma interp_weaken_post {T} (p : free T) s (post1 post2:_->_->Prop) (Hpost : forall r s, post1 r s -> post2 r s) (Hinterp : interp p s post1) : interp p s post2. Proof. revert dependent s; induction p; cbn; firstorder eauto. Qed. Lemma interp_bind {A B} s post (a : free A) (b : A -> free B) : interp (bind a b) s post <-> interp a s (fun x s => interp (b x) s post). Proof. revert post; revert b; revert B; revert s; induction a. 2: { intros. cbn. reflexivity. } split; eapply interp_action_weaken_post; intros; eapply H; eauto. Qed. Lemma interp_bind_ex_mid {A B} m0 post (a : free A) (b : A -> free B) : interp (bind a b) m0 post <-> (exists mid, interp a m0 mid /\ forall x m1, mid x m1 -> interp (b x) m1 post). Proof. rewrite interp_bind. split; [intros ? | intros (?&?&?)]. { exists (fun x m1 => interp (b x) m1 post); split; eauto. } { eauto using interp_weaken_post. } Qed. End WithState. Section WithStateAndAbort. Context {state : Type}. Context (interpret_action : forall a : action, state -> (* initial state *) (result a -> state -> Prop) -> (* postcondition if finished *) (state -> Prop) -> (* postcondition if aborted *) Prop). Section WithOutput. Context {output} (postF : output -> state -> Prop) (postA : state -> Prop). Definition interpret_body rec (a : free output) (s : state) : Prop := match a with | ret x => postF x s | act a k => interpret_action a s (fun r => rec (k r)) postA end. Fixpoint interpret_fix a := interpret_body interpret_fix a. End WithOutput. Definition interpret {output} a s postF postA := @interpret_fix output postF postA a s. Lemma interpret_ret {T} (x : T) m postF postA : interpret (ret x) m postF postA = postF x m. Proof. exact eq_refl. Qed. Lemma interpret_act {T} a (k : _ -> free T) s postF postA : interpret (act a k) s postF postA = interpret_action a s (fun r s => interpret (k r) s postF postA) postA. Proof. exact eq_refl. Qed. Context (interpret_action_weaken_post : forall a (postF1 postF2 : _ -> _ -> Prop) (postA1 postA2 : _ -> Prop), (forall r s, postF1 r s -> postF2 r s) -> (forall s, postA1 s -> postA2 s) -> forall s, interpret_action a s postF1 postA1 -> interpret_action a s postF2 postA2). Lemma interpret_weaken_post {T} (p : free T) s (postF1 postF2 : _ -> _ -> Prop) (postA1 postA2 : _ -> Prop): (forall r s, postF1 r s -> postF2 r s) -> (forall s, postA1 s -> postA2 s) -> interpret p s postF1 postA1 -> interpret p s postF2 postA2. Proof. revert dependent s; induction p. 2: firstorder eauto. cbn. intros. eapply interpret_action_weaken_post. - intros. eapply H; try eassumption. exact H3. - eassumption. - eassumption. Qed. Lemma interpret_bind {A B} s postF postA (a : free A) (b : A -> free B) : interpret (bind a b) s postF postA <-> interpret a s (fun x s => interpret (b x) s postF postA) postA. Proof. revert postF; revert postA; revert b; revert B; revert s; induction a. 2: { intros. cbn. reflexivity. } split; intros; eapply interpret_action_weaken_post; intros. - eapply H. exact H1. - exact H1. - eauto. - eapply H. exact H1. - exact H1. - eauto. Qed. Lemma interpret_bind_ex_mid {A B} m0 postF postA (a : free A) (b : A -> free B) : interpret (bind a b) m0 postF postA <-> (exists mid, interpret a m0 mid postA /\ forall x m1, mid x m1 -> interpret (b x) m1 postF postA). Proof. rewrite interpret_bind. split; [intros ? | intros (?&?&?)]. { exists (fun x m1 => interpret (b x) m1 postF postA); split; eauto. } { eauto using interpret_weaken_post. } Qed. End WithStateAndAbort. End WithInterface. Global Arguments free : clear implicits. End free. Notation free := free.free.
C @(#)pfinit.f 20.6 11/12/98 subroutine pfinit C INITIALIZE POWERFLOW JOB VARIBLES C ( done only on job initialization ) include 'ipfinc/parametr.inc' include 'ipfinc/alpha.inc' include 'ipfinc/blank.inc' include 'ipfinc/basval.inc' include 'ipfinc/branch.inc' include 'ipfinc/epridc.inc' include 'ipfinc/filnam.inc' include 'ipfinc/jobctl.inc' include 'ipfinc/lfiles.inc' include 'ipfinc/mrgtxt.inc' include 'ipfinc/optim.inc' include 'ipfinc/pageno.inc' include 'ipfinc/prt.inc' include 'ipfinc/topbot.inc' include 'ipfinc/usranl.inc' include 'ipfinc/zonlst.inc' include 'ipfinc/wsccbase.inc' include 'ipfinc/miscfile.inc' include 'ipfinc/lndpcp.inc' c c*** now done with initialization routine C C Force linkage of Block Data modules C call init_bd_all C Logical file variables logmbs = 10 logmbr = 11 wscfil = 12 wscc_aname = ' ' wscc_bname = ' ' c c Caution: the following logical assignment must be coordinated c with initlz.f c inp = 13 lprt = 14 mfich = 15 datai = 16 obasnm = ' ' datao = 17 nbasnm = ' ' brndta = 18 brdnam = ' ' dbug = 19 busbrn = 20 bsbrnm = ' ' busfil = 21 bsdnam = ' ' chgdta = 22 chgnam = ' ' lun = 23 ! Used in analys for user_analysis svchfl = 24 lunusr = 25 ! Used in getusr for user_analysis lunscr = 27 ! Used in solton for best solution lunscr1 = 28 ! Used as a scratch file within a module lunscr2 = 29 ! Used as a scratch file within a module newchgfil = ' ' newnetfil = ' ' c c lun = 30 ! Reserved for scratch c lun = 40 ! Reserved for plotting c lun = 41 ! Reserved for plotting c lun = 42 ! Reserved for plotting arcvfile = 51 c c luns 56-65 ! reserved for command files c c Print file switches - 1 = on, 0 = off lprtsw = 1 fichsw = 0 crtsw = 1 if( batch ) crtsw = 0 c Set counters nocase = 0 nobus = 0 c Set pagination parameters.. pageno = -1 lineno = 0 maxlin = 59 fichpg = -1 fichln = 0 fichmx = 59 lstdnl = 0 lstdnf = 0 c Set up job variables bmva = 100.0 sang = 0.0 ksyuu = 0 yptr = 0 nbsmrg=0 nbrmrg=0 nifmrg=0 ntot_alf = 0 ntot = 0 ntot2 = 0 ltot = 0 ltot2 = 0 ntota = 0 ntotb = 0 ntotc = 0 numldc = 0 wsccflag = .false. do i = 1, MAXBUS wsccbase(i) = ' ' enddo c c Initialize EPRI RP1964 counters c nepbus = 0 nepctl = 0 mepbus = 0 mepctl = 0 ntotcs = 0 jtie = 0 nshift = 0 jphno = 0 kdtot = 0 kxtot = 0 nztot = 0 mtdcbs = 0 mtdcln = 0 nbslck = 0 kbsknt = 0 kbrknt = 0 natot = 0 nfzdta = 0 npzdta = 0 nfzout = 0 npzout = 0 nfzanl = 0 npzanl = 0 nfoanl = 0 npoanl = 0 leffan = 0 txefan = 0 lncnt1 = 0 lncnt2 = 0 lncnt3 = 0 lncnt4 = 0 lncnt5 = 0 lncnt6 = 0 do i = 1,40 if (i .ne. 33) kspare(i)= 0 cspare(i)= ' ' enddo numlrt = 0 C Don't save the Fiche file unless asked for... C with a [ FICHE,COPIES=n ] record... kspare(16) = -1 kchgsw = 1 call xdate(dte) cspare(31) = dte c c Initialize BASVAL() values c do i = 1, 9 basval(i) = ' ' enddo basval(5) = dte basval(8) = prgvsn return end
Require Import Iron.Language.SystemF.SubstTypeExp. Require Import Iron.Language.SystemF.SubstExpExp. Require Export Iron.Language.SystemF.Exp. (* Small step evaluation *) Inductive STEP : exp -> exp -> Prop := (* value applications *) | ESLamApp : forall t11 x12 v2 , value v2 -> STEP (XApp (XLam t11 x12) v2) (substXX 0 v2 x12) | ESApp1 : forall x1 x1' x2 , STEP x1 x1' -> STEP (XApp x1 x2) (XApp x1' x2) | ESApp2 : forall v1 x2 x2' , value v1 -> STEP x2 x2' -> STEP (XApp v1 x2) (XApp v1 x2') (* type applications *) | ESLAMAPP : forall x12 t2 , STEP (XAPP (XLAM x12) t2) (substTX 0 t2 x12) | ESAPP1 : forall x1 x1' t2 , STEP x1 x1' -> STEP (XAPP x1 t2) (XAPP x1' t2). Hint Constructors STEP. (********************************************************************) (* Multi-step evaluation. A sequence of small step transitions. As opposed to STEPSL, this version has an append constructor ESAppend that makes it easy to join two evaluations together. We use this when converting big-step evaluations to small-step. *) Inductive STEPS : exp -> exp -> Prop := (* After no steps, we get the same exp. We need this constructor to match the EVDone constructor in the big-step evaluation, so we can convert between big-step and multi-step evaluations. *) | ESNone : forall x1 , STEPS x1 x1 (* Take a single step. *) | ESStep : forall x1 x2 , STEP x1 x2 -> STEPS x1 x2 (* Combine two evaluations into a third. *) | ESAppend : forall x1 x2 x3 , STEPS x1 x2 -> STEPS x2 x3 -> STEPS x1 x3. Hint Constructors STEPS. (* Context lemmas These help when proving something about a reduction in a given context. They're all trivial. TODO: Define contexts directly like in the Simple proof. *) Lemma steps_app1 : forall x1 x1' x2 , STEPS x1 x1' -> STEPS (XApp x1 x2) (XApp x1' x2). Proof. intros. induction H; eauto. Qed. Hint Resolve steps_app1. Lemma steps_app2 : forall v1 x2 x2' , value v1 -> STEPS x2 x2' -> STEPS (XApp v1 x2) (XApp v1 x2'). Proof. intros. induction H0; eauto. Qed. Hint Resolve steps_app2. Lemma steps_APP1 : forall x1 x1' t2 , STEPS x1 x1' -> STEPS (XAPP x1 t2) (XAPP x1' t2). Proof. intros. induction H; eauto. Qed. (********************************************************************) (* Left linearised multi-step evaluation As opposed to STEPS, this version provides a single step at a time and does not have an append constructor. This is convenient when converting a small-step evaluations to big-step, via the eval_expansion lemma. *) Inductive STEPSL : exp -> exp -> Prop := | ESLNone : forall x1 , STEPSL x1 x1 | ESLCons : forall x1 x2 x3 , STEP x1 x2 -> STEPSL x2 x3 -> STEPSL x1 x3. Hint Constructors STEPSL. (* Transitivity of left linearised multi-step evaluation. We use this when "flattening" a big step evaluation to the small step one. *) Lemma stepsl_trans : forall x1 x2 x3 , STEPSL x1 x2 -> STEPSL x2 x3 -> STEPSL x1 x3. Proof. intros. induction H. eauto. eapply ESLCons. eauto. eauto. Qed. (* Linearise a regular multi-step evaluation. This flattens out all the append constructors, leaving us with a list of individual transitions. *) Lemma stepsl_of_steps : forall x1 x2 , STEPS x1 x2 -> STEPSL x1 x2. Proof. intros. induction H. auto. eauto. eapply stepsl_trans; eauto. Qed.
State Before: α : Type u_1 β : Type ?u.8207 γ : Type ?u.8210 r : α → α → Prop s t : Multiset α a✝ : α inst✝ : DecidableEq α a b : α l : Multiset α d : Nodup l ⊢ a ∈ Multiset.erase l b ↔ a ≠ b ∧ a ∈ l State After: no goals Tactic: rw [d.erase_eq_filter b, mem_filter, and_comm]
proposition fixes S :: "complex set" assumes "open S" shows simply_connected_eq_frontier_properties: "simply_connected S \<longleftrightarrow> connected S \<and> (if bounded S then connected(frontier S) else (\<forall>C \<in> components(frontier S). \<not>bounded C))" (is "?fp") and simply_connected_eq_unbounded_complement_components: "simply_connected S \<longleftrightarrow> connected S \<and> (\<forall>C \<in> components(- S). \<not>bounded C)" (is "?ucc") and simply_connected_eq_empty_inside: "simply_connected S \<longleftrightarrow> connected S \<and> inside S = {}" (is "?ei")
/- LoVe Homework 7: Metaprogramming -/ import .lovelib namespace LoVe open expr open tactic open declaration /- Question 1: A `safe` Tactic -/ /- We develop a tactic that applies all safe introduction and elimination rules for the connectives and quantifiers exhaustively. A rule is said to be _safe_ if it always gives rise to provable subgoals. In addition, we will require that safe rules do not introduce metavariables (which can easily be instantiated accidentally with the wrong terms.) We proceed in three steps. -/ /- 1.1. Develop a `safe_intros` tactic that applies the introduction rules for `true`, `¬`, `∧`, `↔`, and `→`/`∀`. The tactic generalizes `intro_ands` from the exercise. **Hint**: You can use `tactic.intro` or `tactic.intro1` for some of these. **Hint**: You can use the `<|>` operator between the rules/tactics for different symbols. -/ meta def safe_intros : tactic unit := sorry example {a b c d : Prop} : a → ¬ b ∧ (c ↔ d) := begin safe_intros, /- The proof state should be roughly as follows: a b c d : Prop, a_1 : a, a_2 : b ⊢ false a b c d : Prop, a_1 : a, a_2 : c ⊢ d a b c d : Prop, a_1 : a, a_2 : d ⊢ c -/ repeat { sorry } end /- 1.2. Develop a `safe_destructs` tactic that eliminates `false`, `∧`, `∨`, `↔`, and `∃`. The tactic generalizes `destruct_ands` from the exercise. -/ meta def safe_destructs : tactic unit := sorry example {a b c d e f : Prop} {p : ℕ → Prop} (hneg: ¬ a) (hand : a ∧ b ∧ c) (hor : c ∨ d) (himp : b → e) (hiff : e ↔ f) (hex : ∃x, p x) : false := begin safe_destructs, /- The proof state should be roughly as follows: 2 goals a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, hand_left : a, hor : d, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false -/ repeat { sorry } end /- 1.3. Implement a `safe` tactic that first performs introduction, then elimination, and finally proves all the subgoals that can be discharged directly by `assumption`. The tactic generalizes `destro_and` from the exercise. **Hint**: The `try` tactic combinator might be useful. -/ meta def safe : tactic unit := sorry example {a b c d e f : Prop} {p : ℕ → Prop} (hneg: ¬ a) (hand : a ∧ b ∧ c) (hor : c ∨ d) (himp : b → e) (hiff : e ↔ f) (hex : ∃x, p x) : a → ¬ b ∧ (c ↔ d) := begin safe, /- The proof state should be roughly as follows: 3 goals a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : b, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : b, hand_left : a, hor : d, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : c, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ d -/ repeat { sorry } end /- Question 2 **optional**: An `auto` Tactic -/ /- 2.1 **optional**. Develop an Isabelle-style `auto` tactic. This tactic would apply all safe introduction and elimination rules. In addition, it would try unsafe rules (such as `or.intro_left` and `false.elim`) but backtrack at some point (or try several possibilities in parallel). Iterative deepening may be a valid approach, or best-first search, or breadth-first search. The tactic should also attempt to apply assumptions whose conclusion matches the goal, but backtrack if necessary. See also "Automatic Proof and Disproof in Isabelle/HOL" (https://www.cs.vu.nl/~jbe248/frocos2011-dis-proof.pdf) by Blanchette, Bulwahn, and Nipkow, and the references they give. -/ /- 2.2 **optional**. Test your tactic on some benchmarks. You can try your tactic on logic puzzles of the kinds we proved in exercise 2 and homework 2. Please include these below. -/ end LoVe
{-# OPTIONS --safe --experimental-lossy-unification #-} module Cubical.Algebra.ZariskiLattice.Base where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.HLevels open import Cubical.Foundations.Transport import Cubical.Data.Empty as ⊥ open import Cubical.Data.Bool open import Cubical.Data.Nat renaming ( _+_ to _+ℕ_ ; _·_ to _·ℕ_ ; _^_ to _^ℕ_ ; +-comm to +ℕ-comm ; +-assoc to +ℕ-assoc ; ·-assoc to ·ℕ-assoc ; ·-comm to ·ℕ-comm ; ·-identityʳ to ·ℕ-rid) open import Cubical.Data.Sigma.Base open import Cubical.Data.Sigma.Properties open import Cubical.Data.FinData open import Cubical.Data.Unit open import Cubical.Relation.Nullary open import Cubical.Relation.Binary open import Cubical.Relation.Binary.Poset open import Cubical.Algebra.Ring open import Cubical.Algebra.Ring.Properties open import Cubical.Algebra.Ring.BigOps open import Cubical.Algebra.CommRing open import Cubical.Algebra.CommRing.BinomialThm open import Cubical.Algebra.CommRing.Ideal open import Cubical.Algebra.CommRing.FGIdeal open import Cubical.Algebra.CommRing.RadicalIdeal open import Cubical.Algebra.RingSolver.Reflection open import Cubical.Algebra.Semilattice open import Cubical.Algebra.Lattice open import Cubical.Algebra.DistLattice open import Cubical.Algebra.Matrix open import Cubical.HITs.SetQuotients as SQ open Iso open BinaryRelation open isEquivRel private variable ℓ ℓ' : Level module ZarLat (R' : CommRing ℓ) where open CommRingStr (snd R') open RingTheory (CommRing→Ring R') open Sum (CommRing→Ring R') open CommRingTheory R' open Exponentiation R' open BinomialThm R' open CommIdeal R' open RadicalIdeal R' open isCommIdeal open ProdFin R' private R = fst R' A = Σ[ n ∈ ℕ ] (FinVec R n) ⟨_⟩ : {n : ℕ} → FinVec R n → CommIdeal ⟨ V ⟩ = ⟨ V ⟩[ R' ] _∼_ : A → A → Type (ℓ-suc ℓ) (_ , α) ∼ (_ , β) = √ ⟨ α ⟩ ≡ √ ⟨ β ⟩ ∼EquivRel : isEquivRel (_∼_) reflexive ∼EquivRel _ = refl symmetric ∼EquivRel _ _ = sym transitive ∼EquivRel _ _ _ = _∙_ ZL : Type (ℓ-suc ℓ) ZL = A / _∼_ 0z : ZL 0z = [ 0 , (λ ()) ] 1z : ZL 1z = [ 1 , (replicateFinVec 1 1r) ] _∨z_ : ZL → ZL → ZL _∨z_ = setQuotSymmBinOp (reflexive ∼EquivRel) (transitive ∼EquivRel) (λ (_ , α) (_ , β) → (_ , α ++Fin β)) (λ (_ , α) (_ , β) → cong √ (FGIdealAddLemma _ α β ∙∙ +iComm _ _ ∙∙ sym (FGIdealAddLemma _ β α))) λ (_ , α) (_ , β) (_ , γ) α∼β → --need to show α∨γ ∼ β∨γ √ ⟨ α ++Fin γ ⟩ ≡⟨ cong √ (FGIdealAddLemma _ α γ) ⟩ √ (⟨ α ⟩ +i ⟨ γ ⟩) ≡⟨ sym (√+LContr _ _) ⟩ √ (√ ⟨ α ⟩ +i ⟨ γ ⟩) ≡⟨ cong (λ I → √ (I +i ⟨ γ ⟩)) α∼β ⟩ √ (√ ⟨ β ⟩ +i ⟨ γ ⟩) ≡⟨ √+LContr _ _ ⟩ √ (⟨ β ⟩ +i ⟨ γ ⟩) ≡⟨ cong √ (sym (FGIdealAddLemma _ β γ)) ⟩ √ ⟨ β ++Fin γ ⟩ ∎ _∧z_ : ZL → ZL → ZL _∧z_ = setQuotSymmBinOp (reflexive ∼EquivRel) (transitive ∼EquivRel) (λ (_ , α) (_ , β) → (_ , α ··Fin β)) (λ (_ , α) (_ , β) → cong √ (FGIdealMultLemma _ α β ∙∙ ·iComm _ _ ∙∙ sym (FGIdealMultLemma _ β α))) λ (_ , α) (_ , β) (_ , γ) α∼β → --need to show α∧γ ∼ β∧γ √ ⟨ α ··Fin γ ⟩ ≡⟨ cong √ (FGIdealMultLemma _ α γ) ⟩ √ (⟨ α ⟩ ·i ⟨ γ ⟩) ≡⟨ sym (√·LContr _ _) ⟩ √ (√ ⟨ α ⟩ ·i ⟨ γ ⟩) ≡⟨ cong (λ I → √ (I ·i ⟨ γ ⟩)) α∼β ⟩ √ (√ ⟨ β ⟩ ·i ⟨ γ ⟩) ≡⟨ √·LContr _ _ ⟩ √ (⟨ β ⟩ ·i ⟨ γ ⟩) ≡⟨ cong √ (sym (FGIdealMultLemma _ β γ)) ⟩ √ ⟨ β ··Fin γ ⟩ ∎ -- join axioms ∨zAssoc : ∀ (𝔞 𝔟 𝔠 : ZL) → 𝔞 ∨z (𝔟 ∨z 𝔠) ≡ (𝔞 ∨z 𝔟) ∨z 𝔠 ∨zAssoc = SQ.elimProp3 (λ _ _ _ → squash/ _ _) λ (_ , α) (_ , β) (_ , γ) → eq/ _ _ (cong √ (IdealAddAssoc _ _ _ _)) ∨zComm : ∀ (𝔞 𝔟 : ZL) → 𝔞 ∨z 𝔟 ≡ 𝔟 ∨z 𝔞 ∨zComm = SQ.elimProp2 (λ _ _ → squash/ _ _) λ (_ , α) (_ , β) → eq/ _ _ (cong √ (FGIdealAddLemma _ α β ∙∙ +iComm _ _ ∙∙ sym (FGIdealAddLemma _ β α))) ∨zLid : ∀ (𝔞 : ZL) → 0z ∨z 𝔞 ≡ 𝔞 ∨zLid = SQ.elimProp (λ _ → squash/ _ _) λ _ → eq/ _ _ refl ∨zRid : ∀ (𝔞 : ZL) → 𝔞 ∨z 0z ≡ 𝔞 ∨zRid _ = ∨zComm _ _ ∙ ∨zLid _ -- -- meet axioms ∧zAssoc : ∀ (𝔞 𝔟 𝔠 : ZL) → 𝔞 ∧z (𝔟 ∧z 𝔠) ≡ (𝔞 ∧z 𝔟) ∧z 𝔠 ∧zAssoc = SQ.elimProp3 (λ _ _ _ → squash/ _ _) λ (_ , α) (_ , β) (_ , γ) → eq/ _ _ (√ ⟨ α ··Fin (β ··Fin γ) ⟩ ≡⟨ cong √ (FGIdealMultLemma _ _ _) ⟩ √ (⟨ α ⟩ ·i ⟨ β ··Fin γ ⟩) ≡⟨ cong (λ x → √ (⟨ α ⟩ ·i x)) (FGIdealMultLemma _ _ _) ⟩ √ (⟨ α ⟩ ·i (⟨ β ⟩ ·i ⟨ γ ⟩)) ≡⟨ cong √ (·iAssoc _ _ _) ⟩ √ ((⟨ α ⟩ ·i ⟨ β ⟩) ·i ⟨ γ ⟩) ≡⟨ cong (λ x → √ (x ·i ⟨ γ ⟩)) (sym (FGIdealMultLemma _ _ _)) ⟩ √ (⟨ α ··Fin β ⟩ ·i ⟨ γ ⟩) ≡⟨ cong √ (sym (FGIdealMultLemma _ _ _)) ⟩ √ ⟨ (α ··Fin β) ··Fin γ ⟩ ∎) ∧zComm : ∀ (𝔞 𝔟 : ZL) → 𝔞 ∧z 𝔟 ≡ 𝔟 ∧z 𝔞 ∧zComm = SQ.elimProp2 (λ _ _ → squash/ _ _) λ (_ , α) (_ , β) → eq/ _ _ (cong √ (FGIdealMultLemma _ α β ∙∙ ·iComm _ _ ∙∙ sym (FGIdealMultLemma _ β α))) ∧zRid : ∀ (𝔞 : ZL) → 𝔞 ∧z 1z ≡ 𝔞 ∧zRid = SQ.elimProp (λ _ → squash/ _ _) λ (_ , α) → eq/ _ _ (cong √ (⟨ α ··Fin (replicateFinVec 1 1r) ⟩ ≡⟨ FGIdealMultLemma _ _ _ ⟩ ⟨ α ⟩ ·i ⟨ (replicateFinVec 1 1r) ⟩ ≡⟨ cong (⟨ α ⟩ ·i_) (contains1Is1 _ (indInIdeal _ _ zero)) ⟩ ⟨ α ⟩ ·i 1Ideal ≡⟨ ·iRid _ ⟩ ⟨ α ⟩ ∎)) -- absorption and distributivity ∧zAbsorb∨z : ∀ (𝔞 𝔟 : ZL) → 𝔞 ∧z (𝔞 ∨z 𝔟) ≡ 𝔞 ∧zAbsorb∨z = SQ.elimProp2 (λ _ _ → squash/ _ _) λ (_ , α) (_ , β) → eq/ _ _ (√ ⟨ α ··Fin (α ++Fin β) ⟩ ≡⟨ cong √ (FGIdealMultLemma _ α (α ++Fin β)) ⟩ √ (⟨ α ⟩ ·i ⟨ α ++Fin β ⟩) ≡⟨ cong (λ x → √ (⟨ α ⟩ ·i x)) (FGIdealAddLemma _ α β) ⟩ √ (⟨ α ⟩ ·i (⟨ α ⟩ +i ⟨ β ⟩)) ≡⟨ √·Absorb+ _ _ ⟩ √ ⟨ α ⟩ ∎) ∧zLDist∨z : ∀ (𝔞 𝔟 𝔠 : ZL) → 𝔞 ∧z (𝔟 ∨z 𝔠) ≡ (𝔞 ∧z 𝔟) ∨z (𝔞 ∧z 𝔠) ∧zLDist∨z = SQ.elimProp3 (λ _ _ _ → squash/ _ _) λ (_ , α) (_ , β) (_ , γ) → eq/ _ _ (√ ⟨ α ··Fin (β ++Fin γ) ⟩ ≡⟨ cong √ (FGIdealMultLemma _ _ _) ⟩ √ (⟨ α ⟩ ·i ⟨ β ++Fin γ ⟩) ≡⟨ cong (λ x → √ (⟨ α ⟩ ·i x)) (FGIdealAddLemma _ _ _) ⟩ √ (⟨ α ⟩ ·i (⟨ β ⟩ +i ⟨ γ ⟩)) ≡⟨ cong √ (·iRdist+i _ _ _) ⟩ -- L/R-dist are swapped -- in Lattices vs Rings √ (⟨ α ⟩ ·i ⟨ β ⟩ +i ⟨ α ⟩ ·i ⟨ γ ⟩) ≡⟨ cong₂ (λ x y → √ (x +i y)) (sym (FGIdealMultLemma _ _ _)) (sym (FGIdealMultLemma _ _ _)) ⟩ √ (⟨ α ··Fin β ⟩ +i ⟨ α ··Fin γ ⟩) ≡⟨ cong √ (sym (FGIdealAddLemma _ _ _)) ⟩ √ ⟨ (α ··Fin β) ++Fin (α ··Fin γ) ⟩ ∎) ZariskiLattice : DistLattice (ℓ-suc ℓ) fst ZariskiLattice = ZL DistLatticeStr.0l (snd ZariskiLattice) = 0z DistLatticeStr.1l (snd ZariskiLattice) = 1z DistLatticeStr._∨l_ (snd ZariskiLattice) = _∨z_ DistLatticeStr._∧l_ (snd ZariskiLattice) = _∧z_ DistLatticeStr.isDistLattice (snd ZariskiLattice) = makeIsDistLattice∧lOver∨l squash/ ∨zAssoc ∨zRid ∨zComm ∧zAssoc ∧zRid ∧zComm ∧zAbsorb∨z ∧zLDist∨z -- An equivalent definition that doesn't bump up the unviverse level module SmallZarLat (R' : CommRing ℓ) where open CommRingStr (snd R') open CommIdeal R' open RadicalIdeal R' open ZarLat R' open Iso private R = fst R' A = Σ[ n ∈ ℕ ] (FinVec R n) ⟨_⟩ : {n : ℕ} → FinVec R n → CommIdeal ⟨ V ⟩ = ⟨ V ⟩[ R' ] -- This is small! _≼_ : A → A → Type ℓ (_ , α) ≼ (_ , β) = ∀ i → α i ∈ √ ⟨ β ⟩ _∼'_ : A → A → Type ℓ α ∼' β = (α ≼ β) × (β ≼ α) -- lives in the same universe as R ZL' : Type ℓ ZL' = A / (_∼'_) IsoLarLatSmall : Iso ZL ZL' IsoLarLatSmall = relBiimpl→TruncIso ~→∼' ~'→∼ where ~→∼' : ∀ {a b : A} → a ∼ b → a ∼' b ~→∼' r = √FGIdealCharLImpl _ ⟨ _ ⟩ (λ x h → subst (λ p → x ∈ p) r h) , √FGIdealCharLImpl _ ⟨ _ ⟩ (λ x h → subst (λ p → x ∈ p) (sym r) h) ~'→∼ : ∀ {a b : A} → a ∼' b → a ∼ b ~'→∼ r = CommIdeal≡Char (√FGIdealCharRImpl _ ⟨ _ ⟩ (fst r)) (√FGIdealCharRImpl _ ⟨ _ ⟩ (snd r)) ZL≃ZL' : ZL ≃ ZL' ZL≃ZL' = isoToEquiv IsoLarLatSmall
[STATEMENT] lemma dense_list_in_range: "x \<in> set (dense_list_of_pdevs X) \<Longrightarrow> x \<in> range (pdevs_apply X)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> set (dense_list_of_pdevs X) \<Longrightarrow> x \<in> range (pdevs_apply X) [PROOF STEP] by (auto simp: dense_list_of_pdevs_def)
While some Dividend Aristocrats -- stocks that have raised their payouts annually for at least 25 years in a row -- offer attractive yields and have solid track records, their growth rate may just be in the low single digits, which can be a problem for long-term investors. That's why it's important to consider the both growth rate and dividend payout ratio. But long-term investors who are saving for retirement, a child's college fund, or even to pass assets down to their descendants will want to consider dividend growth above all else. Below are two rock-solid companies with fast-growing payouts that are likely to be dividend powerhouses decades from now. In the span of one generation, Starbucks (NASDAQ:SBUX) has gone from a small coffee chain to the second-biggest restaurant company in the world, behind McDonald's. Plenty of jokes have been made over the years about the company's ubiquity, but it continues to expand aggressively, adding more than 2,000 stores last year to top 25,000 worldwide. Like Starbucks, Nike(NYSE:NKE) dominates its industry, and has crushed the market over the long term. With its brand and distribution advantages, and its leadership in athletic footwear, Nike is likely to continue to outperform the market. I'm considering SBUX for baby DivHut's portfolio for the same reason you write about... continued growth for a while longer.
theory T12 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) " nitpick[card nat=4,timeout=86400] oops end
lemma homeomorphic_translation: fixes S :: "'a::real_normed_vector set" shows "S homeomorphic ((\<lambda>x. a + x) ` S)"
# This is from the original version of Gemma Halliwell's thesis. # It is probably not useful. `is_element/marked_digraphs` := (V::set) -> (m,n::nonnegint) -> proc(EIO) local E,VI,VO,NI,NO,v; if not (type(EIO,list) and nops(EIO) = 3) then return false; fi; E,VI,VO := op(EIO); if not `is_element/digraphs`(V)(E) then return false; fi; if not(type(VI,set) and nops(VI) = m and VI minus V = {}) then return false; fi; if not(type(VO,set) and nops(VO) = n and VO minus V = {}) then return false; fi; if VI intersect VO <> {} then return false; fi; NI := `in_neighbour_table/digraphs`(V)(E); NO := `out_neighbour_table/digraphs`(V)(E); for v in VI do if nops(NI[v]) <> 0 then return false; fi; od: for v in VO do if nops(NO[v]) <> 0 then return false; fi; if nops(NI[v]) <> 1 then return false; fi; od: return true; end: `internal_vertices/marked_digraphs` := (V) -> (m,n) -> proc(EIO) local E,VI,VO; E,VI,VO := op(EIO); return V minus (VI union VO); end:
(* Title: HOL/Auth/n_germanSimp_lemma_on_inv__32.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_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_on_inv__32 imports n_germanSimp_base begin section{*All lemmas on causal relation between inv__32 and some rule r*} lemma n_SendInv__part__0Vsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv3) ''Cmd'')) (Const GntE))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv3) ''Cmd'')) (Const GntE))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv4) ''Cmd'')) (Const Inv)) (eqn (IVar (Para (Ident ''ShrSet'') p__Inv4)) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__32: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i=p__Inv3)\<or>(i~=p__Inv3\<and>i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv3)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv3\<and>i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__32: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvInvAckVsinv__32: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqE__part__0Vsinv__32: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqE__part__1Vsinv__32: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqSVsinv__32: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__32 p__Inv3 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
$NetBSD: patch-src_editor_inputbox.hpp,v 1.1 2019/05/12 06:17:30 triaxx Exp $ * Port to Boost.Signals2. --- src/editor/inputbox.hpp.orig 2011-12-24 21:46:47.000000000 +0000 +++ src/editor/inputbox.hpp @@ -17,7 +17,7 @@ #ifndef HEADER_PINGUS_EDITOR_INPUTBOX_HPP #define HEADER_PINGUS_EDITOR_INPUTBOX_HPP -#include <boost/signal.hpp> +#include <boost/signals2.hpp> #include "engine/gui/rect_component.hpp" @@ -40,8 +40,8 @@ public: void update_layout() {} - boost::signal<void (const std::string&)> on_change; - boost::signal<void (const std::string&)> on_enter; + boost::signals2::signal<void (const std::string&)> on_change; + boost::signals2::signal<void (const std::string&)> on_enter; private: Inputbox (const Inputbox&);
<h1><center>Tutorial 3: Probability</center></h1> <div style="text-align: center">Adnane Ez-zizi, 16 Oct 2019</div> $\newcommand{\E}{\mathrm{E}}$ $\newcommand{\Var}{\mathrm{Var}}$ $\newcommand{\Cov}{\mathrm{Cov}}$ $\newcommand{\Corr}{\mathrm{Corr}}$ This notebook introduces the elementary concepts from the probability theory that are necessary to understand and build machine learning models. For example, we will cover notions such as a random variable, a probability distribution and independence, as well as useful properties of probability like the chain rule or Bayes theorem. We will also illustrate these notions using Python code. ## 0. Preliminary steps ```python import numpy as np from scipy import stats import matplotlib.pyplot as plt #%precision 3 ``` ## 1. Definition of probability Probability, at its core, refers to the likelihood or the chance that a certain event will occur. For instance, when we roll a fair die, we can intuitively report that there is a probability of $\frac{1}{6}$ that one of the six possible outcomes (1, 2, 3, 4, 5 or 6) will occur. Probability, as a field, is branch of mathematics that provides tools to deal and measure uncertainty. In machine learning, we often have to deal with uncertain or stochastic quantities, whether the system that we try to model is assumed inherently stochastic like the trajectory of a subatomic particle, or cannot be completely observed like a robot with a low quality camera trying to identify objects, or because of incomplete modelling like when have to discard some of the information that we have collected (e.g., a robot that discretises the space when making a prediction about the position of an object). Before we move to more advanced notions, let's cover some elementary terminology that is commonly used in probability theory: - **Experiment:** any process, usually random, that results in one of many possible results. For example in our first example, the toss of a die can be considered as an experiment. - **Trial:** one repetition of the process of an experiment. For example, in the experiment of tossing a die 10 times and recording the sequence of results, each toss is considered as a trial. - **Outcome:** each distinct possible result of an experiment. For example, in the experiment of tossing a die twice, one possible outcome is (3,5) where 3 is the result from the first trial and 5 is the result from the second trial. - **Event:** consists of one or more outcomes. For example, in the experiment of tossing on die, drawing an even number can be considered as an event, which has 3 possible outcomes (2, 4 and 6). - **Sample space** set of all possible outcome. For the die experiment, the sample space is {1,2,3,4,5,6}. In mathematical notation, the probability of an event E is often denoted as $P(E)$ or $Pr(E)$. ## 2. Random variables A random variable is a function that maps a possible outcome of a random process to a real number. For example, we can define a random variable that represents the outcome from a die roll, $X \in \{1,2,3,4,5,6\}$, or the sum of the outcomes from rolling two dice, $Y \in \{1,2,\cdots,12\}$. Once we have defined a random variable, we can talk about its probability of taking a certain value or of taking a value in a given interval. Thus, the probability of observing a 3 when we roll a die is expressed as $P(X = 3)$, while the probability of observing an even outcome can be expressed as $P(X \in \{2,4,6\})$. There are two types of random variables: discrete and continuous. A random variable is said to be discrete if it takes a finite or countably infinite number of values such as the variable $X$ representing the die roll's outcome. A continous random variable can take real values such as the value of a share in a stock exchange market. ## 3. Discrete variables ### 3.1. Probability mass function The probability mass function, or distribution of a discrete random variable $X$ maps the possible values of $X$ ($x_1, x_2, \dots$) to their probabilities. We will denote a probability mass function by a lower-cased $p(.)$: $p(x_i) = P(X = x_i)$ for all possible values $x_i$'s of X. For example, the probability mass function of the random variable $X$ that represents a die roll outcome is defined by: \begin{equation} p(x) = P(X = x) = \frac{1}{6} \;\; \text{for} \; x \in \{1, 2, 3, 4, 5, 6\} \end{equation} A probability mass function $p$ of a random variable $X$ must satisfy 3 conditions: 1. The domain of $p$ must be the set of all possible outcomes of $X$. 2. for all possible values $x$ of $X$, $0\leq p(x) \leq 1$, where $p(x) = 0$ if $x$ can never occur (impossible outcome) and $p(x) = 1$ if $x$ always occur. 3. $\sum_{x} {p(x)} = 1$, that is, the probabilities of all possible outcomes sum to 1. ### 3.2. Expectation and variance #### Expectation The expectation or expected value (or mean) of a discrete random variable $X$ is defined as: $\E(X) = \sum_{i} {x_ip(x_i)}$. In other words, the expectation is a weighted average of the possible values $x_i$ with weights $p(x_i)$, similar to a center of mass in physics. It gives us an idea about the central value taken by the random variable. For the die roll example above, the expectation is equal to: \begin{equation} \E(X) = 1 \cdot \frac{1}{6} + 2 \cdot \frac{1}{6} + 3 \cdot \frac{1}{6} + 4 \cdot \frac{1}{6} + 5 \cdot \frac{1}{6} + 6 \cdot \frac{1}{6} = \frac{21}{6} = 3.5 \end{equation} The expectation has a few properties: - The expectation of a deterministic value is equal to the value itself: $\E(x) = x$, where x is a non-random value. - The expectation is a linear function, that is: $\E(aX + bY) = a\E(X) + b\E(Y)$. - $\E(f(X)) = \sum_{i} {f(x_i)p(x_i)}$ #### Variance The variance provides a measure of how much the values of a random variable $X$ vary as we sample different values of $X$ from its probability distribution. Mathematically, it is defined as: $\Var(X) = \E(\left[X - \E(X)\right]^2) = \E(X^2) - \E(X)^2$. For instance, the variance of $X$ in the die roll example is given by: \begin{equation} \Var(X) = \E(X^2) - \E(X)^2 = (1^2 \cdot \frac{1}{6} + 2^2 \cdot \frac{1}{6} + 3^2 \cdot \frac{1}{6} + 4^2 \cdot \frac{1}{6} + 5^2 \cdot \frac{1}{6} + 6^2 \cdot \frac{1}{6}) - \frac{21}{6} = \frac{71}{6} \end{equation} The variance has a few properties: - The variance of a deterministic value is equal to 0: $\Var(x) = 0$, where $x$ is a non-random value. - The variance preserves the sum: $\Var(X + Y) = \Var(X) + \Var(Y)$. - The variance is a non linear function for the multiplication by a scalar: $\Var(aX) = a^2\Var(X)$. - $\Var(f(X)) = \E(f(X)^2) - \E(f(X))^2$ The standard deviation is a related measure defined as the square root of the variance: $SD(X) = \sqrt{\Var(X)}$. ### 3.3. Some popular discrete probability distributions #### Bernoulli distribution Suppose that we run a random experiment whose outcome can be classified as either a success or a failure. An example of such an experiment is tossing a fair coin where a head is considered as success and tail as failure. If we let $X = 1$ when the outcome is a success (e.g. head) and $X = 0$ when it is a failure (e.g. tail), then the probability mass function of $X$ is given by: \begin{aligned} & p(0) = P(X = 0) = 1 − p\\ & p(1) = P(X = 1) = p \end{aligned} where $p$ is the probability that the experiment is a success ($0\leq p\leq 1$). A random variable $X$ is said to be a Bernoulli random variable if its probability mass function is given by the equations shown just above for some $p \in (0, 1)$. We also say that $X$ follows a Bernoulli distribution with parameter $p$ and write this mathematically as $X \sim Bernoulli(p)$. ```python # Mass function of a Bernoulli(0.7) distribution print('p(0) ={p0: 1.1f}'.format(p0 = stats.bernoulli.pmf(0, p = 0.7))) print('p(1) ={p0: 1.1f}'.format(p0 = stats.bernoulli.pmf(1, p = 0.7))) ``` p(0) = 0.3 p(1) = 0.7 We can draw samples from a Bernoulli distribution, using the function `stats.bernoulli.rvs()`. For example, if we want to draw 10 values from a $Bernoulli(0.7)$ distribution, we would use: ```python # Draw 10 values from a Bernoulli variable with p = 0.7 stats.bernoulli.rvs(p = 0.7, size = 10) ``` The expection and variance of a random variable $X \sim Bernoulli(p)$ can be computed in a straightforward manner as: \begin{align} & \E(X) = 0 \cdot p(0) + 1 \cdot p(1) = p\\ & \Var(X) = E(X^2) - E(X)^2 = (0^2 \cdot p(0) + 1^2 \cdot p(1)) - p^2 = p(1-p) \end{align} ```python # Expectation and variance of a X ~ Bernoulli(0.7) print('E(X) ={exp: 1.2f}'.format(exp = stats.bernoulli.mean(p = 0.7))) print('Var(X) ={var: 1.2f}'.format(var = stats.bernoulli.var(p = 0.7))) ``` #### Binomial distribution Suppose now that we perform an experiment with $n$ independent trials, each of which results in a success with probability $p$ and in a failure with probability $1 − p$. If $X$ represents the number of successes that occur in the $n$ trials, then $X$ is said to be a binomial random variable with parameters $(n, p)$. A Bernoulli random variable is thus just a binomial random variable with parameters $(1, p)$. The probability mass function of a binomial random variable, $X$, having parameters $(n, p)$ (we can write $X \sim B(n,p)$), is given by: \begin{equation} p(i) = {n \choose i} p^i (1 − p)^{n−i} \quad i = 0, 1,\dots, n \end{equation} where ${n \choose i}$ is the number of possible combinations that result from randomly drawing $i$ objects out of $n$ different objects. Mathematically, ${n \choose i} = \frac{n!}{i!\,(n-i)!}$, where $k! = k\times(k-1)\times(k-2)\dots\times1$. ```python # Mass function of a B(6,0.5) distribution for i in range(7): print('p({j:d}) = {p0:1.4f}'.format(j = i, p0 = stats.binom.pmf(i, n = 6, p = 0.5))) ``` p(0) = 0.0156 p(1) = 0.0938 p(2) = 0.2344 p(3) = 0.3125 p(4) = 0.2344 p(5) = 0.0938 p(6) = 0.0156 ```python # Plor of the mass function fig, ax = plt.subplots(1, 1) n, p = 6, 0.5 x = list(range(7)) ax.plot(x, stats.binom.pmf(x, n, p), 'bo', ms=8, label='binom pmf') ax.vlines(x, 0, stats.binom.pmf(x, n, p), colors='b', lw=5, alpha=0.5) plt.show() ``` In code, to draw samples from a Binomial distribution, we can call `stats.binom.rvs()`. For example, drawing 3 values from a $B(6, 0.5)$ distribution can be done using the following code: ```python # Draw 3 values from a variable following a B(6, 0.5) print(stats.binom.rvs(n = 6, p = 0.5, size = 3)) ``` [3 5 1] This means that we got 4 successes ($X = 1$) in each of the first two draws, and got 2 successes in the last draw. The expection and variance of a random variable $X \sim B(n,p)$ are given by: \begin{align} & \E(X) = np\\ & \Var(X) = p(1-p) \end{align} ```python # Expectation and variance of a X ~ B(6, 0.5) print('E(X) ={exp: 1.1f}'.format(exp = stats.binom.mean(n = 6, p = 0.5))) print('Var(X) ={var: 1.1f}'.format(var = stats.binom.var(n = 6, p = 0.5))) ``` E(X) = 3.0 Var(X) = 1.5 ## 4. Continuous variables ### 4.1. Probability density function When working with a continuous random variable, we no longer want to find the probability that the variable take a specific value such as asking what is the probability that the value of a certain share in a financial market is exactly £100.684, since this probability will virtually be 0. Instead, we are more interested in the probability that the continuous random variable lies in a certain interval. For that, we normally describe the distribution of a random variable using a probability density function instead of a probability mass function. More specifically, a function $f$ is said to be the density of a random variable $X$ if, for any interval $I$, $P(X \in I) = \int_{I}{f(x)dx}$. In general, a function $f$ must satisfy 3 conditions to be considered as a density function of a random variable $X$: 1. The domain of $f$ must be the set of all possible outcomes of $X$. 2. for all possible values $x$ of $X$, $f(x) \geq 0$. 3. $\int{f(x)dx} = 1$. ### 4.2. Expectation and variance #### Expectation The definition of expectation in the case of continuous random variables is very similar to that in the discrete case, where we only have to replace the summation with integration, and the probability mass function with the probability density function. More specifically, if $X\sim f$ (meaning that X follows a distribution whose density function is $f$) and the domain of $X$ is $\mathcal{X}$, then: $\E(X) = \int_{\mathcal{X}} {xf(x)dx}$. #### Variance For variance, the definition remains the same: $\Var(X) = \E(\left[X - \E(X)\right]^2) = \E(X^2) - \E(X)^2$. ### 4.3. Cumulative distribution function Let $X$ be a random variable. The function $F$ defined by: \begin{equation} F(x) = P(X \leq x), \quad -\infty \leq x\leq \infty \end{equation} is called the cumulative distribution function of $X$. Thus, $F$ specifies, for all real values $x$, the probability that the random variable is less than or equal to $x$. Similarly to the probability density function, the cumulative distribution function $F$ describes fully the distribution of a random variable, with the additional advantage that it can work with any type of random variables (discrete or continuous). Actually, F can be obtained from $f$, the probability density function, using the formulas: $F(x) = \int{f(t)dt}$ The One interesting property of $F$ is that it is a nondecreasing function; that is, if $a < b$, then $F(a) \leq F(b)$. ### 4.4. Some popular continuous probability distributions #### Uniform distribution A random variable $X$ is said to be uniformly distributed over the interval $(a, b)$, noted in short as $X \sim U(a,b)$, if $X$ is equally likely to fall anywhere in this interval. The probability density function of such random variable is given by: \begin{equation} f(x) = \left\{ \begin{array}{ll} \frac{1}{b-a} & \mbox{if } a\leq x\leq b \\ 0 & \mbox{otherwise } \end{array} \right. \end{equation} ```python # density function of a U(0,1) distribution print('f(-0.2) = {fx:1.1f}'.format(fx = stats.uniform.pdf(-0.2, loc = 0, scale = 1))) print('f(0) = {fx:1.1f}'.format(fx = stats.uniform.pdf(0, loc = 0, scale = 1))) print('f(0.3) = {fx:1.1f}'.format(fx = stats.uniform.pdf(0.1, loc = 0, scale = 1))) print('f(1) = {fx:1.1f}'.format(fx = stats.uniform.pdf(1, loc = 0, scale = 1))) print('f(4.5) = {fx:1.1f}'.format(fx = stats.uniform.pdf(4.5, loc = 0, scale = 1))) ``` f(-0.2) = 0.0 f(0) = 1.0 f(0.3) = 1.0 f(1) = 1.0 f(4.5) = 0.0 ```python # Plot of the density function fig, ax = plt.subplots(1, 1) a, b = 0, 1 x = np.linspace(-2, 2, 200) ax.plot(x, stats.uniform.pdf(x, loc = a, scale = b), 'r-', lw=2, label='frozen pdf') plt.show() ``` In code, to draw samples from a Uniform distribution, we can call `stats.uniform.rvs()`. For example, drawing 10 values from a $U(0, 1)$ distribution can be done using the following code: ```python # Draw 10 values from a variable following a U(0, 1) stats.uniform.rvs(loc = 0, scale = 1, size = 10) ``` Since $F(x) = \int{f(t)dt}$, it follows from the above equation that the distribution function of a uniform random variable on the interval $(a, b)$ is given by: \begin{equation} F(x) = \left\{ \begin{array}{ll} 0 & \mbox{if } x< a \\ \frac{x-a}{b-a} & \mbox{if } a\leq x\leq b \\ 1 & \mbox{otherwise } \end{array} \right. \end{equation} The expectation and variance of the $U(a,b)$ distribution are given by: \begin{align} & \E(X) = \frac{a+b}{2}\\ & \Var(X) = \frac{(b-a)^2}{12} \end{align} ```python # Expectation and variance of a X ~ U(0, 1) print('E(X) ={exp: 1.1f}'.format(exp = stats.uniform.mean(loc = 0, scale = 1))) print('Var(X) ={var: 1.4f}'.format(var = stats.uniform.var(loc = 0, scale = 1))) ``` E(X) = 0.5 Var(X) = 0.0833 #### Normal distribution $X$ is said to be a normal random variable (or normally distributed), with parameters $\mu$ and $\sigma^2$ if the density of $X$ is given by: \begin{equation} f(x) = \frac{1}{\sqrt{2\pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (x-\mu)^2\right) \end{equation} In short, we denote a normal distribution with parameters $\mu$ and $\sigma^2$ by $\mathcal{N}(\mu,\sigma^2)$, so we will also write as before $X \sim \mathcal{N}(\mu,\sigma^2)$ to introduce a normal random variable $X$. ```python # density function of a N(0,1) distribution print('f(-1.96) = {fx:1.2f}'.format(fx = stats.norm.pdf(-1.96, loc = 0, scale = 1))) print('f(0) = {fx:1.2f}'.format(fx = stats.norm.pdf(0, loc = 0, scale = 1))) print('f(1.96) = {fx:1.2f}'.format(fx = stats.norm.pdf(1.96, loc = 0, scale = 1))) print('f(1) = {fx:1.2f}'.format(fx = stats.norm.pdf(1, loc = 0, scale = 1))) ``` f(-1.96) = 0.06 f(0) = 0.40 f(1.96) = 0.06 f(1) = 0.24 ```python # Plot of the density function fig, ax = plt.subplots(1, 1) mu, sigma = 0, 1 x = np.linspace(-5, 5, 100) ax.plot(x, stats.norm.pdf(x, loc = mu, scale = sigma), 'r-', lw=2, label='frozen pdf') plt.show() ``` In code, to draw samples from a Uniform distribution, we can call `stats.uniform.rvs()`. For example, drawing 10 values from a $U(0, 1)$ distribution can be done using the following code: ```python # Draw 10 values from a variable following a N(0, 1) stats.norm.rvs(loc = 0, scale = 1, size = 10) ``` array([-1.07286337, -0.02047795, -1.0892859 , 0.63307728, -0.71625438, -0.43093896, -0.09998078, -0.32279445, -0.98224144, -1.03249923]) The expectation and variance of a normally distributed random variable, $X \sim \mathcal{N}(\mu,\sigma^2)$, are respectively equal to the paramters of the distribution, that is: $\E(X) = \mu$ and $\Var(X) = \sigma^2$. In other words a normal distribution is completely specified using its expectation and variance. ```python # Expectation and variance of a X ~ U(0, 1) print('E(X) ={exp: 1.1f}'.format(exp = stats.norm.mean(loc = 0, scale = 1))) print('Var(X) ={var: 1.1f}'.format(var = stats.norm.var(loc = 0, scale = 1))) ``` E(X) = 0.0 Var(X) = 1.0 ## 5. Joint and conditional distributions ### 5.1. Joint probability Up to now, we have only discussed probability distributions for single random variables. But what if we are interested in the outcomes of two or more random variables? For example, suppose we toss two fair coins and wants to know the probability that the first coin turns up head and the second turns up tail, or in a formal way, $P(X_1 = H, X_2 = T)$, where $X_1$ and $X_2$ respectively represent the outcome of the first and second coin. Let's write the probabilities of all possible joint outcomes in a table: outcome | probability ---- | ------- HT | 1/4 HH | 1/4 TH | 1/4 TT | 1/4 What we just did is to define a joint probability distribution for the random variables $X_1$ and $X2$. Technically, as before, we can talk either about a joint probability mass function in the case of discrete variables or joint probability density function (or cumulative distribution function) when the variables are continuous. #### Joint probability mass function (discrete case): Assume we have two discrete random variables $X$ and $Y$, which can take on values $x_1, x_2, \dots$ and $y_1, y_2, \dots$, respectively. Their joint probability mass function is defined as: \begin{equation} p(x_i, y_i) = P(X = x_i, Y = y_i) \; \text{for all possible values $x_i$'s and $y_i$'s of $X$ and $Y$}. \end{equation} A joint probability mass function $p$ of a random variable $X$ must satisfy the same 3 conditions seen before for a standard mass function: 1. The domain of $p$ must be the set of all possible joint outcomes of $X$ and $Y$. 2. for all possible values $x$ of $X$ and $y$ of $Y$, $0\leq p(x, y) \leq 1$ 3. $\sum_{x,y} {p(x,y)} = 1$, that is, the probabilities of all possible outcomes sum to 1. One of the widely-used joint distributions is the [multinomial distribution](https://en.wikipedia.org/wiki/Multinomial_distribution), which generalises the binomial distribution when we are interested in the probability of any possible combination of number of success of each of $k$ categories (instead of two) in $n$ independent trials. For example, say we roll a 6-sided die $n$ times independently. The multinomial distribution would then give the probabiliy of counts of each of the 6 sides (here, $k=6$). The parameters of a multinomial are: $n$, the number of independent trials and $p_1, \dots, p_k$ the probabilities of successes of each of the $k$ categories to compute the count of successes for. We thus often denote the multinomial distribution by $Mult(n, p_1, \dots, p_k)$ #### Marginal mass function (discrete case) If we have a joint distribution of multiple discrete variables, we can extract the mass function of one of the variables by summing over the possible values of the other variables. The obtained distribution of that variable is called marginal distribution. Concretelely, say we have two random variables $X$ and $Y$ that represent the outcomes of coin flips. Their joint mass function is given by: \begin{equation} p(i,j) = \frac{1}{4} \;\text{for } i,j \in \{H,T\} \end{equation} The marginal mass function of $X$ can be extracted as follows: \begin{equation} p(i) = \sum_{j \in \{H,T\}}{p(i,j)} = \frac{1}{4} + \frac{1}{4} = \frac{1}{2} \end{equation} #### Joint cumulative and density functions (continuous case): Joint cumulative distribution function can be easily generalised from the single variable case to the multiple-variable case. If $X$ and $Y$ are two continous random variables, their joint cumulative distribution function is defined as: \begin{equation} F(x, y) = P(X \leq x, Y \leq y), \quad -\infty \leq x,y\leq \infty \end{equation} We say that $f$ is the joint probabiliy density function of $X$ and $Y$ if, for any interval $I$ and $J$, $P(X \in I, Y \in J) = \int_{I,J}{f(x,y)dxdy}$. The density function $f$ also satisfies the same 3 conditions seen in the case of a single variable, that is: 1. The domain of $f$ must be the set of all possible joint outcomes of $X$ and $Y$. 2. for all possible values $x$ of $X$ and $y$ of $Y$, $f(x, y) \geq 0$. 3. $\int{f(x,y)dxdy} = 1$. #### Marginal density function (continous case) As in the discrete case, if we have a joint distribution of two (or multiple) continuous random variables $X$ and $Y$, we can marginalizing over $Y$ to get the marginal distrubution of $X$. This is done by integrating over the values of $Y$: \begin{equation} f(x) = \int{f(x,y)dy} \end{equation} ### 5.2. Conditional probability #### Definition We often want to know the probability of one event, given that we know another event is true. For instance, given that a house is located in a posh area, what is the probability that its price is greater than £500,000. This is refered to as a conditional probability, and in our case, we write it as $P(\text{price } > 500000 \text{ | area is posh})$. If we know the joint distribution of two random variables, then we can get the conditional distribution of one variable given the other variable as follows: - In the discrete case, the conditional mass function of $X$ given $Y$ is equal to: $p(x|y) = \frac{p(x,y)}{p(y)} = \frac{p(x,y)}{\sum_{x}{p(x,y)}}$ - In the continuous case, the conditional density function of $X$ given $Y$ is equal to: $f(x|y) = \frac{f(x,y)}{f(y)} = \frac{f(x,y)}{\int{f(x,y)dx}}$ The definition can be extended easily to the case of more than two variables by simply replacing one of the variable in the formula with the multiple variables that we want to condition on or compute the conditial distribution for. #### Chain rule Any joint probability distribution over many random variables may be decomposed into conditional distributions over only one variable: \begin{equation} P(x_1, \cdots , x_n) = P(x_n|x_{n-1}, \cdots, x_1)P(x_{n-1}|x_{n-2}, \cdots, x_1) \cdots P(x_2|x_1) P(x_1) \end{equation} Thus, for example, we have: \begin{equation} P(x,y,z) = P(x|y,z)P(y|z)P(z) \end{equation} #### Bayes theorem Bayes theorem, named after the reputable Mathematician Thomas Bayes, is a simple yet a powerful formula that allows to flip a conditional probability. It basically states that: \begin{equation} p(y|x) = \frac{p(x|y)p(y)}{p(x)} = \frac{p(x|y)p(y)}{\sum_y{p(x|y)p(y)}} \end{equation} One major application of Bayes theorem is to compute the probability of a model (or the parameters of the model to be more precise) given some data. Knowing the model, we can determine the probability of the data given a specific set of model parameters. Bayes’ rule allows us to get from the probability of the data given the model $P(data|model)$, to the probability of the model given the data $P(model|data)$. In other words, it allows us to estimate the parameters of a model having collected a set of data. ### 5.3. Independence and conditional independence #### Independence Two random variables $X$ and $Y$ are said to be independent (often denoted as $X\perp Y$) if the values taken by one of the variables have no influence in the values taken by the other variable. Formally, this can be expressed using conditional probabilities as: $p(x|y) = p(x)$ in the discrete case, or $f(x|y) = f(x)$ in the continous case. knowing that $p(x|y) = \frac{p(x,y)}{p(y)}$ then $\frac{p(x,y)}{p(y)} = p(x)$ which means that $p(x,y) = p(x)p(y)$ Actually, in textbooks of probability, you often find that independence is introduced using the last formula instead of using conditional probabilities. #### Conditional independence Two random variables $X$ and $Y$ are conditionally independent given a random variable $z$ (denoted as $X\perp Y \;|\; Z$) if the conditional joint mass (or density) function of $X$ and $Y$ is equal to the product of the conditional mass (or density) functions of the two random variables: \begin{equation} p(x,y|z) = p(x|z)p(y|z) \end{equation} ### 5.4. Covariance and correlation #### Covariance The covariance between $X$ and $Y$, denoted by $\Cov(X,Y)$, is defined by \begin{equation} \Cov(X,Y) = \E\left[(X-\E(X)) (Y-\E(Y))\right] \end{equation} The covariance has a few properties: - The covariance is symmetric: $\Cov(X,Y) = \Cov(Y,X)$ - The covariance is a linear function of each argument, that is: $\Cov(aX,Y) = a\,\Cov(Y,X)$. - If $X$ and $Y$ are independent, then $\Cov(X,Y) = 0$. #### Correlation The correlation of two random variables $X$ and $Y$, denoted by $\Corr(X,Y)$, is defined by: \begin{equation} \Corr(X,Y)= \frac{\Cov(X,Y)}{\sqrt{\Var(X)\Var(Y)}} \end{equation} where $\Var(X)$ and $\Var(Y)$ are strictly positive. One can show that $-1\leq\Corr(X,Y)\leq 1$ The correlation coefficient is a measure of the degree of linearity between $X$ and $Y$. A value of $\Corr(X,Y)$ near $1$ or $−1$ indicates a high degree of linearity between $X$ and $Y$, whereas a value near $0$ indicates that such linearity is absent. A positive value of $\Corr(X,Y)$ indicates that $Y$ tends to increase when $X$ does, whereas a negative value indicates that $Y$ tends to decrease when $X$ increases. If $\Corr(X,Y) = 0$, then $X$ and $Y$ are said to be uncorrelated. ## 6. Law of large numbers, Central limit theorem Here we will cover two of the most fundamental theorems in Probability ### 6.1. Law of large numbers Suppose that we have a collection of random variables $X_1, X_2, \cdots, X_n$ that are independent and identically distributed. The strong law of large numbers states that as the number of random variables increase ($n\to \infty$), the empirical average of the random variables will get closer to the true common expected value of the variables normal distribution: \begin{equation} \frac{1}{n}\sum_{i=1}^n{X_i} \xrightarrow[n\to \infty]{} \E(X) \end{equation} where the convergence is almost sure, that is: \begin{equation} P\left( \lim_{n \to \infty} \frac{1}{n}\sum_{i=1}^n{X_i} = \E(X) \right) = 1 \end{equation} ### 6.2. Central limit theorem Let's $X_1, X_2, \cdots, X_n$ be a collection of random variables that are independent and identically distributed. The central limit theorem states that if we sum them up, then the larger the collection, the closer the sum will be to a normal distribution. Mathematically, this is translated as: \begin{equation} \frac{1}{\sqrt{n}} \sum_{i=1}^n \frac{X_i - \mu}{\sigma} \xrightarrow[n\to \infty]{} \mathcal{N}(0, 1) \quad \left(\text{or equivalently}, \sum_{i=1}^n{X_i} \underset{n\to \infty}{\sim} \mathcal{N}\left(\mu, \frac{\sigma}{n}\right)\right) \end{equation} where $\mu$ and $\sigma^2$ are respectively the common expectation and variance of the random variables $X_1, X_2, \cdots, X_n$, and the convergence is in law, that is: \begin{equation} \lim_{n \to \infty} P\left( \frac{1}{\sqrt{n}} \sum_{i=1}^n \frac{x_i - \mu}{\sigma} \le z \right) = \int_{-\infty}^z (1/\sqrt{2 \pi}) \exp(-u^2/2) \, du \end{equation}
The empty set is convex.
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import ring_theory.power_series.basic import data.nat.parity import algebra.big_operators.nat_antidiagonal /-! # Definition of well-known power series In this file we define the following power series: * `power_series.inv_units_sub`: given `u : units R`, this is the series for `1 / (u - x)`. It is given by `∑ n, x ^ n /ₚ u ^ (n + 1)`. * `power_series.sin`, `power_series.cos`, `power_series.exp` : power series for sin, cosine, and exponential functions. -/ namespace power_series section ring variables {R S : Type*} [ring R] [ring S] /-- The power series for `1 / (u - x)`. -/ def inv_units_sub (u : units R) : power_series R := mk $ λ n, 1 /ₚ u ^ (n + 1) @[simp] lemma coeff_inv_units_sub (u : units R) (n : ℕ) : coeff R n (inv_units_sub u) = 1 /ₚ u ^ (n + 1) := coeff_mk _ _ @[simp] lemma constant_coeff_inv_units_sub (u : units R) : constant_coeff R (inv_units_sub u) = 1 /ₚ u := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_units_sub, zero_add, pow_one] @[simp] lemma inv_units_sub_mul_X (u : units R) : inv_units_sub u * X = inv_units_sub u * C R u - 1 := begin ext (_|n), { simp }, { simp [n.succ_ne_zero, pow_succ] } end @[simp] lemma inv_units_sub_mul_sub (u : units R) : inv_units_sub u * (C R u - X) = 1 := by simp [mul_sub, sub_sub_cancel] lemma map_inv_units_sub (f : R →+* S) (u : units R) : map f (inv_units_sub u) = inv_units_sub (units.map (f : R →* S) u) := by { ext, simp [← monoid_hom.map_pow] } end ring section field variables (A A' : Type*) [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] open_locale nat /-- Power series for the exponential function at zero. -/ def exp : power_series A := mk $ λ n, algebra_map ℚ A (1 / n!) /-- Power series for the sine function at zero. -/ def sin : power_series A := mk $ λ n, if even n then 0 else algebra_map ℚ A ((-1) ^ (n / 2) / n!) /-- Power series for the cosine function at zero. -/ def cos : power_series A := mk $ λ n, if even n then algebra_map ℚ A ((-1) ^ (n / 2) / n!) else 0 variables {A A'} (n : ℕ) (f : A →+* A') @[simp] lemma coeff_exp : coeff A n (exp A) = algebra_map ℚ A (1 / n!) := coeff_mk _ _ @[simp] lemma constant_coeff_exp : constant_coeff A (exp A) = 1 := by { rw [← coeff_zero_eq_constant_coeff_apply, coeff_exp], simp } @[simp] lemma map_exp : map (f : A →+* A') (exp A) = exp A' := by { ext, simp } @[simp] lemma map_sin : map f (sin A) = sin A' := by { ext, simp [sin, apply_ite f] } @[simp] lemma map_cos : map f (cos A) = cos A' := by { ext, simp [cos, apply_ite f] } end field open ring_hom open finset nat variables {A : Type*} [comm_ring A] /-- Shows that $e^{aX} * e^{bX} = e^{(a + b)X}$ -/ theorem exp_mul_exp_eq_exp_add [algebra ℚ A] (a b : A) : rescale a (exp A) * rescale b (exp A) = rescale (a + b) (exp A) := begin ext, simp only [coeff_mul, exp, rescale, coeff_mk, coe_mk, factorial, nat.sum_antidiagonal_eq_sum_range_succ_mk, add_pow, sum_mul], apply sum_congr rfl, rintros x hx, suffices : a^x * b^(n - x) * (algebra_map ℚ A (1 / ↑(x.factorial)) * algebra_map ℚ A (1 / ↑((n - x).factorial))) = a^x * b^(n - x) * ((↑(n.choose x) * (algebra_map ℚ A) (1 / ↑(n.factorial)))), { convert this using 1; ring }, congr' 1, rw [←map_nat_cast (algebra_map ℚ A) (n.choose x), ←map_mul, ←map_mul], refine ring_hom.congr_arg _ _, rw [mul_one_div ↑(n.choose x) _, one_div_mul_one_div], symmetry, rw [div_eq_iff, div_mul_eq_mul_div, one_mul, choose_eq_factorial_div_factorial], norm_cast, rw cast_dvd_char_zero, { apply factorial_mul_factorial_dvd_factorial (mem_range_succ_iff.1 hx), }, { apply mem_range_succ_iff.1 hx, }, { rintros h, apply factorial_ne_zero n, rw cast_eq_zero.1 h, }, end /-- Shows that $e^{x} * e^{-x} = 1$ -/ theorem exp_mul_exp_neg_eq_one [algebra ℚ A] : exp A * eval_neg_hom (exp A) = 1 := by convert exp_mul_exp_eq_exp_add (1 : A) (-1); simp /-- Shows that $(e^{X})^k = e^{kX}$. -/ theorem exp_pow_eq_rescale_exp [algebra ℚ A] (k : ℕ) : (exp A)^k = rescale (k : A) (exp A) := begin induction k with k h, { simp only [rescale_zero, constant_coeff_exp, function.comp_app, map_one, cast_zero, pow_zero, coe_comp], }, simpa only [succ_eq_add_one, cast_add, ←exp_mul_exp_eq_exp_add (k : A), ←h, cast_one, id_apply, rescale_one] using pow_succ' (exp A) k, end /-- Shows that $\sum_{k = 0}^{n - 1} (e^{X})^k = \sum_{p = 0}^{\infty} \sum_{k = 0}^{n - 1} \frac{k^p}{p!}X^p$. -/ theorem exp_pow_sum [algebra ℚ A] (n : ℕ) : (finset.range n).sum (λ k, (exp A)^k) = power_series.mk (λ p, (finset.range n).sum (λ k, k^p * algebra_map ℚ A p.factorial⁻¹)) := begin simp only [exp_pow_eq_rescale_exp, rescale], ext, simp only [one_div, coeff_mk, coe_mk, coeff_exp, factorial, linear_map.map_sum], end end power_series
||| Provie `Day` level function. module Data.Time.Calendar.Days ||| The Modified Julian Day is a standard count of days, with zero being the day 1858-11-17. public export data Day = MkModifiedJulianDay Integer export Eq Day where (MkModifiedJulianDay a) == (MkModifiedJulianDay b) = a == b export Ord Day where compare (MkModifiedJulianDay a) (MkModifiedJulianDay b) = compare a b export toInteger : Day -> Integer toInteger (MkModifiedJulianDay x) = x export Enum Day where pred (MkModifiedJulianDay x) = MkModifiedJulianDay (pred x) toNat (MkModifiedJulianDay x) = toNat x fromNat x = MkModifiedJulianDay (fromNat x) export range: (Day, Day) -> List Day range (MkModifiedJulianDay x, MkModifiedJulianDay y) = map (MkModifiedJulianDay) [x .. y] export index: (Day, Day) -> Nat -> Maybe Day index (a, b) k = let (MkModifiedJulianDay a1) = a (MkModifiedJulianDay b1) = b range_a_b = range (a, b) inbounds = inBounds k range_a_b in case inbounds of Yes prf => Just (List.index k range_a_b) No contra => Nothing export inRange: (Day, Day) -> Day -> Bool inRange (a, b) k = elem k (range (a, b)) export rangeSize: (Day, Day) -> Nat rangeSize x = List.length (range x) export addDays: Integer -> Day -> Day addDays x (MkModifiedJulianDay y) = MkModifiedJulianDay (x + y) export diffDays: Day -> Day -> Integer diffDays (MkModifiedJulianDay x) (MkModifiedJulianDay y) = x - y
If $S$ and $U$ are connected sets with $S \subseteq U$, and $C$ is a component of $U - S$, then $U - C$ is connected.
library(downloader) url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/femaleControlsPopulation.csv" filename <- basename(url) download(url, destfile = filename) data <- unlist(read.csv(filename)) population_mean <- mean(data) # sample 1 mean set.seed(1) abs(mean(sample(data, 5)) - population_mean) # sample 2 mean set.seed(5) abs(mean(sample(data, 5)) - population_mean)
Formal statement is: lemma convergentD: "convergent X \<Longrightarrow> \<exists>L. X \<longlonglongrightarrow> L" Informal statement is: If a sequence converges, then it converges to some limit.
Formal statement is: lemma sets_Sup_measure'2: "sets (Sup_measure' M) = sigma_sets (\<Union>m\<in>M. space m) (\<Union>m\<in>M. sets m)" Informal statement is: The sets of the supremum measure of a family of measures are the sigma-algebra generated by the union of the sets of the measures in the family.
################################################################################ # Copyright 2020, Marta Vanin, Tom Van Acker # ################################################################################ # PowerModelsDistributionStateEstimation.jl # # An extention package of PowerModels(Distribution).jl for Static Power System # # State Estimation. # ################################################################################ # using pkgs using Distributions using HDF5 using Ipopt using Polynomials using PowerModels, PowerModelsDistribution using PowerModelsDistributionStateEstimation #using SCS #removed while SDP tests are not active using Test # pkg const const _DST = Distributions const _PMD = PowerModelsDistribution const _PMDSE = PowerModelsDistributionStateEstimation const _Poly = Polynomials #network and feeder from ENWL for tests ntw, fdr = 4, 2 season = "summer" time_step = 144 elm = ["load", "pv"] pfs = [0.95, 0.90] rm_transfo = true rd_lines = true # set solvers ipopt_solver = optimizer_with_attributes(Ipopt.Optimizer,"max_cpu_time"=>300.0, "tol"=>1e-9, "print_level"=>0) # scs_solver = optimizer_with_attributes(SCS.Optimizer, "max_iters"=>20000, "eps"=>1e-5, # "alpha"=>0.4, "verbose"=>0) #deactivated while SDP tests not active @testset "PowerModelsDistributionStateEstimation" begin include("bad_data.jl") include("distributions.jl") include("estimation_criteria.jl") include("mixed_measurements.jl") include("non_exact_forms.jl") include("power_flow.jl") include("pseudo_measurements.jl") include("single_conductor_branches.jl") include("utils_and_start_val.jl") include("with_errors.jl") end ambiguities = Test.detect_ambiguities(PowerModelsDistributionStateEstimation); if !isempty(ambiguities) println("ambiguities detected: $ambiguities") end
module Main import System.File main : IO () main = do myFile <- openFile "out_string.txt" WriteTruncate case myFile of Right myFile => do fPutStr myFile "Alpha Beta" closeFile myFile Left err => printLn err
// Copyright (C) 2008-2018 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html #include <boost/contract.hpp> int gcd(int const a, int const b) { int result; boost::contract::check c = boost::contract::function() .precondition([&] { BOOST_CONTRACT_ASSERT(a > 0); BOOST_CONTRACT_ASSERT(b > 0); }) .postcondition([&] { BOOST_CONTRACT_ASSERT(result <= a); BOOST_CONTRACT_ASSERT(result <= b); }) ; int x = a, y = b; while(x != y) { if(x > y) x = x - y; else y = y - x; } return result = x; } //[check_macro int main() { // Implementation checks (via macro, disable run-/compile-time overhead). BOOST_CONTRACT_CHECK(gcd(12, 28) == 4); BOOST_CONTRACT_CHECK(gcd(4, 14) == 2); return 0; } //]
/- if R is a ring, I and ideal of R and S a multiplicative subset of R, then S−1I is an ideal of S−1R, and we have S−1R/S−1I=S⎯⎯⎯−1(R/I), where S⎯⎯⎯ is the image of S in R/I, [proof omitted] -/ import Kenny_comm_alg.temp linear_algebra.quotient_module import linear_algebra.linear_map_module import group_theory.submonoid universe u def localize {α : Type u} [comm_ring α] (S : set α) [is_submonoid S] (I : set α) [is_submodule I] : set (localization.loc α S) := {y | ∃ (x s : α) (hx : x ∈ I) (hs : s ∈ S), ⟦(⟨x, s, hs⟩:α × S)⟧ = y} abbreviation localize' {α : Type u} [comm_ring α] (I : set α) [is_submodule I] (S : set α) [is_submonoid S] : set (localization.loc α S) := localize S I variables {α : Type u} [comm_ring α] (S : set α) [is_submonoid S] variables (I : set α) [is_submodule I] postfix ⁻¹ := localize infix ` /ᵣ `:100 := localization.loc infix ` /ᵣ `:100 := localize' notation α` [1/`:max S `]` := localization.loc α S notation I` [1/`:max S `]` := localize S I notation S `ₑ`:max := quotient.mk '' S instance localization.is_submodule.of_comm_ring : is_submodule (S⁻¹ I) := { zero_ := ⟨(0:α), (1:α), @is_submodule.zero _ _ _ _ I _, is_submonoid.one_mem S, quotient.sound $ setoid.refl _⟩, add_ := λ m₁ m₂ ⟨x₁, s₁, hx₁, hs₁, h₁⟩ ⟨x₂, s₂, hx₂, hs₂, h₂⟩, ⟨s₁ * x₂ + s₂ * x₁, s₁ * s₂, is_submodule.add (is_submodule.smul _ hx₂) (is_submodule.smul _ hx₁), is_submonoid.mul_mem hs₁ hs₂, by rw [← h₁, ← h₂]; refl⟩, smul := λ c m ⟨x, s, hx, hs, h⟩, quotient.induction_on c $ λ ⟨cr, cs, ch⟩, ⟨cr * x, cs * s, is_submodule.smul _ hx, is_submonoid.mul_mem ch hs, by rw [← h]; refl⟩ } instance localization.is_submonoid.of_comm_ring : is_submonoid (quotient.mk '' S : set (α /ᵣ I)) := { one_mem := ⟨1, is_submonoid.one_mem S, rfl⟩, mul_mem := λ x y, quotient.induction_on₂ x y $ λ m n ⟨mw, hms, hm⟩ ⟨nw, hns, hn⟩, ⟨mw * nw, is_submonoid.mul_mem hms hns, by rw [← hm, ← hn]; refl⟩ } private def to_be_named_aux1 : α × S → (α /ᵣ I) [1/(S ₑ)] := λ x, ⟦⟨⟦x.1⟧, ⟦x.2.1⟧, x.2.1, x.2.2, rfl⟩⟧ private def to_be_named_aux2 : α [1/S] → (α /ᵣ I) [1/(S ₑ)] := quotient.lift (to_be_named_aux1 S I) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨w, hws, hw⟩, quotient.sound $ ⟨⟦w⟧, ⟨w, hws, rfl⟩, quotient.sound $ begin simp at hw ⊢,rw hw,end⟩ --set_option pp.notation false private def to_be_named_aux3 : α [1/S] /ᵣ (S⁻¹ I) → (α /ᵣ I) [1/(S ₑ)] := quotient.lift (to_be_named_aux2 S I) $ λ x y, quotient.induction_on₂ x y $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨v, w, hv, hw, h⟩, quotient.sound $ let ⟨t, hts, hsv⟩ := quotient.exact h in ⟨⟦w * t⟧, ⟨w * t, is_submonoid.mul_mem hw hts, rfl⟩, quotient.sound $ suffices (s₁ * r₂ - s₂ * r₁) * (w * t) ∈ I, begin simp at this ⊢, show (s₁ * r₂ + -(s₂ * r₁)) * (w * t) - 0 ∈ I, simp [this], end, have (-(s₁ * s₂ * v) + w * (s₂ * r₁ + -(s₁ * r₂))) * t = 0, by simpa using hsv, calc (s₁ * r₂ - s₂ * r₁) * (w * t) = (-(s₁ * s₂ * v) + w * (s₂ * r₁ + -(s₁ * r₂))) * t + (s₁ * r₂ - s₂ * r₁) * (w * t) : by simp [this] ... = (-s₁ * s₂ * t) * v : by ring ... ∈ I : is_submodule.smul _ hv⟩ private lemma to_be_named_aux35 : (1:α [1/S]) = ⟦⟨1, 1, is_submonoid.one_mem S⟩⟧ := rfl private def to_be_named_aux4 : is_ring_hom (to_be_named_aux3 S I) := { map_add := λ x y, quotient.induction_on₂ x y $ λ m n, quotient.induction_on₂ m n $ λ ⟨p, q, r⟩ ⟨s, t, u⟩, by simp [is_ideal.coset_eq, to_be_named_aux3, to_be_named_aux2, to_be_named_aux1, localization.mk_eq], map_mul := λ x y, quotient.induction_on₂ x y $ λ m n, quotient.induction_on₂ m n $ λ ⟨p, q, r⟩ ⟨s, t, u⟩, by simp [is_ideal.coset_eq, to_be_named_aux3, to_be_named_aux2, to_be_named_aux1, localization.mk_eq], map_one := by simp [is_ideal.coset_eq, to_be_named_aux3, to_be_named_aux2, to_be_named_aux1, localization.mk_eq]; rw to_be_named_aux35; rw quotient.lift_beta; simp } local attribute [instance] to_be_named_aux4 local attribute [instance] is_ring_hom.ker.is_ideal instance deus : comm_ring (α [1/S] /ᵣ (S⁻¹ I)) := by apply_instance instance salva : module (α [1/S] /ᵣ (S⁻¹ I)) (α [1/S] /ᵣ (S⁻¹ I)) := ring.to_module instance me : is_submodule (is_ring_hom.ker (to_be_named_aux3 S I)) := is_ring_hom.ker.is_submodule (to_be_named_aux3 S I) private def to_be_named_aux5 : α [1/S] /ᵣ (S⁻¹ I) ≃ᵣ α [1/S] /ᵣ (S⁻¹ I) /ᵣ is_ring_hom.ker (to_be_named_aux3 S I) := { to_fun := quotient.mk, is_ring_hom := is_ideal.to_quotient _ _, inv_fun := quotient.lift (@id (α [1/S] /ᵣ (S⁻¹ I))) $ λ x y, quotient.induction_on₂ x y $ λ m n, quotient.induction_on₂ m n $ λ ⟨b, c, d⟩ ⟨e, f, g⟩ h, begin change _ - _ ∈ _ at h, simp [is_ideal.coset_eq, to_be_named_aux3, to_be_named_aux2, to_be_named_aux1, localization.mk_eq] at h, replace h := quotient.exact h, rcases h with ⟨r, s, h⟩, rcases s with ⟨p, q, hp⟩, rw ← hp at h, replace h := quotient.exact h, change _ - _ ∈ _ at h, apply quotient.sound, existsi p * (f * b - c * e), existsi p * (c * f), have hx : p * (f * b - c * e) ∈ I, { have aux : p * (f * b - c * e) = -((c * f * 0 + -(1 * (f * b + -(c * e)))) * p - 0), { ring }, rw aux, exact is_submodule.neg h }, existsi hx, existsi is_submonoid.mul_mem q (is_submonoid.mul_mem d g), apply quotient.sound, existsi (1:α), existsi is_submonoid.one_mem S, simp, ring end, left_inv := λ x, rfl, right_inv := λ x, quotient.induction_on x $ λ m, rfl } private def to_be_named_aux6 : ↥(is_ring_hom.im (to_be_named_aux3 S I)) ≃ᵣ (α /ᵣ I) [1/(S ₑ)] := { to_fun := subtype.val, is_ring_hom := subring.is_ring_hom _ _, inv_fun := λ x, ⟨x, quotient.induction_on x $ λ ⟨m, n, p, hp, hpn⟩, quotient.induction_on m $ begin intro q, existsi @is_ideal.mk' _ (localization.comm_ring _ _) _ _ ⟦(⟨q, p, hp⟩ : α × S)⟧, simp [to_be_named_aux3, to_be_named_aux2, to_be_named_aux1, localization.mk_eq], apply quotient.sound, existsi ⟦(1:α)⟧, split, { existsi (1:α), existsi is_submonoid.one_mem S, refl }, simp [hpn] end⟩, left_inv := λ x, by simp, right_inv := λ x, rfl } noncomputable def to_be_named : α [1/S] /ᵣ (S⁻¹ I) ≃ᵣ (α /ᵣ I) [1/(S ₑ)] := (to_be_named_aux5 S I).trans $ (first_isom _ _ $ to_be_named_aux3 S I).trans $ to_be_named_aux6 S I
theory AbstractLock_Lib imports Lib Lib_ProofRules begin definition "lock_acquire t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts' \<equiv> let v = lib_value \<sigma>\<^sub>L w; v' = v + 1 in if (2 dvd v) then (lib_update t w v' \<sigma>\<^sub>L \<sigma>\<^sub>C ts', (True, v)) else ((\<sigma>\<^sub>L ,\<sigma>\<^sub>C), (False, v))" definition "lock_release t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts' \<equiv> let v = lib_value \<sigma>\<^sub>L w; v' = v + 1 in lib_write t True w v' \<sigma>\<^sub>L \<sigma>\<^sub>C ts'" definition "lock_acquire_step t x \<sigma>\<^sub>L \<sigma>\<^sub>C \<sigma>\<^sub>L' \<sigma>\<^sub>C' res ver \<equiv> \<exists> w ts' . w \<in> lib_visible_writes \<sigma>\<^sub>L t x \<and> w \<notin> lib_covered \<sigma>\<^sub>L \<and> lib_valid_fresh_ts \<sigma>\<^sub>L w ts' \<and> \<sigma>\<^sub>L' = fst(fst(lock_acquire t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts')) \<and> \<sigma>\<^sub>C' = snd(fst(lock_acquire t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts')) \<and> res = fst(snd(lock_acquire t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts')) \<and> ver = snd(snd(lock_acquire t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts'))" definition "lock_release_step t x \<sigma>\<^sub>L \<sigma>\<^sub>C \<sigma>\<^sub>L' \<sigma>\<^sub>C' \<equiv> \<exists> w ts' . w \<in> lib_visible_writes \<sigma>\<^sub>L t x \<and> w \<notin> lib_covered \<sigma>\<^sub>L \<and> lib_valid_fresh_ts \<sigma>\<^sub>L w ts' \<and> \<sigma>\<^sub>L' = lock_release t w \<sigma>\<^sub>L \<sigma>\<^sub>C ts' \<and> \<sigma>\<^sub>C' = \<sigma>\<^sub>C" abbreviation Lock_acquire_abbr:: " surrey_state \<Rightarrow> lib_state \<Rightarrow> T \<Rightarrow> L \<Rightarrow> surrey_state \<Rightarrow> lib_state \<Rightarrow> bool \<Rightarrow> V \<Rightarrow> bool" ("[_ _ _ LOCKACQ(_) _ _ _ _]") where "[\<sigma>\<^sub>C \<sigma>\<^sub>L t LOCKACQ(x) \<sigma>\<^sub>C' \<sigma>\<^sub>L' r v] \<equiv> lock_acquire_step t x \<sigma>\<^sub>L \<sigma>\<^sub>C \<sigma>\<^sub>L' \<sigma>\<^sub>C' r v" abbreviation Lock_rel_abbr:: " surrey_state \<Rightarrow> lib_state \<Rightarrow> T \<Rightarrow> L \<Rightarrow> lib_state \<Rightarrow> surrey_state \<Rightarrow> bool" ("[_ _ _ LOCKREL(_) _ _ ]") where "[\<sigma>\<^sub>C \<sigma>\<^sub>L t LOCKREL(x) \<sigma>\<^sub>L' \<sigma>\<^sub>C'] \<equiv> lock_release_step t x \<sigma>\<^sub>L \<sigma>\<^sub>C \<sigma>\<^sub>L' \<sigma>\<^sub>C'" definition "lib_covered_val \<sigma> l v \<equiv> (\<exists> ts . ts \<in> lib_writes_on \<sigma> l \<and> lib_value \<sigma> ts = v) \<and> (\<forall> ts . ts \<in> lib_writes_on \<sigma> l \<and> ts \<notin> lib_covered \<sigma> \<longrightarrow> lib_value \<sigma> ts > v)" abbreviation l_covered_val_abbr:: "nat \<Rightarrow> nat \<Rightarrow> lib_state \<Rightarrow> bool" ("cvv[lib(_), _] _" [100, 100, 100]) where "cvv[lib(l), u] \<sigma> \<equiv> lib_covered_val \<sigma> l u" definition "even_not_covered_last ls x \<equiv> \<forall> w . w\<in>lib_writes_on ls x \<and> even (lib_value ls w) \<and> w\<notin>lib_covered ls \<longrightarrow> lib_lastWr ls x = w" definition "abslock_invs ls x \<equiv> even_not_covered_last ls x" lemmas invs_abs = even_not_covered_last_def lemma abslock_even_not_covered_last_inv: assumes "lib_wfs ls cs" and "wfs cs " and "even_not_covered_last ls x" and "lock_acquire_step t x ls cs ls' cs' res ver" shows "even_not_covered_last ls' x" using assms apply(simp add: even_not_covered_last_def abslock_invs_def) apply(intro conjI impI allI, elim conjE) apply(case_tac "res = False", simp) apply(simp add: invs_abs lock_acquire_step_def lock_acquire_def) apply auto[1] apply simp apply(subgoal_tac "a = x", simp) defer apply(simp add: lib_writes_on_def) apply(simp add: lock_acquire_step_def lock_acquire_def ) apply(elim exE conjE) apply(case_tac "even (lib_value ls (aa, ba))", simp_all) apply(simp add: lib_update_def all_updates_l lib_writes_on_def lib_value_def) apply safe apply(simp add: lib_visible_writes_def) apply (simp add: lib_writes_on_def) apply(simp add: lib_visible_writes_def) apply (simp add: lib_writes_on_def) apply(simp add: lib_visible_writes_def lib_writes_on_def) apply clarsimp apply(simp add: lib_visible_writes_def lib_writes_on_def) defer apply(simp add: lib_visible_writes_def lib_writes_on_def lib_lastWr_def lib_valid_fresh_ts_def) proof - fix b :: rat and aa :: nat and ba :: rat and ts' :: rat assume a1: "even (lib_val (lib_mods ls (x, ba)))" assume "ver = lib_val (lib_mods ls (x, ba))" assume a2: "aa = x \<and> (aa, ba) \<in> lib_writes ls \<and> tst (lib_thrView ls t x) \<le> ba" assume a3: "even (lib_val (if b = ts' then \<lparr>lib_val = Suc (lib_val (lib_mods ls (aa, ba))), lib_rel = True\<rparr> else lib_mods ls (x, b)))" assume a4: "\<forall>b. (x, b) \<in> lib_writes ls \<and> even (lib_val (lib_mods ls (x, b))) \<and> (x, b) \<notin> lib_covered ls \<longrightarrow> Max (tst ` {w. var w = x \<and> w \<in> lib_writes ls}) = b" assume a5: "(x, ba) \<notin> lib_covered ls" assume a6: "(x, b) \<in> lib_writes ls" assume a7: "b \<noteq> ba" assume a8: "(x, b) \<notin> lib_covered ls" have "Max (tst ` {p. var p = x \<and> p \<in> lib_writes ls}) = ba" using a5 a4 a2 a1 by meson then have "b = ts'" using a8 a7 a6 a4 a3 by auto then show "Max (tst ` {w. var w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)}) = b" using a3 a2 a1 by force next fix b :: rat and aa :: nat and ba :: rat and ts' :: rat assume a1: "aa = x \<and> (aa, ba) \<in> lib_writes ls \<and> tst (lib_thrView ls t x) \<le> ba" assume a2: "b \<noteq> ba" assume a3: "(x, b) \<in> lib_writes ls" assume a4: "(x, ba) \<notin> lib_covered ls" assume "ver = lib_val (lib_mods ls (x, ba))" assume a5: "(x, b) \<notin> lib_covered ls" assume a6: "even (lib_val (lib_mods ls (x, ba)))" assume a7: "even (lib_val (if b = ts' then \<lparr>lib_val = Suc (lib_val (lib_mods ls (aa, ba))), lib_rel = True\<rparr> else lib_mods ls (x, b)))" assume a8: "\<forall>b. (x, b) \<in> lib_writes ls \<and> even (lib_val (lib_mods ls (x, b))) \<and> (x, b) \<notin> lib_covered ls \<longrightarrow> lib_lastWr ls x = (x, b)" then have "lib_lastWr ls x = (x, ba)" using a6 a4 a1 by blast then have "b = ts' \<or> (x, b) = (x, ba)" using a8 a7 a5 a3 by presburger then show "lib_lastWr (ls\<lparr>lib_thrView := (lib_thrView ls) (t := ts_oride ((lib_thrView ls t)(x := (x, ts'))) (lib_modView ls (x, ba) LVARS)), lib_modView := (lib_modView ls) ((x, ts') := (lib_modView ls (x, ts')) (CVARS := ts_oride (thrView cs t) (lib_modView ls (x, ba) CVARS), LVARS := ts_oride ((lib_thrView ls t)(x := (x, ts'))) (lib_modView ls (x, ba) LVARS))), lib_mods := (lib_mods ls) ((x, ts') := \<lparr>lib_val = Suc (lib_val (lib_mods ls (x, ba))), lib_rel = True\<rparr>), lib_writes := insert (x, ts') (lib_writes ls), lib_covered := insert (x, ba) (lib_covered ls)\<rparr>) x = (x, b)" using a7 a6 a2 a1 by simp qed lemma lock_release_last: "lib_wfs ls cs \<Longrightarrow> ls' = lock_release t (aa, ba) ls cs ts' \<Longrightarrow> lib_valid_fresh_ts ls (aa, ba) ts' \<Longrightarrow> (aa, ba) = lib_lastWr ls x \<Longrightarrow> (aa, ts') = lib_lastWr ls' aa" apply(simp add:lock_release_def lib_lastWr_def lib_writes_on_def tst_def var_def) apply(simp add: lib_write_def all_updates_l lib_valid_fresh_ts_def) apply(elim conjE) apply(subgoal_tac "ts'>ba") defer apply blast apply(subgoal_tac "{w. fst w = x \<and> (w = (x, ts') \<or> w \<in> lib_writes ls)} = {w. fst w = x \<and> w \<in> lib_writes ls} \<union> {(x,ts')}", simp) apply(case_tac "ts'\<in>(snd ` {w. fst w = x \<and> w \<in> lib_writes ls})") apply (smt image_iff less_imp_neq lib_writes_on_def mem_Collect_eq tst_def var_def) apply(subgoal_tac "finite {w. fst w = x \<and> w \<in> lib_writes ls}") apply (smt Max_in Max_less_iff empty_iff finite_imageI finite_insert infinite_growing insertE insertI1) apply(simp add: lib_wfs_def) apply (simp add: lib_writes_on_def var_def) apply(case_tac "ts'\<in>(snd ` {w. fst w = x \<and> w \<in> lib_writes ls})") apply auto[1] apply(subgoal_tac "finite {w. fst w = x \<and> w \<in> lib_writes ls}") apply simp apply auto[1] apply(simp add: lib_wfs_def) by (simp add: lib_writes_on_def var_def) lemma abslock_release_even_not_covered_last_inv: assumes "lib_wfs ls cs" and "wfs cs " and "even_not_covered_last ls x" and "[lib(x) =\<^sub>t u] ls" and "odd u" and "lock_release_step t x ls cs ls' cs'" shows "even_not_covered_last ls' x" using assms apply(simp add: even_not_covered_last_def lock_release_step_def) apply(intro allI impI, elim exE conjE) apply(subgoal_tac "(aa, ba) = lib_lastWr ls x") defer apply(subgoal_tac "aa = x", simp) apply (simp add: lib_dobs_visible_writes_last) apply(simp add: lib_visible_writes_def lib_writes_on_def) apply(subgoal_tac "lib_value ls (aa, ba) = u") defer using lib_dobs_visible_writes apply blast apply(subgoal_tac "(aa, ts') = lib_lastWr ls' aa") defer using lock_release_last apply blast apply(subgoal_tac "aa = x \<and> a = x") defer apply(simp add: lib_visible_writes_def lib_writes_on_def lib_lastWr_def) apply(case_tac "b = ts'", simp_all) apply(simp add: lib_lastWr_def lock_release_def lib_value_def lib_writes_on_def) apply(simp add: var_def tst_def lib_visible_writes_def) apply(simp add: lib_write_def all_updates_l) done end
lemma LIMSEQ_Suc: "f \<longlonglongrightarrow> l \<Longrightarrow> (\<lambda>n. f (Suc n)) \<longlonglongrightarrow> l"
module Hedgehog.Internal.Runner import Data.Colist import Data.Cotree import Data.IORef import Data.List import Hedgehog.Internal.Config import Hedgehog.Internal.Gen import Hedgehog.Internal.Options import Hedgehog.Internal.Property import Hedgehog.Internal.Range import Hedgehog.Internal.Report import Hedgehog.Internal.Seed import Hedgehog.Internal.Terminal import System %default total public export TestRes : Type TestRes = (Either Failure (), Journal) -------------------------------------------------------------------------------- -- Shrinking -------------------------------------------------------------------------------- -- Shrinking shrink : Monad m => Nat -> Coforest a -> b -> (Nat -> a -> m (Maybe b)) -> m b shrink _ [] b _ = pure b shrink 0 _ b _ = pure b shrink (S k) (t :: ts) b f = do Just b2 <- f (S k) t.value | Nothing => shrink k ts b f shrink k t.forest b2 f takeSmallest : Monad m => Size -> Seed -> ShrinkLimit -> (Progress -> m ()) -> Cotree TestRes -> m Result takeSmallest si se (MkTagged slimit) updateUI t = do res <- run 0 t.value if isFailure res then shrink slimit t.forest res runMaybe else pure res where -- calc number of shrinks from the remaining -- allowed numer and the shrink limit calcShrinks : Nat -> ShrinkCount calcShrinks rem = MkTagged $ (slimit `minus` rem) + 1 run : ShrinkCount -> TestRes -> m Result run shrinks t = case t of (Left $ MkFailure err diff, MkJournal logs) => let fail = mkFailure si se shrinks Nothing err diff (reverse logs) in updateUI (Shrinking fail) $> Failed fail (Right x, _) => pure OK runMaybe : Nat -> TestRes -> m (Maybe Result) runMaybe shrinksLeft testRes = do res <- run (calcShrinks shrinksLeft) testRes if isFailure res then pure (Just res) else pure Nothing -------------------------------------------------------------------------------- -- Test Runners -------------------------------------------------------------------------------- -- main test runner checkReport : Monad m => PropertyConfig -> Size -> Seed -> PropertyT () -> (Report Progress -> m ()) -> m (Report Result) checkReport cfg si0 se0 test updateUI = let (conf, MkTagged numTests) = unCriteria cfg.terminationCriteria in loop numTests 0 si0 se0 neutral conf where loop : Nat -> TestCount -> Size -> Seed -> Coverage CoverCount -> Maybe Confidence -> m (Report Result) loop n tests si se cover conf = do updateUI (MkReport tests cover Running) case n of 0 => -- required number of tests run pure $ report False tests si se cover conf S k => if abortEarly cfg.terminationCriteria tests cover conf then -- at this point we know that enough -- tests have been run due to early termination pure $ report True tests si se cover conf else -- run another test let (s0,s1) = split se tr = runGen si s0 $ runTestT test nextSize = if si < maxSize then (si + 1) else 0 in case tr.value of -- the test failed, so we abort and shrink (Left x, _) => let upd = updateUI . MkReport (tests+1) cover in map (MkReport (tests+1) cover) $ takeSmallest si se cfg.shrinkLimit upd tr -- the test succeeded, so we accumulate results -- and loop once more (Right x, journal) => let cover1 = journalCoverage journal <+> cover in loop k (tests + 1) nextSize s1 cover1 conf checkTerm : HasIO io => Terminal -> UseColor -> Maybe PropertyName -> Size -> Seed -> Property -> io (Report Result) checkTerm term color name si se prop = do result <- checkReport {m = io} prop.config si se prop.test $ \prog => if multOf100 prog.tests then let ppprog = renderProgress color name prog in case prog.status of Running => putTmp term ppprog Shrinking _ => putTmp term ppprog else pure () putOut term (renderResult color name result) pure result checkWith : HasIO io => Terminal -> UseColor -> Maybe PropertyName -> Property -> io (Report Result) checkWith term color name prop = initSMGen >>= \se => checkTerm term color name 0 se prop ||| Check a property. export checkNamed : HasIO io => PropertyName -> Property -> io Bool checkNamed name prop = do color <- detectColor term <- console rep <- checkWith term color (Just name) prop pure $ rep.status == OK ||| Check a property. export check : HasIO io => Property -> io Bool check prop = do color <- detectColor term <- console rep <- checkWith term color Nothing prop pure $ rep.status == OK ||| Check a property using a specific size and seed. export recheck : HasIO io => Size -> Seed -> Property -> io () recheck si se prop = do color <- detectColor term <- console _ <- checkTerm term color Nothing si se (withTests 1 prop) pure () checkGroupWith : Terminal -> UseColor -> List (PropertyName, Property) -> IO Summary checkGroupWith term color = run neutral where run : Summary -> List (PropertyName, Property) -> IO Summary run s [] = pure s run s ((pn,p) :: ps) = do rep <- checkWith term color (Just pn) p run (s <+> fromResult rep.status) ps export checkGroup : HasIO io => Group -> io Bool checkGroup (MkGroup group props) = do term <- console putOut term $ "━━━ " ++ unTag group ++ " ━━━" color <- detectColor summary <- liftIO $ checkGroupWith term color props putOut term (renderSummary color summary) pure $ summary.failed == 0 ||| Simple test runner. ||| ||| Use this in a `main` function in order to test a list of ||| property groups. The runner will take into account several ||| command line arguments in order to adjust the number of ||| tests to be run for each property, the maximal number of ||| shrinks and the confidence value to use. ||| ||| ```idris example ||| main : IO () ||| main = test myGroups ||| ``` ||| ||| The resulting executable can then be run as follows: ||| ||| ```sh ||| build/exec/runTests -n 1000 ||| ``` ||| ||| It will fail with an exit code of 1 if at least one property ||| fails. export test : HasIO io => List Group -> io () test gs = do args <- getArgs Right c <- pure $ applyArgs args | Left errs => do putStrLn "Errors when parsing command line args:" traverse_ putStrLn errs exitFailure if c.printHelp then putStrLn info >> exitSuccess else let gs2 = map (applyConfig c) gs in do res <- foldlM (\b,g => map (b &&) (checkGroup g)) True gs2 if res then exitSuccess else putStrLn "\n\nSome tests failed" >> exitFailure
Formal statement is: lemma holomorphic_nonconstant: assumes holf: "f holomorphic_on S" and "open S" "\<xi> \<in> S" "deriv f \<xi> \<noteq> 0" shows "\<not> f constant_on S" Informal statement is: If $f$ is a holomorphic function on an open set $S$ and $f'(\xi) \neq 0$ for some $\xi \in S$, then $f$ is not constant on $S$.
[STATEMENT] lemma LIM_Uniq: "\<exists>\<^sub>\<le>\<^sub>1L::'b::t2_space. f \<midarrow>a\<rightarrow> L" for a :: "'a::perfect_space" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>\<^sub>\<le>\<^sub>1 L. f \<midarrow>a\<rightarrow> L [PROOF STEP] by (auto simp add: Uniq_def LIM_unique)
function Corr = tapas_Cov2Corr(Cov) % Converts a covariance matrix into a correlation matrix % % -------------------------------------------------------------------------------------------------- % Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ % % This file is part of the HGF toolbox, which is released under the terms of the GNU General Public % Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL % (either version 3 or, at your option, any later version). For further details, see the file % COPYING or <http://www.gnu.org/licenses/>. % Check if Cov is symmetric if any(any(Cov'~=Cov)) error('tapas:hgf:Cov2Corr:MatNotSymm', 'Input matrix is not symmetric.'); end % Check if Cov is positive semi-definite if any(isinf(Cov(:))) || any(isnan(Cov(:))) || any(eig(Cov)<0) error('tapas:hgf:Cov2Corr:MatNotPosDef', 'Input matrix is not positive semi-definite.'); end sdev = sqrt(diag(Cov)); Norm = sdev * sdev'; Corr = Cov./Norm; return;
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Algebra.Ring.Base where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Equiv.HalfAdjoint open import Cubical.Foundations.HLevels open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.Transport open import Cubical.Foundations.SIP open import Cubical.Data.Sigma open import Cubical.Structures.Axioms open import Cubical.Structures.Auto open import Cubical.Structures.Macro open import Cubical.Algebra.Semigroup open import Cubical.Algebra.Monoid open import Cubical.Algebra.AbGroup open import Cubical.Reflection.StrictEquiv open Iso private variable ℓ ℓ' : Level record IsRing {R : Type ℓ} (0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R) : Type ℓ where constructor isring field +IsAbGroup : IsAbGroup 0r _+_ -_ ·IsMonoid : IsMonoid 1r _·_ dist : (x y z : R) → (x · (y + z) ≡ (x · y) + (x · z)) × ((x + y) · z ≡ (x · z) + (y · z)) -- This is in the Agda stdlib, but it's redundant -- zero : (x : R) → (x · 0r ≡ 0r) × (0r · x ≡ 0r) open IsAbGroup +IsAbGroup public renaming ( assoc to +Assoc ; identity to +Identity ; lid to +Lid ; rid to +Rid ; inverse to +Inv ; invl to +Linv ; invr to +Rinv ; comm to +Comm ; isSemigroup to +IsSemigroup ; isMonoid to +IsMonoid ; isGroup to +IsGroup ) open IsMonoid ·IsMonoid public renaming ( assoc to ·Assoc ; identity to ·Identity ; lid to ·Lid ; rid to ·Rid ; isSemigroup to ·IsSemigroup ) hiding ( is-set ) -- We only want to export one proof of this ·Rdist+ : (x y z : R) → x · (y + z) ≡ (x · y) + (x · z) ·Rdist+ x y z = dist x y z .fst ·Ldist+ : (x y z : R) → (x + y) · z ≡ (x · z) + (y · z) ·Ldist+ x y z = dist x y z .snd record RingStr (A : Type ℓ) : Type (ℓ-suc ℓ) where constructor ringstr field 0r : A 1r : A _+_ : A → A → A _·_ : A → A → A -_ : A → A isRing : IsRing 0r 1r _+_ _·_ -_ infix 8 -_ infixl 7 _·_ infixl 6 _+_ open IsRing isRing public Ring : Type (ℓ-suc ℓ) Ring = TypeWithStr _ RingStr isSetRing : (R : Ring {ℓ}) → isSet ⟨ R ⟩ isSetRing R = R .snd .RingStr.isRing .IsRing.·IsMonoid .IsMonoid.isSemigroup .IsSemigroup.is-set makeIsRing : {R : Type ℓ} {0r 1r : R} {_+_ _·_ : R → R → R} { -_ : R → R} (is-setR : isSet R) (+-assoc : (x y z : R) → x + (y + z) ≡ (x + y) + z) (+-rid : (x : R) → x + 0r ≡ x) (+-rinv : (x : R) → x + (- x) ≡ 0r) (+-comm : (x y : R) → x + y ≡ y + x) (r+-assoc : (x y z : R) → x · (y · z) ≡ (x · y) · z) (·-rid : (x : R) → x · 1r ≡ x) (·-lid : (x : R) → 1r · x ≡ x) (·-rdist-+ : (x y z : R) → x · (y + z) ≡ (x · y) + (x · z)) (·-ldist-+ : (x y z : R) → (x + y) · z ≡ (x · z) + (y · z)) → IsRing 0r 1r _+_ _·_ -_ makeIsRing is-setR assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-lid ·-rdist-+ ·-ldist-+ = isring (makeIsAbGroup is-setR assoc +-rid +-rinv +-comm) (makeIsMonoid is-setR ·-assoc ·-rid ·-lid) λ x y z → ·-rdist-+ x y z , ·-ldist-+ x y z makeRing : {R : Type ℓ} (0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R) (is-setR : isSet R) (+-assoc : (x y z : R) → x + (y + z) ≡ (x + y) + z) (+-rid : (x : R) → x + 0r ≡ x) (+-rinv : (x : R) → x + (- x) ≡ 0r) (+-comm : (x y : R) → x + y ≡ y + x) (+-assoc : (x y z : R) → x · (y · z) ≡ (x · y) · z) (·-rid : (x : R) → x · 1r ≡ x) (·-lid : (x : R) → 1r · x ≡ x) (·-rdist-+ : (x y z : R) → x · (y + z) ≡ (x · y) + (x · z)) (·-ldist-+ : (x y z : R) → (x + y) · z ≡ (x · z) + (y · z)) → Ring makeRing 0r 1r _+_ _·_ -_ is-setR assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-lid ·-rdist-+ ·-ldist-+ = _ , ringstr 0r 1r _+_ _·_ -_ (makeIsRing is-setR assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-lid ·-rdist-+ ·-ldist-+ ) record RingEquiv (R : Ring {ℓ}) (S : Ring {ℓ'}) (e : ⟨ R ⟩ ≃ ⟨ S ⟩) : Type (ℓ-max ℓ ℓ') where constructor ringequiv private module R = RingStr (snd R) module S = RingStr (snd S) field pres1 : equivFun e R.1r ≡ S.1r isHom+ : (x y : ⟨ R ⟩) → equivFun e (x R.+ y) ≡ equivFun e x S.+ equivFun e y isHom· : (x y : ⟨ R ⟩) → equivFun e (x R.· y) ≡ equivFun e x S.· equivFun e y record RingHom (R S : Ring {ℓ}) : Type ℓ where constructor ringhom private module R = RingStr (snd R) module S = RingStr (snd S) field f : ⟨ R ⟩ → ⟨ S ⟩ pres1 : f R.1r ≡ S.1r isHom+ : (x y : ⟨ R ⟩) → f (x R.+ y) ≡ f x S.+ f y isHom· : (x y : ⟨ R ⟩) → f (x R.· y) ≡ f x S.· f y _$_ : {R S : Ring {ℓ}} → (φ : RingHom R S) → (x : ⟨ R ⟩) → ⟨ S ⟩ φ $ x = RingHom.f φ x module RingΣTheory {ℓ} where RawRingStructure = λ (X : Type ℓ) → (X → X → X) × X × (X → X → X) RawRingEquivStr = AutoEquivStr RawRingStructure rawRingUnivalentStr : UnivalentStr _ RawRingEquivStr rawRingUnivalentStr = autoUnivalentStr RawRingStructure RingAxioms : (R : Type ℓ) (s : RawRingStructure R) → Type ℓ RingAxioms R (_+_ , 1r , _·_) = AbGroupΣTheory.AbGroupAxioms R _+_ × IsMonoid 1r _·_ × ((x y z : R) → (x · (y + z) ≡ (x · y) + (x · z)) × ((x + y) · z ≡ (x · z) + (y · z))) RingStructure : Type ℓ → Type ℓ RingStructure = AxiomsStructure RawRingStructure RingAxioms RingΣ : Type (ℓ-suc ℓ) RingΣ = TypeWithStr ℓ RingStructure RingEquivStr : StrEquiv RingStructure ℓ RingEquivStr = AxiomsEquivStr RawRingEquivStr RingAxioms isPropRingAxioms : (R : Type ℓ) (s : RawRingStructure R) → isProp (RingAxioms R s) isPropRingAxioms R (_+_ , 1r , _·_) = isProp× (AbGroupΣTheory.isPropAbGroupAxioms R _+_) (isPropΣ (isPropIsMonoid 1r _·_) λ R → isPropΠ3 λ _ _ _ → isProp× (IsSemigroup.is-set (R .IsMonoid.isSemigroup) _ _) (IsSemigroup.is-set (R .IsMonoid.isSemigroup) _ _)) Ring→RingΣ : Ring → RingΣ Ring→RingΣ (R , ringstr 0r 1r _+_ _·_ -_ (isring +-isAbelianGroup ·-isMonoid dist)) = ( R , (_+_ , 1r , _·_) , AbGroupΣTheory.AbGroup→AbGroupΣ (_ , abgroupstr _ _ _ +-isAbelianGroup) .snd .snd , ·-isMonoid , dist ) RingΣ→Ring : RingΣ → Ring RingΣ→Ring (_ , (y1 , y2 , y3) , z , w1 , w2) = _ , ringstr _ y2 y1 y3 _ (isring (AbGroupΣTheory.AbGroupΣ→AbGroup (_ , _ , z ) .snd .AbGroupStr.isAbGroup) w1 w2) RingIsoRingΣ : Iso Ring RingΣ RingIsoRingΣ = iso Ring→RingΣ RingΣ→Ring (λ _ → refl) (λ _ → refl) ringUnivalentStr : UnivalentStr RingStructure RingEquivStr ringUnivalentStr = axiomsUnivalentStr _ isPropRingAxioms rawRingUnivalentStr RingΣPath : (R S : RingΣ) → (R ≃[ RingEquivStr ] S) ≃ (R ≡ S) RingΣPath = SIP ringUnivalentStr RingEquivΣ : (R S : Ring) → Type ℓ RingEquivΣ R S = Ring→RingΣ R ≃[ RingEquivStr ] Ring→RingΣ S RingIsoΣPath : {R S : Ring} → Iso (Σ[ e ∈ ⟨ R ⟩ ≃ ⟨ S ⟩ ] RingEquiv R S e) (RingEquivΣ R S) fun RingIsoΣPath (e , ringequiv h1 h2 h3) = e , h2 , h1 , h3 inv RingIsoΣPath (e , h1 , h2 , h3) = e , ringequiv h2 h1 h3 rightInv RingIsoΣPath _ = refl leftInv RingIsoΣPath _ = refl RingPath : (R S : Ring) → (Σ[ e ∈ ⟨ R ⟩ ≃ ⟨ S ⟩ ] RingEquiv R S e) ≃ (R ≡ S) RingPath R S = Σ[ e ∈ ⟨ R ⟩ ≃ ⟨ S ⟩ ] RingEquiv R S e ≃⟨ strictIsoToEquiv RingIsoΣPath ⟩ RingEquivΣ R S ≃⟨ RingΣPath _ _ ⟩ Ring→RingΣ R ≡ Ring→RingΣ S ≃⟨ isoToEquiv (invIso (congIso RingIsoRingΣ)) ⟩ R ≡ S ■ RingPath : (R S : Ring {ℓ}) → (Σ[ e ∈ ⟨ R ⟩ ≃ ⟨ S ⟩ ] RingEquiv R S e) ≃ (R ≡ S) RingPath = RingΣTheory.RingPath isPropIsRing : {R : Type ℓ} (0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R) → isProp (IsRing 0r 1r _+_ _·_ -_) isPropIsRing 0r 1r _+_ _·_ -_ (isring RG RM RD) (isring SG SM SD) = λ i → isring (isPropIsAbGroup _ _ _ RG SG i) (isPropIsMonoid _ _ RM SM i) (isPropDistr RD SD i) where isSetR : isSet _ isSetR = RM .IsMonoid.isSemigroup .IsSemigroup.is-set isPropDistr : isProp ((x y z : _) → ((x · (y + z)) ≡ ((x · y) + (x · z))) × (((x + y) · z) ≡ ((x · z) + (y · z)))) isPropDistr = isPropΠ3 λ _ _ _ → isProp× (isSetR _ _) (isSetR _ _) -- Rings have an abelian group and a monoid Ring→AbGroup : Ring {ℓ} → AbGroup {ℓ} Ring→AbGroup (A , ringstr _ _ _ _ _ R) = A , abgroupstr _ _ _ (IsRing.+IsAbGroup R) Ring→Monoid : Ring {ℓ} → Monoid {ℓ} Ring→Monoid (A , ringstr _ _ _ _ _ R) = monoid _ _ _ (IsRing.·IsMonoid R)
In a rare change , Milligan 's run on the title starts with John living in domestic bliss with a nurse , Phoebe . Over the course of the first storyline , several new characters are introduced , including Epiphany Greaves , the alchemist daughter of a notorious London gangster , and Julian , a Babylonian demon . Over the course of the run , John dealt with a demon taking revenge on people involved in the Liverpool dockers ' strike gone insane and sought help from Shade , The Changing Man , after chopping off his own thumb , seen Phoebe die at the hands of Julian , and traveled to India to try to find a way of saving her . Following this , he realised that he was in love with Epiphany , and married her in the 275th issue . However , the events of this wedding turned Constantine 's niece Gemma against him , due to the Demon Constantine sexually assaulting her in the restroom . The strain of this traumatic incident turned her against John , and she enlisted the help of a coven of witches to kill him , which later came to a head when John was forced to fight off a brutal Demon summoned by them using John 's iconic trenchcoat to target him .
Formal statement is: lemma closed_injective_linear_image_eq: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes f: "linear f" "inj f" shows "(closed(image f s) \<longleftrightarrow> closed s)" Informal statement is: If $f$ is a linear injective map, then $f$ maps closed sets to closed sets.
% SPDX-FileCopyrightText: © 2021 Martin Michlmayr <[email protected]> % SPDX-License-Identifier: CC-BY-4.0 \setchapterimage[9.5cm]{images/stethoscope} \chapter{Community health} \labch{community-health} Community health and growth can be measured, for example through metrics, and dashboards can be used to display and monitor the data. \href{https://chaoss.community/}{Community Health Analytics Open Source Software} (CHAOSS) is a Linux Foundation project focused on creating analytics and metrics to help define community health. It has working groups that focus on different areas, including risk, evolution, and diversity and inclusion. \begin{kaobox}[frametitle=CHAOSS: the importance of community health] \href{https://chaoss.community/about/}{CHAOSS} gives several reasons for monitoring community health: \begin{quote} \begin{itemize} \itemsep 0.5em \item Open source contributors want to know where they should place their efforts and know that they are making an impact. \item Open source communities want to attract new members, ensure consistent quality, and reward valuable members. \item Open source companies want to know which communities to engage with, communicate the impact the organization has on the community, and evaluate the work of their employees within open source. \item Open source foundations want to identify and respond to community needs, evaluate the impact of their work, and promote communities. \end{itemize} \end{quote} \end{kaobox} There are various dashboards available to show metrics of open source projects. One is \href{https://cauldron.io/}{Cauldron}, which aggregates information from multiple collaboration platforms. Another is \href{https://bitergia.com/bitergia-analytics/}{Bitergia Analytics}, which is a project health dashboard that has been \href{https://bitergia.com/oss-foundations/}{adopted by a number of foundations} for the benefit of their member projects.
subroutine setmaxgain(freqoper) c******************************************************************* c PURPOSE: c set maximum gain parameter (giso) for use by ANTCAL c INPUT PARAMETERS: c freqoper = Operating Frequency c freqdesign= Design Frequency (=0=use Operating Frequency) c = in range .7 to 1.4 use as FreqRatio c thus fdesign=foper/FreqRatio c OUTPUT PARAMETERS: c******************************************************************* common /designfreq/ freqdesign common /ccirparm/ parm(20),z6,umax,vmax,giso, + modegain,gainmax(3,2),gainmaxb(30) iant=nint(parm(2)) ! type [1,2,...12] if(modegain.eq.0) then giso=parm(1) ! maximum gain else if(modegain.eq.1) then c interpolate on Frequency ratio and Operating frequency foper=freqoper ! set operating frequency if(foper.lt.2. .or. foper.gt.30.) foper=10. fdesign=freqdesign ! set design frequency c was this Frequency Ratio (.7 to 1.4) if(fdesign.ge..7 .and. fdesign.le.1.4)fdesign=foper/freqdesign if(fdesign.lt.2. .or. fdesign.gt.30.) fdesign=foper parm(5)=foper parm(8)=fdesign if(iant.eq.8) parm(6)=fdesign ! quadrant antenna giso=gainterp(gainmax,foper,fdesign,iant) else if(modegain.eq.2) then parm(5)=freqoper giso=gainterb(gainmaxb,freqoper) ! types 5,6,7,10 end if return end c----------------------------------------------------------------------
import for_mathlib.homotopy_category_pretriangulated import for_mathlib.abelian_category import category_theory.abelian.projective noncomputable theory open category_theory category_theory.limits category_theory.triangulated open homological_complex universes v u variables {A : Type u} [category.{v} A] [abelian A] namespace homotopy_category variables {ι : Type*} {c : complex_shape ι} local notation `𝒦` := homotopy_category A c /-- Say `c` is a complex shape on an index type `ι`. An object of `homotopy_category A c` is acyclic if the homology of this object is 0 at all indices `i : ι`. -/ class is_acyclic (X : 𝒦) : Prop := (cond [] : ∀ i, is_zero ((homotopy_category.homology_functor _ _ i).obj X)) lemma is_acyclic_of_iso {X Y : 𝒦} (e : X ≅ Y) [is_acyclic X] : is_acyclic Y := begin constructor, intros i, let e' : (homology_functor A c i).obj X ≅ (homology_functor A c i).obj Y := functor.map_iso _ e, apply is_zero_of_iso_of_zero _ e', apply is_acyclic.cond X i, end /-- An object of `homotopy_category A c` is "K-projective" if the only map from that object to any acyclic object is the zero map. -/ class is_K_projective (X : 𝒦) : Prop := (cond [] : ∀ (Y : 𝒦) [is_acyclic Y] (f : X ⟶ Y), f = 0) /-- A morphism in the homotopy category is a quasi-isomorphism if it induces isomorphisms on all homology groups. -/ class is_quasi_iso {X Y : 𝒦} (f : X ⟶ Y) : Prop := (cond [] : ∀ i, is_iso ((homotopy_category.homology_functor _ _ i).map f)) end homotopy_category namespace homotopy_category local notation `𝒦` := homotopy_category A (complex_shape.up ℤ) local notation `HH` := homotopy_category.homology_functor A (complex_shape.up ℤ) 0 /-- An object `(Cⁱ)` of `homotopy_category A ℤ↑` is bounded_by `n : ℕ` if the all the objects `Cⁱ` for `i ≥ n` in the complex are zero -/ def bounded_by (X : 𝒦) (n : ℤ) : Prop := ∀ i, n ≤ i → is_zero (X.as.X i) class is_bounded_above (X : 𝒦) : Prop := (cond [] : ∃ a : ℤ, X.bounded_by a) class is_uniformly_bounded_above {α : Type*} (X : α → 𝒦) : Prop := (cond [] : ∃ n : ℤ, ∀ a, (X a).bounded_by n) instance is_bounded_above_of_is_uniformly_bounded_above {α : Type*} (X : α → 𝒦) [is_uniformly_bounded_above X] (a) : is_bounded_above (X a) := begin obtain ⟨n,hn⟩ := is_uniformly_bounded_above.cond X, exact ⟨⟨n, hn a⟩⟩, end end homotopy_category variables (A) /-- The category `bounded_homotopy_category A` has objects the complexes indexed by `ℤ↑` which are bounded above, i.e. the objects in the complex are equal to zero for sufficiently large indices. Morphisms are homotopy classes of maps. -/ structure bounded_homotopy_category := (val : homotopy_category A (complex_shape.up ℤ)) [bdd : homotopy_category.is_bounded_above val]
[GOAL] 𝕜 : Type u_1 inst✝¹ : LinearOrderedField 𝕜 R : Type u_2 inst✝ : CommRing R abv : AbsoluteValue R 𝕜 ⊢ ∀ (x : R), (fun x y => ↑abv (y - x)) x x = 0 [PROOFSTEP] simp
-- @@stderr -- dtrace: failed to compile script test/unittest/bitfields/err.D_DECL_BFCONST.NegBitField.d: [D_DECL_BFCONST] line 18: positive integral constant expression expected as bit-field size
lemma filtermap_times_pos_at_right: fixes c::"'a::{linordered_field, linorder_topology}" assumes "c > 0" shows "filtermap (times c) (at_right p) = at_right (c * p)"
module SpecialArrays using Adapt using Base: @propagate_inbounds, @pure, @_inline_meta using Base: require_one_based_indexing, tail, unsafe_length using Compat using DocStringExtensions using Requires: @require using UnsafeArrays const NestedArray{V,M,N} = AbstractArray{<:AbstractArray{V,M},N} include("tuple.jl") include("util.jl") export inner_eltype, inner_ndims, inner_axes, inner_size, inner_length include("functions.jl") export SlicedArray, slice, align include("slicedarray.jl") export FlattenedArray, flatten include("flattenedarray.jl") export BatchedVector, batch, similarbatch include("batchedvector.jl") function __init__() @require Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" include("zygote.jl") end end # module
using FPRS using Test @testset "FPRS.jl" begin include("test-utilities.jl") include("test-densities.jl") include("test-projections.jl") include("test-loadElser.jl") end
A function $f$ is continuous at $x$ if and only if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x'$, if $|x' - x| < \delta$, then $|f(x') - f(x)| < \epsilon$.
A function $f$ is continuous at $x$ if and only if for every $\epsilon > 0$, there exists a $\delta > 0$ such that for all $x'$, if $|x' - x| < \delta$, then $|f(x') - f(x)| < \epsilon$.
/* dwt_undec.c * Paul Demorest, 2007/10 * * Undecimated wavelet transform and inverse. These * do the usual wavelet filter tree, but don't decimate * by 2 after each step. This makes the transform * translation-invariant (to translations which are * integer numbers of samples anyways). * * Ends up with n*log2(n) sized array, from size n input. * * Wavelet coeffs g and h need to be externally supplied. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_wavelet.h> /* Do one UDWT step on input data, out-of-place (original * data array is unaltered). * Vars: * in pointer to input data (n doubles) * outl pointer to low-pass output data (n doubles) * outh pointer to high-pass output data (n doubles) * n size of in/out * h Wavelet coeffs, low-pass (nc doubles) * g Wavelet coeffs, high-pass (nc doubles) * nc size of h/g * s scale (filters expand by 2^s) */ void udwt_forward_step(double *in, double *outl, double *outh, size_t n, const double h[], const double g[], size_t nc, int s) { int i,j,idx; /* Zero output array */ for (i=0; i<n; i++) { outl[i]=0.0; outh[i]=0.0; } /* Filter */ for (i=0; i<n; i++) { for (j=0; j<nc; j++) { idx = (i + (1<<s)*j) % n; outl[i] += h[j] * in[idx]; outh[i] += g[j] * in[idx]; } } } /* Inverse UDWT step similar to above. Remember to stay * consistent about which half contains h and which * contains g chunks! */ void udwt_inverse_step(double *inl, double *inh, double *out, size_t n, const double h[], const double g[], size_t nc, int s) { int i,j,idx; /* Zero output */ for (i=0; i<n; i++) { out[i]=0.0; } /* filter, add */ for (i=0; i<n; i++) { for (j=0; j<nc; j++) { idx = (i - (1<<s)*j) % n; out[i] += h[j] * inl[idx]; out[i] += g[j] * inh[idx]; } } /* Inverse needs a rescaling */ for (i=0; i<n; i++) { out[i] *= 0.5; } } /* Return integer log 2 of input. * Error if not a power of 2? */ static int log2i(int n) { int rv=0; while ((n>>rv)>1) { rv++; } return(rv); } /* Do a undec wavelet transform on input data n. * Vars: * in pointer to input data (n doubles) * out pointer to output data (n*log2(n) doubles) * n size of in * h Wavelet coeffs, high-pass (nc doubles) * g Wavelet coeffs, low-pass (nc doubles) * nc size of h/g * * This can be called using a GSL wavelet definition struct like: * gsl_wavelet *w; * (etc, init wavelet...) * dwt_undec_transform(in, &out, n, w->h1, w->g1, w->nc); */ int _dwt_undec_transform(double *in, double *out, size_t n, const double h[], const double g[], size_t nc) { /* Determine number of levels of decomp */ int nl=0; nl = log2i(n); /* maybe do some value checks on n, nl .. */ /* Temporary low-pass outputs */ double *tmp1 = (double *)malloc(sizeof(double)*n); double *tmp2 = (double *)malloc(sizeof(double)*n); /* Loop to do dwts */ int i; double *curi, *curol, *curoh, *swp; curi = in; curol = tmp1; curoh = out; for (i=0; i<nl; i++) { udwt_forward_step(curi, curol, curoh, n, h, g, nc, i); if (i==0) { curi=tmp2; } swp = curi; curi = curol; curol = swp; curoh = &(out[(i+1)*n]); } free(tmp1); free(tmp2); return(nl); } /* Inverse, similar to above, but switch in/out * This can be called using a GSL wavelet definition struct like: * gsl_wavelet *w; * (etc, init wavelet...) * dwt_undec_inverse(in, out, n, w->h2, w->g2, w->nc); */ int _dwt_undec_inverse(double *in, double *out, size_t n, const double h[], const double g[], size_t nc) { /* Determine number of levels of decomp */ int nl=0; nl = log2i(n); /* maybe do some value checks on n, nl .. */ /* Temporary low-pass outputs */ int i; double *tmp1 = (double *)malloc(sizeof(double)*n); double *tmp2 = (double *)malloc(sizeof(double)*n); for (i=0; i<n; i++) { tmp1[i]=0.0; } /* Loop to do dwts */ double *curil, *curih, *curo, *swp; curil = tmp1; curih = &in[(nl-1)*n]; curo = tmp2; for (i=nl-1; i>=0; i--) { udwt_inverse_step(curil, curih, curo, n, h, g, nc, i); swp = curil; curil = curo; curo = swp; curih = &in[(i-1)*n]; } /* We end up with final output in curil */ for (i=0; i<n; i++) { out[i] = curil[i]; } free(tmp1); free(tmp2); return(nl); } /* Wrappers using GSL wavelet definitions */ int dwt_undec_transform(double *in, double *out, size_t n, const gsl_wavelet *w) { return _dwt_undec_transform(in, out, n, w->h1, w->g1, w->nc); } int dwt_undec_inverse(double *in, double *out, size_t n, const gsl_wavelet *w) { return _dwt_undec_inverse(in, out, n, w->h2, w->g2, w->nc); }
(* This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_sort_nat_HSort2Sorts imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" datatype Heap = Node "Heap" "Nat" "Heap" | Nil fun le :: "Nat => Nat => bool" where "le (Z) y = True" | "le (S z) (Z) = False" | "le (S z) (S x2) = le z x2" fun ordered :: "Nat list => bool" where "ordered (nil2) = True" | "ordered (cons2 y (nil2)) = True" | "ordered (cons2 y (cons2 y2 xs)) = ((le y y2) & (ordered (cons2 y2 xs)))" fun hmerge :: "Heap => Heap => Heap" where "hmerge (Node z x2 x3) (Node x4 x5 x6) = (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else Node (hmerge (Node z x2 x3) x6) x5 x4)" | "hmerge (Node z x2 x3) (Nil) = Node z x2 x3" | "hmerge (Nil) y = y" (*fun did not finish the proof*) function toList :: "Heap => Nat list" where "toList (Node q y r) = cons2 y (toList (hmerge q r))" | "toList (Nil) = nil2" by pat_completeness auto fun hinsert :: "Nat => Heap => Heap" where "hinsert x y = hmerge (Node Nil x Nil) y" fun toHeap2 :: "Nat list => Heap" where "toHeap2 (nil2) = Nil" | "toHeap2 (cons2 y xs) = hinsert y (toHeap2 xs)" fun hsort2 :: "Nat list => Nat list" where "hsort2 x = toList (toHeap2 x)" theorem property0 : "ordered (hsort2 xs)" oops end
If $S$ is locally path-connected, then for every open set $v$ and every point $x \in v$, there exists an open set $u$ such that $x \in u \subseteq v$ and $u$ is path-connected.
Require Import maps. Set Implicit Arguments. Set Contextual Implicit. Inductive MapRep (Key Elt : Type) : Type := rEmpty : MapRep Key Elt | rItem : Key -> Elt -> MapRep Key Elt | rJoin : MapRep Key Elt -> MapRep Key Elt -> MapRep Key Elt | rLeaf : Map Key Elt -> MapRep Key Elt . Function join {Key Elt} (m1 m2 : Map Key Elt) : Map Key Elt := match m1, m2 with | mapEmpty, _ => m2 | _, mapEmpty => m1 | _, _ => m1 :* m2 end. Lemma join_sem : forall {K E} (m1 m2 : Map K E), m1 :* m2 ~= join m1 m2. Proof. intros. functional induction (join m1 m2). apply equivUnitL. apply equivUnit. apply equivRefl. Qed. Fixpoint unrep {K E} (r : MapRep K E) : Map K E := match r with | rEmpty => mapEmpty | rItem k v => k |-> v | rJoin l r => unrep l :* unrep r | rLeaf m => m end. Fixpoint simplRep {K E} (r : MapRep K E) : Map K E := match r with | rEmpty => mapEmpty | rItem k v => k |-> v | rJoin l r => join (simplRep l) (simplRep r) | rLeaf m => m end. Lemma simplValid {K E} (r : MapRep K E) : unrep r ~= simplRep r. induction r;try reflexivity. simpl. rewrite <- join_sem. apply equivJoin;assumption. Qed. Inductive MapZipper (Key Elt : Type) : Type := Here : MapZipper Key Elt | Left : forall {r : Map Key Elt}, MapZipper Key Elt -> MapZipper Key Elt | Right : forall {l : Map Key Elt}, MapZipper Key Elt -> MapZipper Key Elt . Fixpoint plug {K E} (z : MapZipper K E) (m : Map K E) : Map K E := match z with | Here => m | Left r z' => plug z' m :* r | Right l z' => l :* plug z' m end. Fixpoint plug' {K E} (z : MapZipper K E) : Map K E := match z with | Here => mapEmpty | Left r Here => r | Left r z' => plug' z' :* r | Right l Here => l | Right l z' => l :* plug' z' end. Lemma plug'_plug : forall {K E} (z : MapZipper K E), plug' z ~= plug z mapEmpty. intros. induction z;simpl; [reflexivity|..];rewrite <- IHz; clear IHz; (destruct z;[simpl;rewrite ?equivUnit,?equivUnitL|..];reflexivity). Qed. Lemma plug_plug' : forall {K E} m (z : MapZipper K E), plug z m ~= m :* plug' z. induction z;simpl; [rewrite equivUnit;reflexivity|..]; rewrite IHz;clear IHz. rewrite equivAssoc. destruct z;[simpl;rewrite equivUnitL|..];reflexivity. destruct z;rewrite equivComAssoc;[simpl;rewrite equivUnit|..];reflexivity. Qed. Lemma same_item {K E} k v m' (z : MapZipper K E): plug' z ~= m' -> plug z (k |-> v) ~= k |-> v :* m'. intros. rewrite <- H. apply plug_plug'. Qed. Lemma equiv_item {K E} k v v' m' (z : MapZipper K E): v = v' -> plug' z ~= m' -> plug z (k |-> v) ~= k |-> v' :* m'. intros. subst. rewrite <- H0. apply plug_plug'. Qed. Lemma item_test : forall (k1 k2 : nat) (v1 v2 : nat) (m1 : Map nat nat), exists m1', exists v2', k1 |-> v1 :* m1 :* k2 |-> v2 ~= k2 |-> v2' :* k1 |-> v1 :* m1'. intros. eexists. eexists. refine (equiv_item (Right (Right Here)) (eq_refl _) _);unfold plug'. refine (equiv_item (Left Here) (eq_refl _) _);unfold plug'. reflexivity. Qed. Ltac find k m s := match m with | @mapItem ?K ?E k _ => let t := constr:(@Here K E) in s t | ?l :* ?r => find k l ltac:(fun m => let m' := constr:(Left (r:=r) m) in s m') || find k r ltac:(fun m => let m' := constr:(Right (l:=l) m) in s m') end. Ltac items := match goal with |[|- ?m ~= ?k |-> _ :* _] => find k m ltac:(fun t => (apply (same_item t) || apply (equiv_item t)); [..|unfold plug';instantiate;items]) |_ => idtac end. Lemma item_tac_test : forall (k1 k2 k3 : nat) (v1 v2 : nat) (m1 : Map nat nat), exists v1', exists v2', exists v3', k3 |-> v1 :* k1 |-> v1 :* k2 |-> v1 ~= k2 |-> v2' :* k1 |-> v1' :* k3 |-> v3'. intros; repeat eexists. items. apply equivRefl. Qed. Print item_tac_test.
open import Coinduction using ( ♯_ ; ♭ ) open import Data.Strict using ( Strict ; ! ) open import Data.Natural using ( Natural ; # ; _+_ ) open import Data.Bool using ( Bool ; true ; false ) open import System.IO.Transducers.Session using ( I ; Σ ; ⟨_⟩ ; * ; _&*_ ; ¿ ) open import System.IO.Transducers.Lazy using ( _⇒_ ; inp ; out ; done ) open import System.IO.Transducers.Strict using ( _⇛_ ) module System.IO.Transducers.List where -- Length of a list length' : ∀ {T S} → (Strict Natural) → (T &* S) ⇛ ⟨ Natural ⟩ length' {I} {S} (! n) true = inp (♯ length' {S} {S} (! (n + # 1))) length' {I} {S} (! n) false = out n done length' {Σ V G} {S} (! n) b = inp (♯ length' {♭ G b} {S} (! n)) length : ∀ {S} → (* S) ⇛ ⟨ Natural ⟩ length {S} = length' {I} {S} (! (# 0)) -- Flatten a list of lists mutual concat' : ∀ {T S} → ((T &* S) &* * S) ⇛ (T &* S) concat' {I} {S} true = out true (inp (♯ concat' {S} {S})) concat' {I} {S} false = inp (♯ concat {S}) concat' {Σ W G} {S} a = out a (inp (♯ concat' {♭ G a} {S})) concat : ∀ {S} → (* (* S)) ⇛ (* S) concat {S} true = inp (♯ concat' {I} {S}) concat {S} false = out false done -- Some inclusions, which coerce traces from one session to another. -- TODO: Add more inclusions. -- TODO: Prove that these are monomorphisms. -- TODO: It would be nice if inclusions like this could be handled by subtyping. S⊆S&*T : ∀ {S T} → S ⇒ S &* T S⊆S&*T {I} = out false done S⊆S&*T {Σ V F} = inp (♯ λ a → out a S⊆S&*T) S⊆*S : ∀ {S} → S ⇒ * S S⊆*S = out true S⊆S&*T ¿S⊆*S : ∀ {S} → ¿ S ⇛ * S ¿S⊆*S {S} true = out true (S⊆S&*T {S} {S}) ¿S⊆*S {S} false = out false done
function [ drecksMDH, iLCPositions ] = fMeas_mainLUTDrecks( sFilename ) %FMEAS_MAIN main function for extracting Data, Loop counters, evalInfoMask % and drecksMDH % % (c) Christian Wuerslin, Thomas Kuestner % --------------------------------------------------------------------- % input read parameter % Set, Seg, Smp % measReadPara = {[0 inf], [0 inf], [21 inf]}; % for CS_Trufi and CS_Flash, CS_Flash_Retro, CS_EPI [sPath, sName, sExt] = fileparts(sFilename); if(~exist(fullfile(sPath,[sName,'.mat']),'file')) fprintf('Creating look-up table for measdata file\n'); fMeasCreateLUT_main(sFilename); end % load data matfile = whos('-file', fullfile(sPath,[sName,'.mat'])); if(ismember('iLCDrecks', {matfile.name}) && ismember('iLCPositions', {matfile.name})) % drecksMDH 1.0 % [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3}); [drecksMDH, iLCPositions] = fMeasReadDrecksMDH(fullfile(sPath,[sName,sExt])); elseif(ismember('SDrecksMDH', {matfile.name})) % drecksMDH 2.0 % [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3}); load(fullfile(sPath,[sName,'.mat']), 'SDrecksMDH'); drecksMDH = SDrecksMDH; iLCPositions = []; else % no drecksMDH at all % [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3}); drecksMDH = []; iLCPositions = []; end end
[STATEMENT] lemma scount_infinite_iff: "scount P \<omega> = \<infinity> \<longleftrightarrow> alw (ev P) \<omega>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (scount P \<omega> = \<infinity>) = alw (ev P) \<omega> [PROOF STEP] by (metis enat_ord_simps(4) not_alw_not scount_finite scount_infinite)
(* Title: HOL/Auth/n_german_lemma_on_inv__31.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_german Protocol Case Study*} theory n_german_lemma_on_inv__31 imports n_german_base begin section{*All lemmas on causal relation between inv__31 and some rule r*} lemma n_SendInvEVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvE i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvE i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvSVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvS i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvS i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__31: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__31: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqESVsinv__31: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqES i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqVsinv__31: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReq N i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__31: assumes a1: "\<exists> j. j\<le>N\<and>r=n_SendReqS j" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqEIVsinv__31: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqEI i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
{-# OPTIONS --universe-polymorphism #-} module Categories.Monad where open import Level open import Categories.Category open import Categories.Functor hiding (_≡_; assoc; identityˡ; identityʳ) open import Categories.NaturalTransformation renaming (id to idN) record Monad {o ℓ e} (C : Category o ℓ e) : Set (o ⊔ ℓ ⊔ e) where field F : Endofunctor C η : NaturalTransformation id F μ : NaturalTransformation (F ∘ F) F open Functor F field .assoc : μ ∘₁ (F ∘ˡ μ) ≡ μ ∘₁ (μ ∘ʳ F) .identityˡ : μ ∘₁ (F ∘ˡ η) ≡ idN .identityʳ : μ ∘₁ (η ∘ʳ F) ≡ idN
Require Import HoareDef OpenDef STB Repeat0 Repeat1 SimModSem. Require Import Coqlib. Require Import ImpPrelude. Require Import Skeleton. Require Import PCM. Require Import ModSem Behavior. Require Import Relation_Definitions. (*** TODO: export these in Coqlib or Universe ***) Require Import Relation_Operators. Require Import RelationPairs. From ITree Require Import Events.MapDefault. From ExtLib Require Import Core.RelDec Structures.Maps Data.Map.FMapAList. Require Import HTactics ProofMode Invariant. Require Import Imp. Require Import ImpNotations. Require Import ImpProofs. Set Implicit Arguments. Local Open Scope nat_scope. Section SIMMODSEM. Context `{Σ: GRA.t}. Let W: Type := Any.t * Any.t. Variable FunStb: Sk.t -> gname -> option fspec. Variable GlobalStb: Sk.t -> gname -> option fspec. Let wf: _ -> W -> Prop := @mk_wf _ unit (fun _ _ _ => True%I) . Hypothesis FunStb_incl: forall sk, stb_incl (FunStb sk) (GlobalStb sk). Hypothesis GlobalStb_repeat: forall sk, fn_has_spec (GlobalStb sk) "repeat" (Repeat1.repeat_spec FunStb sk). Hypothesis GlobalStb_complete: forall sk fn, GlobalStb sk fn <> None. Theorem correct: refines2 [Repeat0.Repeat] [Repeat1.Repeat FunStb GlobalStb]. Proof. eapply adequacy_local2. econs; ss. i. econstructor 1 with (wf:=wf) (le:=top2); ss. 2: { esplits; et. red. econs. eapply to_semantic. et. } econs; ss. unfold repeatF. init. { harg. destruct x as [[[f n] x] f_spec]. ss. mDesAll. des; clarify. steps. force_r; auto. des_ifs. { astop. steps. force_l. eexists. steps. hret _; ss. iPureIntro. splits; et. destruct n; et. exfalso. lia. } { destruct n. { exfalso. lia. } steps. inv PURE3. inv SPEC. rewrite FBLOCK. unfold ccallU. steps. astart 2. acatch. { eapply FunStb_incl. et. } hcall_weaken _ _ _ with ""; et. { splits; ss. eapply Ord.le_lt_lt. { eapply OrdArith.add_base_l. } { eapply OrdArith.lt_add_r. rewrite Ord.from_nat_S. eapply Ord.S_lt. } } ss. mDesAll. des; clarify. hexploit GlobalStb_repeat. i. inv H. steps. acatch. { et. } hcall_weaken (Repeat1.repeat_spec FunStb sk) (_, n, _, _) _ with ""; ss. { iPureIntro. esplits; et. { repeat f_equal. lia. } { unfold_intrange_64. unfold sumbool_to_bool in *. des_ifs; try lia. } { econs; et. econs; et. } } { splits; ss. eauto with ord_step. } mDesAll. des; clarify. steps. astop. steps. force_l. eexists. steps. hret _; ss. } } { harg. mDesAll. des; clarify. steps. } Unshelve. all: ss. all: try exact 0. Qed. End SIMMODSEM.
SUBROUTINE SN_OPNF ( filnam, wrtflg, isnfln, iflsrc, nparm, + parms, ivert, mrgdat, iret ) C************************************************************************ C* SN_OPNF * C* * C* This subroutine opens an existing sounding data file. * C* * C* SN_OPNF ( FILNAM, WRTFLG, ISNFLN, IFLSRC, NPARM, PARMS, IVERT, * C* MRGDAT, IRET ) * C* * C* Input parameters: * C* FILNAM CHAR* Sounding file name * C* WRTFLG LOGICAL Write access flag * C* * C* Output parameters: * C* ISNFLN INTEGER File number * C* IFLSRC INTEGER Data source * C* NPARM INTEGER Number of parameters * C* PARMS (NPARM) CHAR*4 Parameter names * C* IVERT INTEGER Vertical coordinate * C* MRGDAT LOGICAL Merged data flag * C* IRET INTEGER Return code * C* 0 = normal return * C* -2 = file could not be opened * C* -7 = file not sounding file * C* -24 = file name is blank * C** * C* Log: * C* M. desJardins/GSFC 8/87 * C* M. desJardins/GSFC 4/90 Add error for blank file name * C* S. Schotz/GSFC 8/90 Write error message for blank file name * C************************************************************************ INCLUDE 'GEMPRM.PRM' INCLUDE 'GMBDTA.CMN' INCLUDE 'sncmn.cmn' C* CHARACTER* (*) filnam, parms (*) LOGICAL wrtflg, mrgdat C* LOGICAL shrflg C------------------------------------------------------------------------- C* Check for blank name. C CALL ST_LSTR ( filnam, lenf, ier ) IF ( lenf .eq. 0 ) THEN iret = -24 CALL ER_WMSG ( 'SN', iret, filnam, ier ) RETURN END IF C C* Call general subroutine to open file without shared access. C shrflg = .false. CALL SN_OFIL ( filnam, wrtflg, shrflg, isnfln, iflsrc, + nparm, parms, ivert, mrgdat, iret ) C* RETURN END
{-# OPTIONS --without-K --safe #-} open import Algebra.Structures.Bundles.Field module Algebra.Linear.Morphism.VectorSpace {k ℓᵏ} (K : Field k ℓᵏ) where open import Level open import Algebra.FunctionProperties as FP import Algebra.Linear.Morphism.Definitions as LinearMorphismDefinitions import Algebra.Morphism as Morphism open import Relation.Binary using (Rel; Setoid) open import Relation.Binary.Morphism.Structures open import Algebra.Morphism open import Algebra.Linear.Core open import Algebra.Linear.Structures.VectorSpace K open import Algebra.Linear.Structures.Bundles module LinearDefinitions {a₁ a₂ ℓ₂} (A : Set a₁) (B : Set a₂) (_≈_ : Rel B ℓ₂) where open Morphism.Definitions A B _≈_ public open LinearMorphismDefinitions K A B _≈_ public module _ {a₁ ℓ₁} (From : VectorSpace K a₁ ℓ₁) {a₂ ℓ₂} (To : VectorSpace K a₂ ℓ₂) where private module F = VectorSpace From module T = VectorSpace To K' : Set k K' = Field.Carrier K open F using () renaming (Carrier to A; _≈_ to _≈₁_; _+_ to _+₁_; _∙_ to _∙₁_) open T using () renaming (Carrier to B; _≈_ to _≈₂_; _+_ to _+₂_; _∙_ to _∙₂_) open import Function open LinearDefinitions (VectorSpace.Carrier From) (VectorSpace.Carrier To) _≈₂_ record IsLinearMap (⟦_⟧ : Morphism) : Set (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂) where field isAbelianGroupMorphism : IsAbelianGroupMorphism F.abelianGroup T.abelianGroup ⟦_⟧ ∙-homo : ScalarHomomorphism ⟦_⟧ _∙₁_ _∙₂_ open IsAbelianGroupMorphism isAbelianGroupMorphism public renaming (∙-homo to +-homo; ε-homo to 0#-homo) distrib-linear : ∀ (a b : K') (u v : A) -> ⟦ a ∙₁ u +₁ b ∙₁ v ⟧ ≈₂ a ∙₂ ⟦ u ⟧ +₂ b ∙₂ ⟦ v ⟧ distrib-linear a b u v = T.trans (+-homo (a ∙₁ u) (b ∙₁ v)) (T.+-cong (∙-homo a u) (∙-homo b v)) record IsLinearMonomorphism (⟦_⟧ : Morphism) : Set (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂) where field isLinearMap : IsLinearMap ⟦_⟧ injective : Injective _≈₁_ _≈₂_ ⟦_⟧ open IsLinearMap isLinearMap public record IsLinearIsomorphism (⟦_⟧ : Morphism) : Set (k ⊔ a₁ ⊔ a₂ ⊔ ℓ₁ ⊔ ℓ₂) where field isLinearMonomorphism : IsLinearMonomorphism ⟦_⟧ surjective : Surjective _≈₁_ _≈₂_ ⟦_⟧ open IsLinearMonomorphism isLinearMonomorphism public module _ {a ℓ} (V : VectorSpace K a ℓ) where open VectorSpace V open LinearDefinitions Carrier Carrier _≈_ IsLinearEndomorphism : Morphism -> Set (k ⊔ a ⊔ ℓ) IsLinearEndomorphism ⟦_⟧ = IsLinearMap V V ⟦_⟧ IsLinearAutomorphism : Morphism -> Set (k ⊔ a ⊔ ℓ) IsLinearAutomorphism ⟦_⟧ = IsLinearIsomorphism V V ⟦_⟧
c======================================================================= c c subroutine nqhess c c Quasi-Newton optimizer with BFGS method c c----------------------------------------------------------------------- c c---------------------------------------------------------------------- c subroutine nqhess(n,imp,lp,iz,rz) implicit double precision(a-h,o-z) dimension iz(*),rz(*) 1000 format(//) 1001 format(34h nqhess hessienne au point final) 1002 format(9h nqhess,i4,5d12.4,/,(9h nqhess,4x,5d12.4)) ni=2*n nw=n*(n+1)/2 nw1=nw+n if(n.eq.1) go to 50 nr=iz(ni+1) if(nr.eq.0) go to 20 do 10 i=1,n if(iz(n+i).ne.0) go to 10 nc=i call fajc1(n,nc,nr,rz(1),rz(nw+1),iz(1)) if(nr.eq.0) go to 20 10 continue 20 n1=n-1 do 40 i=1,n1 j1=iz(i) if(j1.eq.i) go to 40 ni=i nj=j1 call f1qhes(n,ni,nj,nw,rz) call f1qhes(n,nj,ni,nw1,rz) call f2qhes(n,nj,nw,rz) call f2qhes(n,ni,nw1,rz) if(i.eq.n1) go to 50 i1=i+1 do 30 k=i1,n if(iz(k).ne.i) go to 30 iz(k)=j1 go to 40 30 continue 40 continue 50 if(imp.le.0) return write(lp,1000) write(lp,1001) do 60 i=1,n write(lp,1002) i,(rz(i+(j-1)*(2*n-j)/2),j=1,i) 60 continue return end
Formal statement is: lemma emeasure_notin_sets: "A \<notin> sets M \<Longrightarrow> emeasure M A = 0" Informal statement is: If a set $A$ is not in the $\sigma$-algebra of a measure space $(X, \mathcal{A}, \mu)$, then $\mu(A) = 0$.
(* Copyright © 2009 Valentin Blot Permission is hereby granted, free of charge, to any person obtaining a copy of this proof and associated documentation files (the "Proof"), to deal in the Proof without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Proof, and to permit persons to whom the Proof is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Proof. THE PROOF IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF. *) Require Import Zring Qring Q_can. Import CRings.coercions. Section nat_Q_lists. Fixpoint list_nat (p : nat) : list nat := match p with | O => O::nil | S p => S p::list_nat p end. Lemma list_nat_spec : forall p a, a <= p -> In a (list_nat p). Proof. intro p; induction p. intros a Hle; inversion Hle; left; reflexivity. intros a Hle; simpl. case (eq_nat_dec (S p) a). left; assumption. right; apply IHp. inversion Hle. destruct n; symmetry; assumption. assumption. Qed. Definition list_nat_prod (p q : nat) : list (nat * nat) := list_prod (list_nat p) (list_nat q). Lemma list_nat_prod_spec : forall p q a b, a <= p -> b <= q -> In (a, b) (list_nat_prod p q). Proof. intros; apply in_prod; apply list_nat_spec; assumption. Qed. Definition nat_prod_to_Q (pq : nat * nat) : list Q_as_CRing := let (p, q) := pq in match p with | O => Qmake Z0 (P_of_succ_nat q)::nil | S p => match q with | O => nil | S q => Qmake (Zpos (P_of_succ_nat p)) (P_of_succ_nat q):: Qmake (Zneg (P_of_succ_nat p)) (P_of_succ_nat q)::nil end end. Definition list_Q (a b : Z_as_CRing) : list Q_as_CRing := flat_map nat_prod_to_Q (list_nat_prod (Z.abs_nat a) (Z.abs_nat b)). Lemma list_Q_spec_pos : forall a b c d, Z.abs_nat c <= Z.abs_nat a -> Z.abs_nat (Zpos d) <= Z.abs_nat b -> In (Qmake c d) (list_Q a b). Proof. intros a b c d Hca Hdb. case (Qeq_dec (c#d)%Q [0]). unfold Qeq; simpl; rewrite Zmult_1_r. intro Heq; rewrite Heq. clear c Hca Heq. unfold list_Q. rewrite -> in_flat_map. exists (0, pred (nat_of_P d)). split. apply list_nat_prod_spec. apply le_O_n. apply (le_trans _ _ _ (le_pred_n _) Hdb). left. f_equal. destruct (ZL4 d). rewrite H. simpl. rewrite <- nat_of_P_o_P_of_succ_nat_eq_succ in H. apply nat_of_P_inj; symmetry; assumption. unfold list_Q. intro H. rewrite -> in_flat_map. exists (Z.abs_nat c, Z.abs_nat d). split. apply list_nat_prod_spec; assumption. simpl. case (ZL4 d). intros d' Hd'. unfold Z.abs_nat at 1 in Hdb. rewrite Hd'. rewrite Hd' in Hdb. case_eq (Z.abs_nat c). intro Heq. destruct H. destruct c. reflexivity. simpl in Heq; destruct (ZL4 p); rewrite Heq in H; discriminate. simpl in Heq; destruct (ZL4 p); rewrite Heq in H; discriminate. intros. destruct c as [|c|c]. discriminate. constructor 1. unfold Qeq; simpl. assert (c = P_of_succ_nat n). rewrite <- nat_of_P_o_P_of_succ_nat_eq_succ in H0. simpl in H. apply nat_of_P_inj; assumption. rewrite H1. cut (P_of_succ_nat d' = d). intro H2; rewrite H2; reflexivity. apply nat_of_P_inj. rewrite nat_of_P_o_P_of_succ_nat_eq_succ. symmetry; assumption. constructor 2. constructor 1. unfold Qeq; simpl. assert (c = P_of_succ_nat n). rewrite <- nat_of_P_o_P_of_succ_nat_eq_succ in H0. simpl in H. apply nat_of_P_inj; assumption. rewrite H1. cut (P_of_succ_nat d' = d). intro H2; rewrite H2; reflexivity. apply nat_of_P_inj. rewrite nat_of_P_o_P_of_succ_nat_eq_succ. symmetry; assumption. Qed. Lemma list_Q_spec_neg : forall a b c d, Z.abs_nat c <= Z.abs_nat a -> Z.abs_nat (Zneg d) <= Z.abs_nat b -> In (Qmake c d) (list_Q a b). Proof. intros a b c d. apply list_Q_spec_pos. Qed. Lemma list_Q_spec_zero : forall a b d, nat_of_P d <= Z.abs_nat b -> In (Qmake Z0 d) (list_Q a b). Proof. intros a b d Hle. unfold list_Q. rewrite -> in_flat_map. exists (0, pred (nat_of_P d)). split. apply list_nat_prod_spec. apply le_O_n. apply (le_trans _ _ _ (le_pred_n _) Hle). left. f_equal. destruct (ZL4 d). rewrite H. simpl. rewrite <- nat_of_P_o_P_of_succ_nat_eq_succ in H. apply nat_of_P_inj; symmetry; assumption. Qed. Lemma div_imp_leq : forall a b : Z_as_CRing, b [#] [0] -> Zdivides a b -> Z.abs_nat a <= Z.abs_nat b. Proof. intros a b Hap Hdiv. destruct Hdiv. rewrite <- H. rewrite Zabs_nat_mult. rewrite <- H in Hap. destruct x. destruct Hap. reflexivity. simpl. destruct (ZL4 p). rewrite H0. simpl. rewrite <- (plus_0_r (Z.abs_nat a)) at 1. apply plus_le_compat_l. apply le_O_n. simpl. destruct (ZL4 p). rewrite H0. simpl. rewrite <- (plus_0_r (Z.abs_nat a)) at 1. apply plus_le_compat_l. apply le_O_n. Qed. Lemma list_Q_spec : forall (a b : Z_as_CRing) q, a [#] [0] -> b [#] [0] -> Zdivides (Q_can_num q) a -> Zdivides (Z.abs_nat (Q_can_den_pos_val q)) b -> In (Q_can q) (list_Q a b). Proof. intros a b q Hapa Hapb Ha Hb. destruct q as [qn qd]. destruct qn. apply list_Q_spec_zero. revert Hb; generalize (Q_can_den_pos_val (0#qd)%Q). intros p Hdiv. assert (nat_of_P p = Z.abs_nat p). reflexivity. rewrite H; apply div_imp_leq. assumption. rewrite inj_Zabs_nat in Hdiv. apply Zdivides_abs_intro_lft; assumption. apply list_Q_spec_pos. apply div_imp_leq; assumption. apply div_imp_leq. assumption. apply Zdivides_abs_intro_lft. rewrite <- inj_Zabs_nat. assumption. apply list_Q_spec_neg. apply div_imp_leq; assumption. apply div_imp_leq. assumption. apply Zdivides_abs_intro_lft. rewrite <- inj_Zabs_nat. assumption. Qed. End nat_Q_lists.
-- @@stderr -- dtrace: failed to compile script test/unittest/bitfields/err.D_ADDROF_BITFIELD.BitfieldAddress.d: [D_ADDROF_BITFIELD] line 26: cannot take address of bit-field
module Lukasiewicz import Prelude.Bool %access public export %default total -- ||| Three values for Kleene logic as type -- ||| Also interpretable as a Fuzzy Boolean -- ||| Also intrepretable in the context of Map Theory -- data Fool = T True | U Unknown | F False ||| Fuzzy Bool Representation Fool : Type Fool = Maybe Bool -- Fuzzy Logic | Quantum Logic | Category Theory | Map Theory -- TODO : -> Lazy Bool ? -- useful aliases for lazy people T : Fool T = Just True F : Fool F = Just False U : Fool U = Nothing ||| Kleene NOT ||| Ref https://en.wikipedia.org/wiki/Three-valued_logic#Kleene_and_Priest_logics not : Fool -> Fool not Nothing = Nothing not (Just b) = (Just (not b)) imp: Fool -> Fool -> Fool imp (Just False) _ = (Just True) imp Nothing False = Nothing imp Nothing _ = (Just True) imp (Just True) b = b
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jannis Limperg Facts about `ulift` and `plift`. -/ universes u v namespace plift variables {α : Sort u} {β : Sort v} /-- Functorial action. -/ @[simp] protected def map (f : α → β) : plift α → plift β | (up a) := up (f a) /-- Embedding of pure values. -/ @[simp] protected def pure : α → plift α := up /-- Applicative sequencing. -/ @[simp] protected def seq : plift (α → β) → plift α → plift β | (up f) (up a) := up (f a) /-- Monadic bind. -/ @[simp] protected def bind : plift α → (α → plift β) → plift β | (up a) f := f a instance : monad plift := { map := @plift.map, pure := @plift.pure, seq := @plift.seq, bind := @plift.bind } instance : is_lawful_functor plift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative plift := { pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad plift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, rfl, bind_assoc := λ α β γ ⟨x⟩ f g, rfl } @[simp] lemma rec.constant {α : Sort u} {β : Type v} (b : β) : @plift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, plift.cases_on x (λ a, eq.refl (plift.rec (λ a', b) {down := a}))) end plift namespace ulift variables {α : Type u} {β : Type v} /-- Functorial action. -/ @[simp] protected def map (f : α → β) : ulift α → ulift β | (up a) := up (f a) /-- Embedding of pure values. -/ @[simp] protected def pure : α → ulift α := up /-- Applicative sequencing. -/ @[simp] protected def seq : ulift (α → β) → ulift α → ulift β | (up f) (up a) := up (f a) /-- Monadic bind. -/ @[simp] protected def bind : ulift α → (α → ulift β) → ulift β | (up a) f := up (down (f a)) -- The `up ∘ down` gives us more universe polymorphism than simply `f a`. instance : monad ulift := { map := @ulift.map, pure := @ulift.pure, seq := @ulift.seq, bind := @ulift.bind } instance : is_lawful_functor ulift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative ulift := { pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad ulift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl }, bind_assoc := λ α β γ ⟨x⟩ f g, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } } @[simp] lemma rec.constant {α : Type u} {β : Sort v} (b : β) : @ulift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, ulift.cases_on x (λ a, eq.refl (ulift.rec (λ a', b) {down := a}))) end ulift
\RequirePackage[l2tabu,orthodox]{nag} \RequirePackage{fixltx2e} \documentclass[11pt]{bxart} \usepackage[widespace]{fourier} \usepackage{microtype} \usepackage{lipsum} \usepackage{booktabs} \usepackage[bf]{caption} \title{\textbf{Testing B/X Article}} \author{Peter H.\ Fr\"ohlich} \newcommand{\f}{\bfseries} \begin{document} \maketitle \tableofcontents \section{Welcome} \lipsum[1-6] \begin{table} \footnotesize \centering \begin{tabular}{cccc} Charisma & Adjustment & Maximum number & Morale of\\ Score & to Reactions & of retainers & retainers\\ \cmidrule(lr){1-1}\cmidrule(lr){2-2}\cmidrule(lr){3-3}\cmidrule(lr){4-4} 3 & \(-2\) & 1 & 4\\ 4--5 & \(-2\) & 2 & 5\\ 6--8 & \(-1\) & 3 & 6\\ 9--12 & None & 4 & 7\\ 13--15 & \(+1\) & 5 & 8\\ 16--17 & \(+2\) & 6 & 9\\ 18 & \(+2\) & 7 & 10\\ \end{tabular} \caption{Charisma Bonuses and Penalties. Easy to pull off, but terrible without at least bold headers.} \label{charisma} \end{table} \section{Stylin' in Style} \subsection{Well} \lipsum[11-15] \subsection{Now} \lipsum[16-20] \begin{table*} \small \centering \begin{tabular}{lllllccc@{\quad\quad\quad}cr} \f Dragon & \f Where & \f Breath & \f Range & \f & \f Chance & \f Chance of & \multicolumn{3}{c}{\f Spells (by level)}\\ \f Type & \f Found & \f Weapon & \f Length \(\times\) Width & \f Shape & \f of Talking & \f being Asleep & \f 1 & \f 2 & \f 3\\ \cmidrule(lr){1-1}\cmidrule(lr){2-2}\cmidrule(lr){3-3}\cmidrule(lr){4-4}\cmidrule(lr){5-5}\cmidrule(lr){6-6}\cmidrule(lr){7-7}\cmidrule(lr){8-10} White & Cold region & Cold & \(80' \times 30'\) & Cone & 10\% & 50\% & 3 & - & -\\ Black & Swamp, marsh & Acid & \(60' \times 5'\) & Line & 20\% & 40\% & 4 & - & -\\ Green & Jungle, forest & Gas & \(50' \times 40'\) & Cloud & 30\% & 30\% & 3 & 3 & -\\ Blue & Desert, plain & Lightning & \(100' \times 5'\) & Line & 40\% & 20\% & 4 & 4 & -\\ Red & Mountain, hill & Fire & \(90' \times 30'\) & Cone & 50\% & 10\% & 3 & 3 & 3\\ Gold & Anywhere & Fire/Gas & \(90' \times 30'\)/\(50' \times 40'\) & Cone/Cloud & 100\% & 5\% & 4 & 4 & 4\\ \end{tabular} \caption{The Dreaded Dragon Table. Only one change was necessary, saying ``Gas'' instead of ``Chlorine Gas'' for Greens. Oh, and a smaller font.} \label{dragons} \end{table*} \section{Zwecks Geil} \lipsum[21-28] \end{document}
from functools import partial from typing import List, Callable import albumentations as A import numpy as np import torch from sklearn.externals._pilutil import bytescale from torchvision.ops import nms import torchvision.transforms as T from utils import select_interpolation_method def addHM(inp: np.ndarray): inp_out = np.append(inp,[[123 for i in range(inp.shape[0])]], axis = 0) return inp_out def normalize_01(inp: np.ndarray): """Acotar la imagen de entrada al rango de valores [0, 1] (sin recorte)""" inp_out = (inp - np.min(inp)) / np.ptp(inp) return inp_out def normalize(inp: np.ndarray, mean: float, std: float): """Normalizar basado en una media y una desviación estándar.""" inp_out = (inp - mean) / std return inp_out def re_normalize(inp: np.ndarray, low: int = 0, high: int = 255): """Normalizar la información a cierto rango. Por Defecto: [0-255]""" inp_out = bytescale(inp, low=low, high=high) return inp_out def clip_bbs(inp: np.ndarray, bbs: np.ndarray): """ Si las cajas dilimitadoras exceden la imagen en alguna dimensión, son recortadas a el máximo posible dentro de esa dimensión. Se esperan las cajas delimitadoras con el formato xyxy. Ejemplo: x_value=224 but x_shape=200 -> x1=199 """ def clip(value: int, max: int): if value >= max - 1: value = max - 1 elif value <= 0: value = 0 return value output = [] for bb in bbs: x1, y1, x2, y2 = tuple(bb) x_shape = inp.shape[1] y_shape = inp.shape[0] x1 = clip(x1, x_shape) y1 = clip(y1, y_shape) x2 = clip(x2, x_shape) y2 = clip(y2, y_shape) output.append([x1, y1, x2, y2]) return np.array(output) def map_class_to_int(labels: List[str], mapping: dict): """Mapea una cadena (string) a un entero (int).""" labels = np.array(labels) dummy = np.empty_like(labels) for key, value in mapping.items(): dummy[labels == key] = value return dummy.astype(np.uint8) def apply_nms(target: dict, iou_threshold): """Supresión de No-Máximos (Non-maximum Suppression NMS)""" boxes = torch.tensor(target["boxes"]) labels = torch.tensor(target["labels"]) scores = torch.tensor(target["scores"]) if boxes.size()[0] > 0: mask = nms(boxes, scores, iou_threshold=iou_threshold) mask = (np.array(mask),) target["boxes"] = np.asarray(boxes)[mask] target["labels"] = np.asarray(labels)[mask] target["scores"] = np.asarray(scores)[mask] return target def apply_score_threshold(target: dict, score_threshold): """Remueve las prediciones de las cajas delimitadoras con bajos puntajes.""" boxes = target["boxes"] labels = target["labels"] scores = target["scores"] mask = np.where(scores > score_threshold) target["boxes"] = boxes[mask] target["labels"] = labels[mask] target["scores"] = scores[mask] return target class Repr: """Representación de cadena evaluable de un objeto""" def __repr__(self): return f"{self.__class__.__name__}: {self.__dict__}" class FunctionWrapperSingle(Repr): """Una función wrapper que regresa un parcial para una sola entrada.""" def __init__(self, function: Callable, *args, **kwargs): self.function = partial(function, *args, **kwargs) def __call__(self, inp: np.ndarray): return self.function(inp) class FunctionWrapperDouble(Repr): """Una función wrapper que regresa un parcial para un par entrada-objetivo.""" def __init__( self, function: Callable, input: bool = True, target: bool = False, *args, **kwargs, ): self.function = partial(function, *args, **kwargs) self.input = input self.target = target def __call__(self, inp: np.ndarray, tar: dict): if self.input: inp = self.function(inp) if self.target: tar = self.function(tar) return inp, tar class Compose: """Clase Base - compone multiples transformaciones juntas.""" def __init__(self, transforms: List[Callable]): self.transforms = transforms def __repr__(self): return str([transform for transform in self.transforms]) class ComposeDouble(Compose): """Compone transformaciones para pares entrada-objetico.""" def __call__(self, inp: np.ndarray, target: dict): for t in self.transforms: try: inp, target = t(inp, target) except: inp = np.squeeze(t(torch.from_numpy(np.expand_dims(inp, axis = 0))).numpy()) return inp, target class ComposeSingle(Compose): """Compone transformaciones para una única entrada.""" def __call__(self, inp: np.ndarray): for t in self.transforms: inp = t(inp) return inp class AlbumentationWrapper(Repr): """ Un wrapper para el paquete albumentation. Es esperado que las cajas delimitadoras estén en el formato xyxy (pascal_voc) Las cajas delimitadoras no pueden ser mas grandes que la dimensión espacial de la imagen Se usa Clip() si alguna caja delimitadora sale del espacio de la imagen, antes de usar la función. """ def __init__(self, albumentation: Callable, format: str = "pascal_voc"): self.albumentation = albumentation self.format = format def __call__(self, inp: np.ndarray, tar: dict): # input, target transform = A.Compose( [self.albumentation], bbox_params=A.BboxParams(format=self.format, label_fields=["class_labels"]), ) out_dict = transform(image=inp, bboxes=tar["boxes"], class_labels=tar["labels"]) input_out = np.array(out_dict["image"]) boxes = np.array(out_dict["bboxes"]) labels = np.array(out_dict["class_labels"]) tar["boxes"] = boxes tar["labels"] = labels return input_out, tar class Clip(Repr): """ Si las cajas delimitadoras exceden una dimensión, son cortadas al máximo valor de la dimenisón Las cajas delimitadoras son esperadas en formato xyxy. Ejemplo: x_value=224 but x_shape=200 -> x1=199 """ def __call__(self, inp: np.ndarray, tar: dict): new_boxes = clip_bbs(inp=inp, bbs=tar["boxes"]) tar["boxes"] = new_boxes return inp, tar class RescaleWithBB: def __init__(self, size, interp_m = 'bilinear', to_PIL = False): self.size = size self.interp_m = interp_m self.to_PIL = to_PIL # hace el objeto llamable, # se comporta como una una función def __call__(self, img, box): # obtenemos las dimensiones originales try: img_w, img_h = img.shape except: img_w, img_h,_ = img.shape if len(self.size) == 1: if len(img.shape) < 3: if self.interp_m in ['box','hamming','lanczos'] or self.to_PIL: # Pasamos a PIL para poder aplicar estas interpolaciones de rescalado de imagen img = np.squeeze(T.ToTensor()(T.Resize([self.size[0],self.size[0]],interpolation = select_interpolation_method(self.interp_m))(T.ToPILImage()(torch.from_numpy(np.expand_dims(img, axis = 0))))).numpy()) else: img = np.squeeze(T.Resize([self.size[0],self.size[0]],interpolation = select_interpolation_method(self.interp_m))(torch.from_numpy(np.expand_dims(img, axis = 0))).numpy()) else: if self.interp_m in ['box','hamming','lanczos'] or self.to_PIL: # Pasamos a PIL para poder aplicar estas interpolaciones de rescalado de imagen img = np.moveaxis(T.ToTensor()(T.Resize([self.size[0],self.size[0]],interpolation = select_interpolation_method(self.interp_m))(T.ToPILImage()(torch.from_numpy(np.moveaxis(img, -1, 0))))).numpy(), 0, -1) else: img = np.moveaxis(T.Resize([self.size[0],self.size[0]],interpolation = select_interpolation_method(self.interp_m))(torch.from_numpy(np.moveaxis(img, -1, 0))).numpy(), 0, -1) # calculamos escalas scale_x = img_w / self.size[0] scale_y = img_h / self.size[0] elif len(self.size) == 2: if len(img.shape) < 3: if self.interp_m in ['box','hamming','lanczos'] or self.to_PIL: # Pasamos a PIL para poder aplicar estas interpolaciones de rescalado de imagen img = np.squeeze(T.ToTensor()(T.Resize([self.size[0],self.size[1]],interpolation = select_interpolation_method(self.interp_m))(T.ToPILImage()(torch.from_numpy(np.expand_dims(img, axis = 0))))).numpy()) else: img = np.squeeze(T.Resize([self.size[0],self.size[1]],interpolation = select_interpolation_method(self.interp_m))(torch.from_numpy(np.expand_dims(img, axis = 0))).numpy()) else: if self.interp_m in ['box','hamming','lanczos'] or self.to_PIL: # Pasamos a PIL para poder aplicar estas interpolaciones de rescalado de imagen img = np.moveaxis(T.ToTensor()(T.Resize([self.size[0],self.size[1]],interpolation = select_interpolation_method(self.interp_m))(T.ToPILImage()(torch.from_numpy(np.moveaxis(img, -1, 0))))).numpy(), 0, -1) else: img = np.moveaxis(T.Resize([self.size[0],self.size[1]],interpolation = select_interpolation_method(self.interp_m))(torch.from_numpy(np.moveaxis(img, -1, 0))).numpy(), 0, -1) # calculamos escalas scale_x = img_w / self.size[0] scale_y = img_h / self.size[1] totalboxes = [] for bx in box['boxes']: # escalamos el cuadro delimitador x1, y1, x2, y2 = bx y1 = int(y1 / scale_y) y2 = int(y2 / scale_y) x1 = int(x1 / scale_x) x2 = int(x2 / scale_x) # calculamos ancho y alto w = x2 #- x1 h = y2 #- y1 # armamos cuadro delimitador totalboxes.append([x1, y1, w, h]) box['boxes'] = np.array(totalboxes, dtype=np.float32) return img, box
{-# OPTIONS --without-K #-} module container.core where open import level open import sum open import equality open import function module _ {li}{I : Set li} where -- homsets in the slice category _→ⁱ_ : ∀ {lx ly} → (I → Set lx) → (I → Set ly) → Set _ X →ⁱ Y = (i : I) → X i → Y i -- identity of the slice category idⁱ : ∀ {lx}{X : I → Set lx} → X →ⁱ X idⁱ i x = x -- composition in the slice category _∘ⁱ_ : ∀ {lx ly lz} {X : I → Set lx}{Y : I → Set ly}{Z : I → Set lz} → (Y →ⁱ Z) → (X →ⁱ Y) → (X →ⁱ Z) (f ∘ⁱ g) i = f i ∘ g i infixl 9 _∘ⁱ_ -- extensionality funext-isoⁱ : ∀ {lx ly} {X : I → Set lx}{Y : (i : I) → X i → Set ly} → {f g : (i : I)(x : X i) → Y i x} → (∀ i x → f i x ≡ g i x) ≅ (f ≡ g) funext-isoⁱ {f = f}{g = g} = (Π-ap-iso refl≅ λ i → strong-funext-iso) ·≅ strong-funext-iso funext-invⁱ : ∀ {lx ly} {X : I → Set lx}{Y : (i : I) → X i → Set ly} → {f g : (i : I)(x : X i) → Y i x} → f ≡ g → ∀ i x → f i x ≡ g i x funext-invⁱ = invert funext-isoⁱ funextⁱ : ∀ {lx ly} {X : I → Set lx}{Y : (i : I) → X i → Set ly} → {f g : (i : I)(x : X i) → Y i x} → (∀ i x → f i x ≡ g i x) → f ≡ g funextⁱ = apply funext-isoⁱ -- Definition 1 in Ahrens, Capriotti and Spadotti (arXiv:1504.02949v1 [cs.LO]) record Container (li la lb : Level) : Set (lsuc (li ⊔ la ⊔ lb)) where constructor container field I : Set li A : I → Set la B : {i : I} → A i → Set lb r : {i : I}{a : A i} → B a → I -- Definition 2 in Ahrens, Capriotti and Spadotti (arXiv:1504.02949v1 [cs.LO]) -- functor associated to this indexed container F : ∀ {lx} → (I → Set lx) → I → Set _ F X i = Σ (A i) λ a → (b : B a) → X (r b) F-ap-iso : ∀ {lx ly}{X : I → Set lx}{Y : I → Set ly} → (∀ i → X i ≅ Y i) → ∀ i → F X i ≅ F Y i F-ap-iso isom i = Σ-ap-iso refl≅ λ a → Π-ap-iso refl≅ λ b → isom (r b) -- morphism map for the functor F imap : ∀ {lx ly} → {X : I → Set lx} → {Y : I → Set ly} → (X →ⁱ Y) → (F X →ⁱ F Y) imap g i (a , f) = a , λ b → g (r b) (f b) -- action of a functor on homotopies hmap : ∀ {lx ly} → {X : I → Set lx} → {Y : I → Set ly} → {f g : X →ⁱ Y} → (∀ i x → f i x ≡ g i x) → (∀ i x → imap f i x ≡ imap g i x) hmap p i (a , u) = ap (_,_ a) (funext (λ b → p (r b) (u b))) hmap-id : ∀ {lx ly} → {X : I → Set lx} → {Y : I → Set ly} → (f : X →ⁱ Y) → ∀ i x → hmap (λ i x → refl {x = f i x}) i x ≡ refl hmap-id f i (a , u) = ap (ap (_,_ a)) (funext-id _)
Robyn 's children from her first marriage who were adopted by Kody on June 17 , 2015 :
theory T84 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) " nitpick[card nat=8,timeout=86400] oops end