Datasets:
AI4M
/

text
stringlengths
0
3.34M
Set Implicit Arguments. Require Import TLC.LibTactics. Require Import TLC.LibInt. Require Import ZArith. Open Scope Z_scope. Require Import Psatz. (************************************************************) (* A preorder on Z*Z *) Definition ZZle : Z * Z -> Z * Z -> Prop := fun '(m,n) '(m', n') => m <= m' /\ n <= n'. (************************************************************) (* * max *) Hint Resolve Z.le_max_l : zarith. Hint Resolve Z.le_max_r : zarith. Lemma Zmax_ub_l : forall a b c, c <= a -> c <= Z.max a b. Proof. intros. lia. Qed. Lemma Zmax_ub_r : forall a b c, c <= b -> c <= Z.max a b. Proof. intros. lia. Qed. Hint Resolve Zmax_ub_l Zmax_ub_r : zarith. Lemma Zmax_0_l : forall x, 0 <= x -> Z.max 0 x = x. Proof. intros. lia. Qed. Lemma Zmax_0_r : forall x, 0 <= x -> Z.max x 0 = x. Proof. intros. lia. Qed. (************************************************************) (* * quotient *) Lemma Zquot_mul_2 : forall x, 0 <= x -> x - 1 <= 2 * (x ÷ 2) <= x. Proof. intros x Hx. rewrite <-Zquot2_quot. set (half := Z.quot2 x). destruct (Zeven_odd_dec x) as [H|H]. - rewrite (Zeven_quot2 x); subst half; auto with zarith. - rewrite (Zodd_quot2 x); subst half; auto with zarith. Qed. (************************************************************) (* * Pow function *) Lemma pow_ge_1 : forall k n, 0 < k -> 0 <= n -> 1 <= k ^ n. Proof. intros a b A B. rewrite <-(Z.pow_0_r a). apply Z.pow_le_mono_r; auto. Qed. Hint Resolve pow_ge_1 : zarith. Lemma pow2_ge_1 : forall n, 0 <= n -> 1 <= 2 ^ n. Proof using. auto with zarith. Qed. Hint Resolve pow2_ge_1 : zarith. Lemma pow_succ : forall k n, 0 < k -> 0 <= n -> k ^ (n + 1) = k * k ^ n. Proof using. intros. math_rewrite (n+1 = Z.succ n). rewrite Z.pow_succ_r; auto. Qed. Lemma pow2_succ : forall n, 0 <= n -> 2 ^ (n+1) = 2 * 2^n. Proof using. intros. rewrite pow_succ; auto with zarith. Qed. Lemma pow_succ_quot : forall k n, 0 < k -> 0 <= n -> k ^ (n+1) ÷ k = k ^ n. Proof using. intros. rewrite pow_succ, Z.mul_comm, Z.quot_mul; auto with zarith. Qed. (* A tactic that helps dealing with goals containing "b^m" for multiple m *) Require Import TLC.LibList. Ltac subst_eq_boxer_list l rewrite_tac := match l with | nil => idtac | (@boxer _ ?p) :: ?Hs => match p with (?tm, ?Htm) => rewrite_tac Htm; clear Htm; clear tm; subst_eq_boxer_list Hs rewrite_tac end end. (* Develop occurences of (b ^ m) in H into (b ^ (m - min_e) * b ^ min_e). (and try to simplify/compute b^(m - min_e)). *) Ltac rew_pow_develop b m min_e H := let m_eq_plusminus := fresh in assert (m = min_e + (m - min_e)) as m_eq_plusminus by (rewrite Zplus_minus; reflexivity); rewrite m_eq_plusminus in H; clear m_eq_plusminus; rewrite (Z.pow_add_r b min_e (m - min_e)) in H; [ rewrite Z.mul_comm in H; let tm' := fresh "tm'" in let H' := fresh "H'" in remember (b ^ (m - min_e)) as tm' eqn:H' in H; let e := fresh "e" in evar (e: int); let Heqe := fresh in assert (e = m - min_e) as Heqe by (ring_simplify; subst e; reflexivity); rewrite <-Heqe in H'; clear Heqe; unfold e in H'; ring_simplify in H'; rewrite H' in H; clear H'; clear tm'; clear e; try rewrite Z.mul_1_l in H | ring_simplify; auto with zarith ..]. Ltac rew_pow_aux_goal b min_e normalized_acc := match goal with | |- context [ b ^ ?m ] => let tm := fresh "tm" in let Heqtm := fresh "Heqtm" in remember (b ^ m) as tm eqn:Heqtm in |- *; rew_pow_develop b m min_e Heqtm; [ rew_pow_aux_goal b min_e ((boxer (tm, Heqtm)) :: normalized_acc) | ..] | _ => subst_eq_boxer_list normalized_acc ltac:(fun E => rewrite E) end. Ltac rew_pow_aux_in b min_e H normalized_acc := match type of H with | context [ b ^ ?m ] => let tm := fresh "tm" in let Heqtm := fresh "Heqtm" in remember (b ^ m) as tm eqn:Heqtm in H; rew_pow_develop b m min_e Heqtm; [ rew_pow_aux_in b min_e H ((boxer (tm, Heqtm)) :: normalized_acc) | ..] | _ => subst_eq_boxer_list normalized_acc ltac:(fun E => rewrite E in H) end. Tactic Notation "rew_pow" constr(b) constr(min_e) := rew_pow_aux_goal b min_e (@nil Boxer). Tactic Notation "rew_pow" "~" constr(b) constr(min_e) := rew_pow_aux_goal b min_e (@nil Boxer); auto_tilde. Tactic Notation "rew_pow" "*" constr(b) constr(min_e) := rew_pow_aux_goal b min_e (@nil Boxer); auto_star. Tactic Notation "rew_pow" constr(b) constr(min_e) "in" hyp(H) := rew_pow_aux_in b min_e H (@nil Boxer). Tactic Notation "rew_pow" "~" constr(b) constr(min_e) "in" hyp(H) := rew_pow_aux_in b min_e H (@nil Boxer); auto_tilde. Tactic Notation "rew_pow" "*" constr(b) constr(min_e) "in" hyp(H) := rew_pow_aux_in b min_e H (@nil Boxer); auto_star. (* Test *) Axiom P : int -> Prop. Goal forall n, P (1 + 2 ^ (n + 3) + 2 ^ n + 2 ^ (n+1)). Proof. intros. skip_asserts H: (3 = 2 ^ (n+3)). rew_pow 2 n in H. rew_pow 2 n. Admitted. (* ---------------------------------------------------------------------------- *) (* Base 2 logarithm. *) Lemma Zlog2_step : forall x, 2 <= x -> 1 + Z.log2 (x÷2) = Z.log2 x. Proof. admit. (* TODO: prove from the log2_step in LibNatExtra? *) Qed.
# Upbit Open API # # ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [[email protected]] # # OpenAPI spec version: 1.0.0 # Contact: [email protected] # Generated by: https://github.com/swagger-api/swagger-codegen.git #' Ask Class #' #' @field currency #' @field price_unit #' @field min_total #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export Ask <- R6::R6Class( 'Ask', public = list( `currency` = NULL, `price_unit` = NULL, `min_total` = NULL, initialize = function(`currency`, `price_unit`, `min_total`){ if (!missing(`currency`)) { stopifnot(is.character(`currency`), length(`currency`) == 1) self$`currency` <- `currency` } if (!missing(`price_unit`)) { stopifnot(is.character(`price_unit`), length(`price_unit`) == 1) self$`price_unit` <- `price_unit` } if (!missing(`min_total`)) { self$`min_total` <- `min_total` } }, toJSON = function() { AskObject <- list() if (!is.null(self$`currency`)) { AskObject[['currency']] <- self$`currency` } if (!is.null(self$`price_unit`)) { AskObject[['price_unit']] <- self$`price_unit` } if (!is.null(self$`min_total`)) { AskObject[['min_total']] <- self$`min_total` } AskObject }, fromJSON = function(AskJson) { AskObject <- jsonlite::fromJSON(AskJson) if (!is.null(AskObject$`currency`)) { self$`currency` <- AskObject$`currency` } if (!is.null(AskObject$`price_unit`)) { self$`price_unit` <- AskObject$`price_unit` } if (!is.null(AskObject$`min_total`)) { self$`min_total` <- AskObject$`min_total` } }, toJSONString = function() { sprintf( '{ "currency": %s, "price_unit": %s, "min_total": %s }', self$`currency`, self$`price_unit`, self$`min_total` ) }, fromJSONString = function(AskJson) { AskObject <- jsonlite::fromJSON(AskJson) self$`currency` <- AskObject$`currency` self$`price_unit` <- AskObject$`price_unit` self$`min_total` <- AskObject$`min_total` } ) )
## Basic sympy setting ```python %reset -f from sympy import * # import everything from sympy module init_printing() # for nice math output ## forcing plots inside browser %matplotlib inline ``` ### Declare symbolic variables ```python x = symbols('x') ``` ### Example 1 Find 4-th degree Taylor polynamial of $f(x) = \sin(x)$ at $a = \frac{\pi}{2}$. Plot $f(x)$ and Taylor polynomial on the same window ```python ## Finding Taylor polynomial a = pi/2 f = sin(x) T = f.subs(x,a) \ + diff(f,x,1).subs(x,a)*(x-a) \ + diff(f,x,2).subs(x,a)*(x-a)**2/2 \ + diff(f,x,3).subs(x,a)*(x-a)**3/factorial(3) \ + diff(f,x,4).subs(x,a)*(x-a)**4/factorial(4) T ``` ```python ## plotting f(x) and T(x) in same window p = plot(f,T, (x,a - 4, a + 4),show=False, legend=True) p[0].line_color = 'blue' p[1].line_color = 'green' p[0].label = 'f(x)' p[1].label = 'T(x)' p.show() ``` ### Example 2 Find 20-th degree Taylor polynamial of $f(x) = \log(x)$ at $a = 1$. Plot $f(x)$ and Taylor polynomial on the same window ```python ## evaluation of T a = 1 n = 20 f = log(x) T = f.subs(x,a) for k in range(1,n+1): df = diff(f,x,k) T = T + df.subs(x,a)*(x-a)**k/factorial(k) T ``` ```python ## plotting f(x) and T(x) in same window p = plot(f,T, (x, 0.5, 2),show=False, legend=True) p[0].line_color = 'blue' p[1].line_color = 'green' p[0].label = 'f(x)' p[1].label = 'T(x)' p.show() ``` ```python ```
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details Class(PDTT_Base, TaggedNonTerminal, rec( abbrevs := [ n -> Checked(IsPosIntSym(n), [n]) ], dims := self >> [self.params[1], self.params[1]], isReal := True, print := (self,i,is) >> Print(self.__name__, "(", PrintCS(self.params), ")", When(self.transposed, Print(".transpose()")), When(self.tags<>[], Print(".withTags(", self.tags, ")"))), normalizedArithCost := self >> let(n := self.params[1], floor(2.5 * n * log(n) / log(2.0)) ) )); # # Discrete Trigonometric Transforms (DTTs) via PRF # Declare(PDST3, PDCT3); Class(PDST4, PDTT_Base, rec( transpose := self >> Copy(self), terminate := self >> Mat(DST_IVunscaled(EvalScalar(self.params[1]))), )); Class(PDCT4, PDTT_Base, rec( transpose := self >> Copy(self), terminate := self >> Mat(DCT_IVunscaled(EvalScalar(self.params[1]))), )); Class(PDCT2, PDTT_Base, rec( terminate := self >> Mat(DCT_IIunscaled(EvalScalar(self.params[1]))), transpose := self >> PDCT3(self.params[1]) )); Class(PDST2, PDTT_Base, rec( terminate := self >> Mat(DST_IIunscaled(EvalScalar(self.params[1]))), transpose := self >> PDST3(self.params[1]) )); Class(PDCT3, PDTT_Base, rec( terminate := self >> Mat(DCT_IIIunscaled(EvalScalar(self.params[1]))), transpose := self >> PDCT2(self.params[1]) )); Class(PDST3, PDTT_Base, rec( terminate := self >> Mat(DST_IIIunscaled(EvalScalar(self.params[1]))), transpose := self >> PDST2(self.params[1]) )); RulesFor(PDST4, rec( PDST4_Base2 := DST4_Base, #BaseRule(PDST4, 2), PDST4_CT := rec( isApplicable := P -> P[1] > 2, #not IsPrime(P), forTransposition := false, allChildren := P -> let(N := P[1], Map2(DivisorPairs(2*N), (m,n) -> Cond( IsEvenInt(m) and IsEvenInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n) ], #IsEvenInt(m) and IsEvenInt(n), [ PDHT3(m).transpose(), PDHT3(n) ], IsEvenInt(m) and IsOddInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n), PDST4(m/2) ], IsOddInt(m) and IsEvenInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n), PDST4(n/2) ], IsOddInt(m) and IsOddInt(n), Error("This can't happen")))), rule := (P,C) -> let(N := P[1], m := Rows(C[1]), n := Cols(C[2]), nf:=Int(n/2), nc:=Int((n+1)/2), mf:=Int(m/2), mc:=Int((m+1)/2), j:=Ind(nf), i:=Ind(mf), # mult twid by -E(4) for RDFT, by 1/2 for DHT t := ScaledTwid(2*N, mf, 1, 1/2, 1/2, j, -E(4)), T := When(IsOddInt(m), Diag(diagDirsum(t,fConst(1,1))), Diag(t)), Et := Tensor(I(mf),Mat([[0,-1],[-1,0]])), Ett := Tensor(I(mf),Mat([[0,-1],[1,0]])), SUM( ISum(j, Scat(BH(N, 2*N-1, m, j, n)) * C[1] * #Ett * RC(T) * #Et * # DHT only RC(Gath(H(mc*nc, mc, j, nc))) ), When(IsEvenInt(n), [], Scat(H(N,m/2,nf,n))*C[3]*Gath(H(2*mc*nc, m/2, 2*nf, 2*nc))) ) * SUM( ISum(i, RC(Scat(H(mc*nc, nc, i*nc, 1))) * C[2] * Gath(BH(N, 2*N-1, n, i, m))), # output is imaginary, but we output into real slot, because subseq transform # is jIR2, which we implement as IR2 * (-j) When(IsEvenInt(m), [], Scat(H(2*mc*nc, nc, 2*mf*nc, 2))*C[3]*Gath(H(N,n/2,mf,m))) ))), PDST4_CT_SPL := rec( isApplicable := P -> P[1] > 2 and ForAny(DivisorPairs(2*P[1]), d->IsEvenInt(d[1]) and IsEvenInt(d[2])), forTransposition := false, allChildren := P -> let(N := P[1], Map2(Filtered(DivisorPairs(2*N), d -> IsEvenInt(d[1]) and IsEvenInt(d[2])), (m,n) -> [ PRDFT3(m,-1).transpose(), PRDFT3(n) ])), rule := (P,C) -> let(N := P[1], m := Rows(C[1]), n := Cols(C[2]), TT := Diag(fPrecompute(diagMul(fConst(N/2, -E(4)), fCompose(dOmega(8 * N, 1), diagTensor(dLin(N/m, 2, 1, TInt), dLin(m/2, 2, 1, TInt)))))), Prm(Refl(N, 2*N-1, N, L(m*n, m))) * Tensor(I(n/2), C[1]) * RC(TT) * RC(L(m*n/4, n/2)) * Tensor(I(m/2), C[2]) * Prm(Refl(N, 2*N-1, N, L(m*n, m))) ) ) )); RulesFor(PDCT4, rec( PDCT4_Base2 := rec(isApplicable:=P->P[1]=2, rule:=(P,C)->DCT4(2).terminate()), PDCT4_Base4 := rec(isApplicable:=P->P[1]=4, allChildren := P -> [[ DCT4(4) ]], rule:=(P,C)->C[1]), PDCT4_CT := rec( isApplicable := P -> P[1] > 2, #not IsPrime(P), forTransposition := false, allChildren := P -> let(N := P[1], Map2(DivisorPairs(2*N), (m,n) -> Cond( IsEvenInt(m) and IsEvenInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n) ], #IsEvenInt(m) and IsEvenInt(n), [ PDHT3(m).transpose(), PDHT3(n) ], IsEvenInt(m) and IsOddInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n), PDCT4(m/2) ], IsOddInt(m) and IsEvenInt(n), [ PRDFT3(m,-1).transpose(), PRDFT3(n), PDCT4(n/2) ], IsOddInt(m) and IsOddInt(n), Error("This can't happen")))), rule := (P,C) -> let(N := P[1], m := Rows(C[1]), n := Cols(C[2]), nf:=Int(n/2), nc:=Int((n+1)/2), mf:=Int(m/2), mc:=Int((m+1)/2), j:=Ind(nf), i:=Ind(mf), t := fPrecompute(Twid(2*N, mf, 1, 1/2, 1/2, j)), T := When(IsOddInt(m), Diag(diagDirsum(t,fConst(1,1))), Diag(t)), Et := Tensor(I(mf),Mat([[0,1],[1,0]])), SUM( ISum(j, Scat(BH(N, 2*N-1, m, j, n)) * Diag(BHN(m)) * C[1] * # mult twid by 1/2 for DHT RC(T) * #Et * # DHT only RC(Gath(H(mc*nc, mc, j, nc))) ), When(IsEvenInt(n), [], Scat(H(N,m/2,nf,n))*C[3]*Gath(H(2*mc*nc, m/2, 2*nf, 2*nc))) ) * SUM( ISum(i, RC(Scat(H(mc*nc, nc, i*nc, 1))) * C[2] * Diag(BHN(n)) * Gath(BH(N, 2*N-1, n, i, m))), When(IsEvenInt(m), [], Scat(H(2*mc*nc, nc, 2*mf*nc, 2))*C[3]*Gath(H(N,n/2,mf,m))) ))), )); NewRulesFor(PDCT4, rec( PDCT4_CT_SPL := rec( libApplicable := t -> eq(imod(t.params[1], 2), 0), applicable := t -> IsSymbolic(t.params[1]) or (t.params[1] > 2 and (t.params[1] mod 4) = 0), extraLeftTags := [], forTransposition := false, freedoms := t -> [ divisorsIntNonTriv(t.params[1]/2) ], child := (self, t, fr) >> let(N := t.params[1], f := fr[1], [ spiral.sym.ASP(-1).RDFT3(2*f).withTags(self.extraLeftTags).transpose(), spiral.sym.ASP.RDFT3(div(N,f)) ]), apply := (t,C,Nonterms) -> let(N := t.params[1], m := Rows(C[1]), n := Cols(C[2]), mh := Rows(C[1])/2, nh := Cols(C[2])/2, D := RC(Diag(fPrecompute(fCompose(dOmega(8 * N, 1), diagTensor(dLin(N/m, 2, 1, TInt), dLin(m/2, 2, 1, TInt)))))), Grp(Scat(Refl1(nh, m)) * Tensor(I(nh), Diag(BHN(m)) * C[1]) * D * Tensor(I(nh), Tr(2, mh))) * #RC(Tr(mh, nh)) * Grp(Tr(mh, n) * Tensor(I(mh), C[2] * Diag(BHN(n))) * Gath(Refl1(mh, n))) ) ) )); RulesFor(PDCT4, rec( # Variant better suited for vectorization PDCT4_CT_SPL_Vec := rec( isApplicable := P -> P[1] > 2 and (P[1] mod 2) = 0, forTransposition := false, allChildren := P -> let(N := P[1], Map2(Filtered(DivisorPairs(2*N), d -> IsEvenInt(d[1]) and IsEvenInt(d[2])), (m,n) -> [ PRDFT3(m,-1).transpose(), PRDFT3(n) ])), rule := (P,C) -> let(N := P[1], m := Rows(C[1]), n := Cols(C[2]), TT := Diag(fPrecompute(fCompose(dOmega(8 * N, 1), diagTensor(dLin(N/m, 2, 1, TInt), dLin(m/2, 2, 1, TInt))))), Prm(condIJ(N, n/2)) * Prm(L(N, m)) * Tensor(I(n/2), condM(m,m/2) * Diag(BHN(m)) * C[1]) * RC(TT) * Prm(L(N, n/2)) * Tensor(I(m/2), L(n, 2) * C[2] * Diag(BHN(n)) * condK(n, 2)) * Prm(L(N, m/2)) * Prm(condIJ(N, m/2)) ) ) )); testPDCT4 := function(n) local opts, r, s; opts := CopyFields(SpiralDefaults, rec( breakdownRules := rec( PDCT4 := [PDCT4_Base2, PDCT4_CT_SPL_Vec], PRDFT1 := [PRDFT1_Base1, PRDFT1_Base2, PRDFT1_CT], PRDFT3 := [PRDFT3_Base1, PRDFT3_Base2, PRDFT3_CT], DFT := [DFT_Base, DFT_CT] ))); r := RandomRuleTree(PDCT4(n), opts); s := SumsRuleTree(r, opts); return [opts,r,s]; end; NewRulesFor(PDCT2, rec( PDCT2_Base2 := rec( forTransposition := true, applicable := t -> t.params[1] = 2, apply := (t, C, Nonterms) -> DCT2(2).terminate() ), PDCT2_Base4 := rec( forTransposition := true, applicable := t -> t.params[1] = 4, apply := (t, C, Nonterms) -> LIJ(4) * DirectSum( Diag(FList(TReal, [ 1, 0.70710678118654757 ])) * F(2), Rot(cospi(13/8), sinpi(13/8)) * J(2)) * (Tensor(I(2), F(2))) ^ LIJ(4) ), PDCT2_CT_SPL := rec( forTransposition := true, libApplicable := t -> eq(imod(t.params[1], 2), 0), extraLeftTags := [], applicable := t -> let(N:=t.params[1], IsSymbolic(N) or (N > 2 and IsEvenInt(N) and (N mod 4) = 0)), freedoms := t -> [ divisorsIntNonTriv(t.params[1]/2) ], # N/2 = k*m child := (self, t, fr) >> let(N:=t.params[1], k:=fr[1], m:=N/2/k, [ PDCT2(2*k).withTags(self.extraLeftTags), spiral.sym.ASP(-1).RDFT3(2*k).transpose().withTags(self.extraLeftTags), spiral.sym.ASP(+1).URDFT(2*m) ]), apply := (t,C,Nonterms) -> let(N:=t.params[1], k:=Rows(C[1])/2, m:=Cols(C[3])/2, D := RC(Diag(fPrecompute(fCompose(dOmega(4 * N, 1), diagTensor(dLin(m-1, 1, 1, TInt), dLin(k, 2, 1, TInt)))))), Grp( Scat(Refl0_u(m, 2*k)) * DirectSum( C[1] * KK(k, 2), Tensor(I(m-1), Diag(BHN(2*k)) * C[2]) * D )) * Grp( RC(Tr(k, m)) * Tensor(I(k), C[3]) * Gath(Refl1(k, 2*m)) ) ) ) )); NewRulesFor(PDST2, rec( PDST2_Base2 := rec( applicable := t -> t.params[1] = 2, apply := (t, C, Nonterms) -> DST2(2).terminate() ), PDST2_CT_SPL := rec( forTransposition := true, applicable := t -> let(N:=t.params[1], N > 2 and IsEvenInt(N) and (N mod 4) = 0), freedoms := t -> [ DivisorsIntNonTriv(t.params[1]/2) ], # N/2 = k*m child := (t, fr) -> let(N:=t.params, k:=fr[1], m:=N/2/k, [ DST2(2*k), PRDFT3(2*k,-1).transpose(), URDFT(2*m) ]), apply := (t,C,Nonterms) -> let(N:=t.params[1], k:=Rows(C[1])/2, m:=Cols(C[3])/2, TT := Diag(fPrecompute(fCompose(dOmega(4 * N, 1), # ie multiply all twiddles by -E(4) diagAdd(diagDirsum(fConst(k, 0), fConst(k*(m-1), 3*N)), diagTensor(dLin(m, 1, 0, TInt), dLin(k, 2, 1, TInt)))))), J(N) * Kp(N, 2*k) * DirectSum( J(2*k) * C[1] * Diag(BHN(2*k)) * K(2*k, 2), Tensor(I(m-1), J(2*k) * M(2*k, k) * C[2]) ) * RC(TT) * RC(L(N/2, m)) * Tensor(I(k), C[3] * Diag(BHN(2*m))) * Prm(Refl(N, 2*N-1, N, L(2*N, 2*k))) ) ) )); RulesFor(DCT5, rec( DCT5_Rader := rec( forTransposition := false, isApplicable := P -> P > 2 and IsPrime(2*P-1), allChildren := P -> [[ IPRDFT(P-1,-1), PRDFT(P-1,-1) ]], diag := N -> Sublist( DFT_Rader.raderDiag(2*N-1,1,PrimitiveRootMod(2*N-1)), [1..Int((N-1)/2)]*2), # 3rd col with 0's is for PRDFT, not necessary for (non-packed) RDFT raderMid := (self, N) >> let(Fsize := 2*N-1, DirectSum(Mat([[1, 1, 0], [1, -1/(Fsize-1), 0], [0,0,0]]), RC(Diag(FData(self.diag(N)))))), # NOTE, special case for even P-1 rule := (self,P,C) >> let(N := P, #RealRR(N).transpose() * Gath(H(2*P-1, P, 0, 1)) * RR(2*P-1).transpose() * DirectSum(I(1), VStack(I(P-1), I(P-1))) * DirectSum(I(1), C[1]) * # C[1]*Diag(1,1, Replicate(2*Int((P-2)/2), 2), # When(IsEvenInt(P-1), [1,1],[]))) * self.raderMid(N) * DirectSum(I(1), C[2]) * # replace by RealRR Gath(H(2*P-1, P, 0, 1)) * RR(2*P-1) * DirectSum(I(1), VStack(I(P-1), J(P-1))) )) )); #q:=ExpandSPL(DCT5(6))[1]; #s:=SPLRuleTree(q); #me := MatSPL(s); #them := remat(MatSPL(q.node)); #RDFT-11, DCT5(6) 15(6/9 rots) + 19(12/7 irdft) + 17(12/5 rdft) = 30/21 = 51 # DST5(5) # 10(blk) # fftw 60/50 # RDFT-13 # DCT5(7) 18(8/10=4/8+0/1+2/1 rots) + 18(14/4 irdft) + 18(14/4 rdft) = 36/18=54 # DST5(6) # 12(blk) # fftw 76/34=110 # DFT-13 # fftw 176+68=244 # us = 54*2 (dct5) + 24(blk)*2 + dst5
module Main import Test.Golden prefixFolder : String -> List String -> List String prefixFolder pref paths = map ((pref ++ "/") ++) paths lexerTests : TestPool lexerTests = MkTestPool "Lexer Tests" [] Nothing $ prefixFolder "lexer" ["call", "all", "readme"] main : IO () main = runner $ [ lexerTests ]
-- 2014-04-06 Andreas, issue reported by flickyfrans -- {-# OPTIONS --show-implicit -v tc.section.apply:60 #-} open import Common.Level renaming (lsuc to suc) record RawMonad {α β : Level} (M : {γ : Level} → Set γ → Set γ) : Set (suc (α ⊔ β)) where infixl 1 _>>=_ field return' : {A : Set α} → A → M A _>>=_ : {A : Set α} {B : Set β} → M A → (A → M B) → M B module MonoMonad {α} = RawMonad {α} {α} module MM = MonoMonad {{...}} -- return : {α : Level} {M : {γ : Level} → Set γ → Set γ} {{m : RawMonad {α} {α} M }} {A : Set α} → A → M A return : _ return = MM.return' -- WAS: Panic: deBruijn index out of scope: 2 in context [M,α] -- when checking that the expression MM.return' has type _15 -- CAUSE: Ill-formed section telescope produced by checkSectionApplication. -- NOW: Works.
/*! \file \brief A text encoder. Copyright (C) 2019-2022 kaoru https://www.tetengo.org/ */ #if !defined(TETENGO_PLATFORMDEPENDENT_TEXTENCODER_HPP) #define TETENGO_PLATFORMDEPENDENT_TEXTENCODER_HPP #include <memory> #include <string> #include <string_view> #include <boost/core/noncopyable.hpp> namespace tetengo::platform_dependent { /*! \brief A text encoder. */ class text_encoder : private boost::noncopyable { public: // static functions /*! \brief Returns the instance. \return The instance. */ [[nodiscard]] static const text_encoder& instance(); // constructors and destructor /*! \brief Destroys the text encoder. */ ~text_encoder(); // functions /*! \brief Encodes a string to CP932. \param utf8 A string in UTF-8. \return A string in CP932. */ [[nodiscard]] std::string encode_to_cp932(const std::string_view& utf8) const; /*! \brief Decodes a string from CP932. \param cp932 A string in CP932. \return A string in UTF-8. */ [[nodiscard]] std::string decode_from_cp932(const std::string_view& cp932) const; private: // types class impl; // variables const std::unique_ptr<impl> m_p_impl; // constructors text_encoder(); }; } #endif
## This script uses the output of the QC.r & methylationDerivedVariables.r scripts and extends our ASD case control analysis to include an interaction with gender ## Filepaths and sample IDs have been removed for security reasons, therefore it serves as a guide to the analysis only setwd("") load("QCed_Data.rda") crosshyb<-read.csv("/data/Non_iPSYCH_Projects/Minerva/FromEilis/450KAnno/CrossHybridisingProbesPriceORWeksberg.csv", row.names = 1) probes<-read.csv("/data/Non_iPSYCH_Projects/Minerva/FromEilis/450KAnno/SNPsinProbesAnno.csv", row.names = 1) ## remove cross hybridising probes remove<-match(crosshyb[,1], rownames(betas)) remove<-remove[which(is.na(remove) != TRUE)] betas<-betas[-remove,] ## remove SNP probes as not a twin analysis probes<-probes[row.names(betas),] betas<-betas[which(probes$Weksburg_CommonSNP_Af_within10bpSBE == "" | probes$Illumina_CommonSNP_Af_within10bpSBE == ""),] betas<-betas[-grep("rs", rownames(betas)),] ## load cellular composition variables counts<-read.csv("Analysis/HousemanEstimatedCellCounts.csv", stringsAsFactors = FALSE, row.names = 1) counts<-counts[match(colnames(betas) ,rownames(counts)),] ### alternatively use smokingScores scores<-read.csv("Analysis/QC/SmokingScores.csv", stringsAsFactors = FALSE, row.names = 1) scores<-scores[match(colnames(betas), scores$Basename),] pheno<-read.csv("", stringsAsFactors = FALSE) ### reformat to match DNA methylation data pheno.cont<-pheno[,c(22,18,grep("cont", colnames(pheno)))] pheno.case<-pheno[,c(21,18,grep("case", colnames(pheno)))] pheno.cont<-cbind(pheno.cont, "Con") pheno.case<-cbind(pheno.case, "Case") colnames(pheno.cont)<-gsub("_cont", "", colnames(pheno.cont)) colnames(pheno.case)<-gsub("_case", "", colnames(pheno.case)) colnames(pheno.cont)[1]<-"participiant_id" colnames(pheno.case)[1]<-"participiant_id" colnames(pheno.cont)[13]<-"CasCon" colnames(pheno.case)[13]<-"CasCon" pheno<-rbind(pheno.cont,pheno.case) pheno$participiant_id<-gsub("MMXII_iPSYCH_", "", pheno$participiant_id) pheno<-pheno[(match(sampleSheet$Sample_Name, pheno$participiant_id)),] birthMonth<-unlist(strsplit(pheno$fdato, "/"))[seq(from = 2, by = 3, to = 3*nrow(pheno))] birthMonth<-factor(birthMonth) birthYear<-unlist(strsplit(pheno$fdato, "/"))[seq(from = 3, by = 3, to = 3*nrow(pheno))] birthYear<-factor(birthYear) res<-matrix(data = NA, nrow = nrow(betas), ncol = 15) colnames(res)<-c("Aut:Females:P-value", "Aut:Females:MeanDiff", "Aut:Females:SE","Aut:Males:P-value", "Aut:Males:MeanDiff", "Aut:Males:SE","Aut:P-value", "Aut:MeanDiff", "Aut:SE", "Gender:P-value", "Gender:MeanDiff", "Gender:SE", "Int:P-value", "Int:MeanDiff", "Int:SE") rownames(res)<-rownames(betas) for(i in 1:nrow(betas)){ model<-lm(betas[i,] ~ as.factor(sampleSheet$CaCo) + as.factor(sampleSheet$Sentrix_ID) + counts[,1] + counts[,2] + counts[,3] + counts[,4] + counts[,5] + counts[,6] + scores$scores_combined_A + birthMonth + birthYear + as.factor(pheno$geo5) + pheno$gest_week, subset = which(sampleSheet$gender.x.chr == "F")) res[i,1:3]<-summary(model)$coefficients["as.factor(sampleSheet$CaCo)Ctrl", c(4,1,2)] model<-lm(betas[i,] ~ as.factor(sampleSheet$CaCo) + as.factor(sampleSheet$Sentrix_ID) + counts[,1] + counts[,2] + counts[,3] + counts[,4] + counts[,5] + counts[,6] + scores$scores_combined_A + birthMonth + birthYear + as.factor(pheno$geo5) + pheno$gest_week, subset = which(sampleSheet$gender.x.chr == "M")) res[i,4:6]<-summary(model)$coefficients["as.factor(sampleSheet$CaCo)Ctrl", c(4,1,2)] model<-lm(betas[i,] ~ as.factor(sampleSheet$CaCo) + as.factor(sampleSheet$gender.x.chr) + as.factor(sampleSheet$CaCo)*as.factor(sampleSheet$gender.x.chr) + as.factor(sampleSheet$Sentrix_ID) + counts[,1] + counts[,2] + counts[,3] + counts[,4] + counts[,5] + counts[,6] + scores$scores_combined_A + birthMonth + birthYear + as.factor(pheno$geo5) + pheno$gest_week) res[i,13:15]<-summary(model)$coefficients["as.factor(sampleSheet$CaCo)Ctrl:as.factor(sampleSheet$gender.x.chr)M", c(4,1,2)] res[i,7:9]<-summary(model)$coefficients["as.factor(sampleSheet$CaCo)Ctrl", c(4,1,2)] res[i,10:12]<-summary(model)$coefficients["as.factor(sampleSheet$gender.x.chr)M", c(4,1,2)] } library(IlluminaHumanMethylation450kanno.ilmn12.hg19) data(IlluminaHumanMethylation450kanno.ilmn12.hg19) probeAnnot<-as.data.frame(IlluminaHumanMethylation450kanno.ilmn12.hg19@data$Locations) probeAnnot<-probeAnnot[rownames(betas),] res<-cbind(res, probeAnnot) probeAnnot<-as.data.frame(IlluminaHumanMethylation450kanno.ilmn12.hg19@data$Other) probeAnnot<-probeAnnot[rownames(betas),] res<-cbind(res, probeAnnot) write.csv(res, "Analysis/Aut_InteractionwithGender_wCovariates.csv")
[GOAL] α β : FinBddDistLatCat e : ↑α.toBddDistLatCat.toDistLatCat ≃o ↑β.toBddDistLatCat.toDistLatCat ⊢ ((let src := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }; { toLatticeHom := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑e ⊤ = ⊤), map_bot' := (_ : ↑e ⊥ = ⊥) }) ≫ let src := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }; { toLatticeHom := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤), map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) }) = 𝟙 α [PROOFSTEP] ext [GOAL] case w α β : FinBddDistLatCat e : ↑α.toBddDistLatCat.toDistLatCat ≃o ↑β.toBddDistLatCat.toDistLatCat x✝ : (forget FinBddDistLatCat).obj α ⊢ ↑((let src := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }; { toLatticeHom := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑e ⊤ = ⊤), map_bot' := (_ : ↑e ⊥ = ⊥) }) ≫ let src := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }; { toLatticeHom := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤), map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) }) x✝ = ↑(𝟙 α) x✝ [PROOFSTEP] exact e.symm_apply_apply _ [GOAL] α β : FinBddDistLatCat e : ↑α.toBddDistLatCat.toDistLatCat ≃o ↑β.toBddDistLatCat.toDistLatCat ⊢ ((let src := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }; { toLatticeHom := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤), map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) }) ≫ let src := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }; { toLatticeHom := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑e ⊤ = ⊤), map_bot' := (_ : ↑e ⊥ = ⊥) }) = 𝟙 β [PROOFSTEP] ext [GOAL] case w α β : FinBddDistLatCat e : ↑α.toBddDistLatCat.toDistLatCat ≃o ↑β.toBddDistLatCat.toDistLatCat x✝ : (forget FinBddDistLatCat).obj β ⊢ ↑((let src := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }; { toLatticeHom := { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑(OrderIso.symm e), map_sup' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑β.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑(OrderIso.symm e) ⊤ = ⊤), map_bot' := (_ : ↑(OrderIso.symm e) ⊥ = ⊥) }) ≫ let src := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }; { toLatticeHom := { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom (a ⊔ b) = SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom a ⊔ SupHom.toFun { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) }.toSupHom b) }, map_inf' := (_ : ∀ (a b : ↑α.toBddDistLatCat.toDistLatCat), SupHom.toFun src.toSupHom (a ⊓ b) = SupHom.toFun src.toSupHom a ⊓ SupHom.toFun src.toSupHom b) }, map_top' := (_ : ↑e ⊤ = ⊤), map_bot' := (_ : ↑e ⊥ = ⊥) }) x✝ = ↑(𝟙 β) x✝ [PROOFSTEP] exact e.apply_symm_apply _
// // Copyright 2010 Scott McMurray. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_HASH_DIGEST_HPP #define BOOST_HASH_DIGEST_HPP #include <boost/array.hpp> #include <boost/integer.hpp> #include <boost/static_assert.hpp> #include <string> #include <cstring> namespace boost { namespace hashes { unsigned const octet_bits = 8; typedef uint_t<octet_bits>::least octet_type; // Always stored internally as a sequence of octets in display order. // This allows digests from different algorithms to have the same type, // allowing them to be more easily stored and compared. template <unsigned digest_bits_> class digest : public array<octet_type, digest_bits_/octet_bits> { public: static unsigned const digest_bits = digest_bits_; BOOST_STATIC_ASSERT(digest_bits % octet_bits == 0); static unsigned const digest_octets = digest_bits/octet_bits; typedef array<octet_type, digest_octets> base_array_type; static unsigned const cstring_size = digest_bits/4 + 1; typedef array<char, cstring_size> cstring_type; digest() : base_array_type() {} digest(base_array_type const &a) : base_array_type(a) {} template <typename oit_T> oit_T to_ascii(oit_T it) const { for (unsigned j = 0; j < digest_octets; ++j) { octet_type b = base_array()[j]; *it++ = "0123456789abcdef"[(b >> 4) & 0xF]; *it++ = "0123456789abcdef"[(b >> 0) & 0xF]; } return it; } std::string str() const { cstring_type cstr = cstring(); return std::string(cstr.data(), cstr.size()-1); } cstring_type cstring() const { cstring_type s; char *p = to_ascii(s.data()); *p++ = '\0'; return s; } base_array_type const &base_array() const { return *this; } }; template <unsigned NDB, unsigned ODB> digest<NDB> resize(digest<ODB> const &od) { digest<NDB> nd; unsigned bytes = sizeof(octet_type)*(NDB < ODB ? NDB : ODB)/octet_bits; std::memcpy(nd.data(), od.data(), bytes); return nd; } template <unsigned NDB, unsigned ODB> digest<NDB> truncate(digest<ODB> const &od) { BOOST_STATIC_ASSERT(NDB <= ODB); return resize<NDB>(od); } template <unsigned DB1, unsigned DB2> bool operator==(digest<DB1> const &a, digest<DB2> const &b) { unsigned const DB = DB1 < DB2 ? DB2 : DB1; return resize<DB>(a).base_array() == resize<DB>(b).base_array(); } template <unsigned DB1, unsigned DB2> bool operator!=(digest<DB1> const &a, digest<DB2> const &b) { return !(a == b); } template <unsigned DB1, unsigned DB2> bool operator<(digest<DB1> const &a, digest<DB2> const &b) { unsigned const DB = DB1 < DB2 ? DB2 : DB1; return resize<DB>(a).base_array() < resize<DB>(b).base_array(); } template <unsigned DB1, unsigned DB2> bool operator>(digest<DB1> const &a, digest<DB2> const &b) { return b < a; } template <unsigned DB1, unsigned DB2> bool operator<=(digest<DB1> const &a, digest<DB2> const &b) { return !(b < a); } template <unsigned DB1, unsigned DB2> bool operator>=(digest<DB1> const &a, digest<DB2> const &b) { return !(b > a); } template <unsigned DB> bool operator!=(digest<DB> const &a, char const *b) { BOOST_ASSERT(std::strlen(b) == DB/4); return std::strcmp(a.cstring().data(), b); } template <unsigned DB> bool operator==(digest<DB> const &a, char const *b) { return !(a != b); } template <unsigned DB> bool operator!=(char const *b, digest<DB> const &a) { return a != b; } template <unsigned DB> bool operator==(char const *b, digest<DB> const &a) { return a == b; } } // namespace hashes } // namespace boost #endif // BOOST_HASH_DIGEST_HPP
c leemodi222 c iesc=0 :lee dos atmosferas modelo contando puntos en tau de la 1 c iesc=1 :escribe dos atmosferas modelo c ntau : numero de puntos en tau c tau : log10(tau) c ierror=0 O.K. ierror=1 el modelo 1 no existe, ierror=2 el modelo 2 no existe c ierror=3 no existen los modelos 1 ni 2 subroutine leemodi222(iesc,model1,model2,atmos,ntau,ierror, & z1,pg1,ro1,z2,pg2,ro2) include 'PARAMETER' !por kt real*4 atmos(*),a(8) real*4 pg1(*),z1(*),ro1(*) real*4 pg2(*),z2(*),ro2(*) character model1*(*),model2*(*) character*100 control character*80 men1 common/canal/icanal common/nombrecontrol/control common/nohaycampo/nohaycampo1,nohaycampo2 common/nciclos/nciclos !para marquardt, leeuve3, leemodi2 epsilon=2.e-5 ican=52 if(iesc.eq.0)then c contamos las lineas del modelo 1 if(ierror.ne.1)then open(ican,file=model1,status='old',err=991) ntau=0 read(ican,*,err=999)a(1),fill1,peso1 do while(ntau.lt.kt) ntau=ntau+1 read(ican,*,end=221,err=999)a end do 221 ntau=ntau-1 close(ican) c ahora leemos el modelo 1 open(ican,file=model1) read(ican,*,err=999)atmos(8*ntau+1),atmos(8*ntau+2),pesostray do i=1,ntau read(ican,*,err=999)(atmos(i+j*ntau),j=0,7),z1(i),pg1(i),ro1(i) end do close(ican) end if c contamos las lineas del modelo 2 if(ierror.ne.2)then open(ican,file=model2,status='old',err=992) ntau2=0 read(ican,*,err=999)a(1),fill2 do while(ntau2.lt.kt) ntau2=ntau2+1 read(ican,*,end=222,err=999)a,z2(i),pg2(i),ro2(i) end do 222 ntau2=ntau2-1 close(ican) go to 993 !el fichero del modelo 2 no existe 992 ierror=2 if(abs(fill1-1.0).ne.0)then men1=' WARNING: The FILLING FACTOR is being changed to 1.0' print*,men1 c open(icanal,file=control,fileopt='eof') c write(icanal,*) men1 c close(icanal) endif fill1=1. fill2=0. ntau2=ntau do i=1,ntau do j=0,2 atmos(i+(8+j)*ntau+2)=atmos(i+j*ntau) end do do j=3,7 atmos(i+(8+j)*ntau+2)=0. end do end do nohaycampo2=0 nohaycampo1=0 do i=1,ntau if(abs(atmos(4*ntau+i)).gt.1.)nohaycampo1=1 end do if(pesostray.lt.0..or.pesostray.gt.100.) then men1='STOP: In model 1, the stray light factor is outside the interval [0,100]' call mensaje(1,men1,men1,men1) endif atmos(16*ntau+5)=pesostray !% de luz difusa c Comprobamos que el modelo esta equiespaciado y con tau decreciente paso=atmos(2)-atmos(1) if(paso.ge.0)then men1='STOP: The model supplied is NOT ordered with DECREASING log(tau).' call mensaje(1,men1,men1,men1) end if do i=2,ntau-1 paso1=atmos(i+1)-atmos(i) if(abs(paso1-paso).gt.epsilon)then if(nciclos.gt.0)then men1='STOP: For inversion, an EQUALLY SPACED grid is required to discretize the model.' call mensaje(1,men1,men1,men1) endif end if end do return 993 if(ntau2.ne.ntau)then men1='STOP: The initial models are discretized in DIFFERENT SPATIAL GRIDS.' call mensaje(1,men1,men1,men1) end if end if c comprobamos que fill1 esta en el intervalo [0,1] if(fill1.lt.0.or.fill1.gt.1.)then men1='STOP: For model 1, the filling factor is outside the interval [0,1] ' call mensaje(1,men1,men1,men1) end if if(abs(1-(fill1+fill2)).gt.epsilon)then fill2=1.-fill1 print*,' WARNING: For model 2, the filling factor is taken to be ',fill2 end if c ahora leemos los dos modelos open(ican,file=model1) read(ican,*,err=999)atmos(8*ntau+1),atmos(8*ntau+2),peso1 do i=1,ntau read(ican,*,err=999)(atmos(i+j*ntau),j=0,7),z1(i),pg1(i),ro1(i) end do close(ican) open(ican,file=model2) read(ican,*,err=999)atmos(16*ntau+3),atmos(16*ntau+4),peso2 do i=1,ntau read(ican,*,err=999)(atmos(i+j*ntau+2),j=8,15),z2(i),pg2(i),ro2(i) end do close(ican) if(peso1.lt.0..or.peso1.gt.100.) then men1='STOP: In model 1, the stray light factor is outside the interval [0,100] ' call mensaje(1,men1,men1,men1) endif if(peso1.ne.peso2)then print*,' WARNING: The stray light factor is DIFFERENT in models 1 and 2.' print*,' Its value in model 1 is being adopted:',peso1 c open(icanal,file=control,fileopt='eof') c write(icanal,*)' WARNING: The stray light factor is DIFFERENT in models 1 and 2.' c write(icanal,*)' Its value in model 1 is being adopted:',peso1 c close(icanal) endif atmos(16*ntau+5)=peso1 !% de luz difusa atmos(8*ntau+2)=fill1 c comprobamos que estan equiespaciados y con tau decreciente paso=atmos(2)-atmos(1) if(paso.ge.0)then men1='STOP: The models supplied are NOT ordered with DECREASING log(tau).' call mensaje(1,men1,men1,men1) end if do i=2,ntau-1 paso1=atmos(i+1)-atmos(i) paso2=atmos(8*ntau+i+3)-atmos(8*ntau+i+2) if(abs(paso1-paso).gt.epsilon)then if(nciclos.gt.0)then men1='STOP: Model 1 is NOT equally spaced. For inversion, an evenly spaced grid is required' call mensaje(1,men1,men1,men1) endif end if if(abs(paso2-paso1).gt.epsilon)then men1='STOP: The same spatial grid has to be used to discretize models 1 and 2.' call mensaje(1,men1,men1,men1) end if end do nohaycampo1=0 nohaycampo2=0 do i=1,ntau if(abs(atmos(4*ntau+i)).gt.1.)nohaycampo1=1 if(abs(atmos(12*ntau+i+2)).gt.1.)nohaycampo2=1 end do else c escribimos los modelos peso=atmos(16*ntau+5) open(ican,file=model1,err=990) goto 800 990 print*,' ' print*,'WARNING: The file containing model 1 does NOT exist' ierror=1 goto 989 800 write(ican,*)atmos(8*ntau+1),atmos(8*ntau+2),peso do i=1,ntau if(atmos(i+ntau) .lt. 0)atmos(i+ntau)=0. !T if(atmos(i+ntau) .gt. 9.999e4)atmos(i+ntau)=9.999e4 !T write(ican,100)(atmos(i+j*ntau),j=0,7),z1(i),pg1(i),ro1(i) end do close(ican) 989 if(ierror.eq.0)then open(ican,file=model2,err=988) write(ican,*)atmos(16*ntau+3),atmos(16*ntau+4),peso do i=1,ntau if(atmos(i+9*ntau+2) .lt. 0)atmos(i+9*ntau+2)=0. !T if(atmos(i+9*ntau+2) .gt. 9.999e4)atmos(i+9*ntau+2)=9.999e4 !T write(ican,100)(atmos(i+j*ntau+2),j=8,15),z2(i),pg2(i),ro2(i) end do close(ican) end if end if 100 format(1x,f7.4,1x,f8.1,1x,1pe12.5,1x,e10.3,1x,7(e11.4,1x)) return 991 men1='STOP: The file containing model 1 does NOT exist' call mensaje(1,men1,men1,men1) 988 print*,'WARNING: Is the file containing model 2, ',model2,', unexistent?? ' if(ierror.eq.0)then ierror=2 else ierror=3 end if return 999 men1='STOP: Incorrect format in the file(s) containing the model(s).' call mensaje(1,men1,men1,men1) end
% EX_ARTICLE_SECTION_513: short example with macro-element integration rule. % % Example to solve the problem % % - div ( grad (u)) = (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2) in Omega % u = 0 on Gamma % % with Omega = (1 < x^2+y^2 < 4) & (x > 0) & (y > 0) % and exact solution u = (x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x)) % % using a quadrature rule on macro-elements as proposed in % % % [1] Hughes, Reali, Sangalli. Comput. Methods Appl. Mech. Engrg. % Volume 199, Issues 5-8, 1 January 2010, Pages 301-313 % % This is the example of Section 5.1.3 in the article % % C. De Falco, A. Reali, R. Vazquez % GeoPDEs: a research tool for IsoGeometric Analysis of PDEs % % Copyright (C) 2009, 2010 Carlo de Falco % Copyright (C) 2011, 2015 Rafael Vazquez % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. nodes = [5.168367524056075e-02, 2.149829914261059e-01, ... 3.547033685486441e-01, 5.000000000000000e-01, ... 6.452966314513557e-01, 7.850170085738940e-01, ... 9.483163247594394e-01]; weights = [1.254676875668223e-01, 1.708286087294738e-01, ... 1.218323586744639e-01, 1.637426900584793e-01, ... 1.218323586744638e-01, 1.708286087294741e-01, ... 1.254676875668223e-01]; rule = [nodes; weights]; geometry = geo_load ({@ring_polar_map, @ring_polar_map_der}); [knots, breaks] = kntuniform ([10 10], [2 2], [1 1]); breaks{1} ([2:3:end-2,3:3:end-1]) = []; breaks{2} ([2:3:end-2,3:3:end-1]) = []; [qn, qw] = msh_set_quad_nodes (breaks, {rule, rule}, [0 1]); msh = msh_cartesian (breaks, qn, qw, geometry); space = sp_bspline (knots, [2, 2], msh); mat = op_gradu_gradv_tp (space, space, msh); rhs = op_f_v_tp (space, msh, @(x, y) (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2)); drchlt_dofs = []; for iside = 1:4 drchlt_dofs = union (drchlt_dofs, space.boundary(iside).dofs); end int_dofs = setdiff (1:space.ndof, drchlt_dofs); u = zeros (space.ndof, 1); u(int_dofs) = mat(int_dofs, int_dofs) \ rhs(int_dofs); sp_to_vtk (u, space, geometry, [20 20], 'laplace_solution.vts', 'u') err = sp_l2_error (space, msh, u, @(x,y)(x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x))) %!demo %! ex_article_section_513; %!test %! nodes = [5.168367524056075e-02, 2.149829914261059e-01, ... %! 3.547033685486441e-01, 5.000000000000000e-01, ... %! 6.452966314513557e-01, 7.850170085738940e-01, ... %! 9.483163247594394e-01]; %! weights = [1.254676875668223e-01, 1.708286087294738e-01, ... %! 1.218323586744639e-01, 1.637426900584793e-01, ... %! 1.218323586744638e-01, 1.708286087294741e-01, ... %! 1.254676875668223e-01]; %! rule = [nodes; weights]; %! geometry = geo_load ({@ring_polar_map, @ring_polar_map_der}); %! [knots, breaks] = kntuniform ([10 10], [2 2], [1 1]); %! breaks{1} ([2:3:end-2,3:3:end-1]) = []; %! breaks{2} ([2:3:end-2,3:3:end-1]) = []; %! [qn, qw] = msh_set_quad_nodes (breaks, {rule, rule}, [0 1]); %! msh = msh_cartesian (breaks, qn, qw, geometry); %! space = sp_bspline (knots, [2, 2], msh); %! mat = op_gradu_gradv_tp (space, space, msh, @(x, y) ones (size (x))); %! rhs = op_f_v_tp (space, msh, @(x, y) (8-9*sqrt(x.^2+y.^2)).*sin(2*atan(y./x))./(x.^2+y.^2)); %! drchlt_dofs = []; %! for iside = 1:4 %! drchlt_dofs = union (drchlt_dofs, space.boundary(iside).dofs); %! end %! int_dofs = setdiff (1:space.ndof, drchlt_dofs); %! u = zeros (space.ndof, 1); %! u(int_dofs) = mat(int_dofs, int_dofs) \ rhs(int_dofs); %! err = sp_l2_error (space, msh, u, @(x,y)(x.^2+y.^2-3*sqrt(x.^2+y.^2)+2).*sin(2.*atan(y./x))); %! assert (msh.nel, 9) %! assert (space.ndof, 121) %! assert (err, 4.71881595641687e-05, 1e-16)
section \<open>Environments and Substitution for Quasi-Terms\<close> theory QuasiTerms_Environments_Substitution imports QuasiTerms_PickFresh_Alpha begin text\<open>Inside this theory, since anyway all the interesting properties hold only modulo alpha, we forget completely about qAFresh and use only qFresh.\<close> text\<open>In this section we define, for quasi-terms, parallel substitution according to {\em environments}. This is the most general kind of substitution -- an environment, i.e., a partial map from variables to quasi-terms, indicates which quasi-term (if any) to be substituted for each variable; substitution is then applied to a subject quasi-term and an environment. In order to ``keep up" with the notion of good quasi-term, we define good environments and show that substitution preserves goodness. Since, unlike swapping, substitution does not behave well w.r.t. quasi-terms (but only w.r.t. terms, i.e., to alpha-equivalence classes), here we prove the minimum amount of properties required for properly lifting parallel substitution to terms. Then compositionality properties of parallel substitution will be proved directly for terms. \<close> subsection \<open>Environments\<close> type_synonym ('index,'bindex,'varSort,'var,'opSym)qEnv = "'varSort \<Rightarrow> 'var \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qTerm option" (*********************************************) context FixVars (* scope all throughout the file *) begin definition qGoodEnv :: "('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> bool" where "qGoodEnv rho == (\<forall> xs. liftAll qGood (rho xs)) \<and> (\<forall> ys. |{y. rho ys y \<noteq> None}| <o |UNIV :: 'var set| )" definition qFreshEnv where "qFreshEnv zs z rho == rho zs z = None \<and> (\<forall> xs. liftAll (qFresh zs z) (rho xs))" definition alphaEnv where "alphaEnv = {(rho,rho'). \<forall> xs. sameDom (rho xs) (rho' xs) \<and> liftAll2 (\<lambda>X X'. X #= X') (rho xs) (rho' xs)}" abbreviation alphaEnv_abbrev :: "('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> bool" (infix "&=" 50) where "rho &= rho' == (rho,rho') \<in> alphaEnv" definition pickQFreshEnv where "pickQFreshEnv xs V XS Rho == pickQFresh xs (V \<union> (\<Union> rho \<in> Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union> rho \<in> Rho. {X. \<exists> ys y. rho ys y = Some X}))" lemma qGoodEnv_imp_card_of_qTerm: assumes "qGoodEnv rho" shows "|{X. \<exists> y. rho ys y = Some X}| <o |UNIV :: 'var set|" proof- let ?rel = "{(y,X). rho ys y = Some X}" let ?Left = "{X. \<exists> y. rho ys y = Some X}" let ?Left' = "{y. \<exists> X. rho ys y = Some X}" have "\<And> y X X'. (y,X) \<in> ?rel \<and> (y,X') \<in> ?rel \<longrightarrow> X = X'" by force hence "|?Left| \<le>o |?Left'|" using card_of_inj_rel[of ?rel] by auto moreover have "|?Left'| <o |UNIV :: 'var set|" using assms unfolding qGoodEnv_def by auto ultimately show ?thesis using ordLeq_ordLess_trans by blast qed lemma qGoodEnv_imp_card_of_qTerm2: assumes "qGoodEnv rho" shows "|{X. \<exists> ys y. rho ys y = Some X}| <o |UNIV :: 'var set|" proof- let ?Left = "{X. \<exists> ys y. rho ys y = Some X}" let ?F = "\<lambda> ys. {X. \<exists> y. rho ys y = Some X}" have "?Left = (\<Union> ys. ?F ys)" by auto moreover have "\<forall> ys. |?F ys| <o |UNIV :: 'var set|" using assms qGoodEnv_imp_card_of_qTerm by auto ultimately show ?thesis using var_regular_INNER varSort_lt_var_INNER by(force simp add: regular_UNION) qed lemma qGoodEnv_iff: "qGoodEnv rho = ((\<forall> xs. liftAll qGood (rho xs)) \<and> (\<forall> ys. |{y. rho ys y \<noteq> None}| <o |UNIV :: 'var set| ) \<and> |{X. \<exists> ys y. rho ys y = Some X}| <o |UNIV :: 'var set| )" unfolding qGoodEnv_def apply auto apply(rule qGoodEnv_imp_card_of_qTerm2) unfolding qGoodEnv_def by simp lemma alphaEnv_refl: "qGoodEnv rho \<Longrightarrow> rho &= rho" using alpha_refl unfolding alphaEnv_def qGoodEnv_def liftAll_def liftAll2_def sameDom_def by fastforce lemma alphaEnv_sym: "rho &= rho' \<Longrightarrow> rho' &= rho" using alpha_sym unfolding alphaEnv_def liftAll2_def sameDom_def by fastforce lemma alphaEnv_trans: assumes good: "qGoodEnv rho" and alpha1: "rho &= rho'" and alpha2: "rho' &= rho''" shows "rho &= rho''" using assms unfolding alphaEnv_def apply(auto) using sameDom_trans apply blast unfolding liftAll2_def proof(auto) fix xs x X X'' assume rho: "rho xs x = Some X" and rho'': "rho'' xs x = Some X''" moreover have "(rho xs x = None) = (rho' xs x = None)" using alpha1 unfolding alphaEnv_def sameDom_def by auto ultimately obtain X' where rho': "rho' xs x = Some X'" by auto hence "X #= X'" using alpha1 rho unfolding alphaEnv_def liftAll2_def by auto moreover have "X' #= X''" using alpha2 rho' rho'' unfolding alphaEnv_def liftAll2_def by auto moreover have "qGood X" using good rho unfolding qGoodEnv_def liftAll_def by auto ultimately show "X #= X''" using alpha_trans by blast qed lemma pickQFreshEnv_card_of: assumes Vvar: "|V| <o |UNIV :: 'var set|" and XSvar: "|XS| <o |UNIV :: 'var set|" and good: "\<forall> X \<in> XS. qGood X" and Rhovar: "|Rho| <o |UNIV :: 'var set|" and RhoGood: "\<forall> rho \<in> Rho. qGoodEnv rho" shows "pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall> X \<in> XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall> rho \<in> Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)" proof- let ?z =" pickQFreshEnv xs V XS Rho" let ?V2 = "\<Union> rho \<in> Rho. {x. rho xs x \<noteq> None}" let ?W = "V \<union> ?V2" let ?XS2 = "\<Union> rho \<in> Rho. {X. \<exists> ys y. rho ys y = Some X}" let ?YS = "XS \<union> ?XS2" have "|?W| <o |UNIV :: 'var set|" proof- have "\<forall> rho \<in> Rho. |{x. rho xs x \<noteq> None}| <o |UNIV :: 'var set|" using RhoGood unfolding qGoodEnv_iff using qGoodEnv_iff by auto hence "|?V2| <o |UNIV :: 'var set|" using var_regular_INNER Rhovar by (auto simp add: regular_UNION) thus ?thesis using var_infinite_INNER Vvar card_of_Un_ordLess_infinite by auto qed moreover have "|?YS| <o |UNIV :: 'var set|" proof- have "\<forall> rho \<in> Rho. |{X. \<exists> ys y. rho ys y = Some X}| <o |UNIV :: 'var set|" using RhoGood unfolding qGoodEnv_iff by auto hence "|?XS2| <o |UNIV :: 'var set|" using var_regular_INNER Rhovar by (auto simp add: regular_UNION) thus ?thesis using var_infinite_INNER XSvar card_of_Un_ordLess_infinite by auto qed moreover have "\<forall> Y \<in> ?YS. qGood Y" using good RhoGood unfolding qGoodEnv_iff liftAll_def by blast ultimately have "?z \<notin> ?W \<and> (\<forall> Y \<in> ?YS. qFresh xs ?z Y)" unfolding pickQFreshEnv_def using pickQFresh_card_of[of ?W ?YS] by auto thus ?thesis unfolding qFreshEnv_def liftAll_def by(auto) qed lemma pickQFreshEnv: assumes Vvar: "|V| <o |UNIV :: 'var set| \<or> finite V" and XSvar: "|XS| <o |UNIV :: 'var set| \<or> finite XS" and good: "\<forall> X \<in> XS. qGood X" and Rhovar: "|Rho| <o |UNIV :: 'var set| \<or> finite Rho" and RhoGood: "\<forall> rho \<in> Rho. qGoodEnv rho" shows "pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall> X \<in> XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall> rho \<in> Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)" proof- have 1: "|V| <o |UNIV :: 'var set| \<and> |XS| <o |UNIV :: 'var set| \<and> |Rho| <o |UNIV :: 'var set|" using assms var_infinite_INNER by(auto simp add: finite_ordLess_infinite2) show ?thesis apply(rule pickQFreshEnv_card_of) using assms 1 by auto qed corollary obtain_qFreshEnv: fixes XS::"('index,'bindex,'varSort,'var,'opSym)qTerm set" and Rho::"('index,'bindex,'varSort,'var,'opSym)qEnv set" and rho assumes Vvar: "|V| <o |UNIV :: 'var set| \<or> finite V" and XSvar: "|XS| <o |UNIV :: 'var set| \<or> finite XS" and good: "\<forall> X \<in> XS. qGood X" and Rhovar: "|Rho| <o |UNIV :: 'var set| \<or> finite Rho" and RhoGood: "\<forall> rho \<in> Rho. qGoodEnv rho" shows "\<exists> z. z \<notin> V \<and> (\<forall> X \<in> XS. qFresh xs z X) \<and> (\<forall> rho \<in> Rho. qFreshEnv xs z rho)" apply(rule exI[of _ "pickQFreshEnv xs V XS Rho"]) using assms by(rule pickQFreshEnv) subsection \<open>Parallel substitution\<close> (* I shall prove only a *minimal* collection of facts for quasi- [parallel substitution], just enough to show that substitution preserves alpha. The other properties shall be proved for alpha-equivalence directly. *) definition aux_qPsubst_ignoreFirst :: "('index,'bindex,'varSort,'var,'opSym)qEnv * ('index,'bindex,'varSort,'var,'opSym)qTerm + ('index,'bindex,'varSort,'var,'opSym)qEnv * ('index,'bindex,'varSort,'var,'opSym)qAbs \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qTermItem" where "aux_qPsubst_ignoreFirst K == case K of Inl (rho,X) \<Rightarrow> termIn X |Inr (rho,A) \<Rightarrow> absIn A" lemma aux_qPsubst_ignoreFirst_qTermLessQSwapped_wf: "wf(inv_image qTermQSwappedLess aux_qPsubst_ignoreFirst)" using qTermQSwappedLess_wf wf_inv_image by auto function qPsubst :: "('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qTerm \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qTerm" and qPsubstAbs :: "('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qAbs \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qAbs" where "qPsubst rho (qVar xs x) = (case rho xs x of None \<Rightarrow> qVar xs x| Some X \<Rightarrow> X)" | "qPsubst rho (qOp delta inp binp) = qOp delta (lift (qPsubst rho) inp) (lift (qPsubstAbs rho) binp)" | "qPsubstAbs rho (qAbs xs x X) = (let x' = pickQFreshEnv xs {x} {X} {rho} in qAbs xs x' (qPsubst rho (X #[[x' \<and> x]]_xs)))" by(pat_completeness, auto) termination apply(relation "inv_image qTermQSwappedLess aux_qPsubst_ignoreFirst") apply(simp add: aux_qPsubst_ignoreFirst_qTermLessQSwapped_wf) by(auto simp add: qTermQSwappedLess_def qTermLess_modulo_def aux_qPsubst_ignoreFirst_def qSwap_qSwapped) abbreviation qPsubst_abbrev :: "('index,'bindex,'varSort,'var,'opSym)qTerm \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qTerm" ("_ #[[_]]") where "X #[[rho]] == qPsubst rho X" abbreviation qPsubstAbs_abbrev :: "('index,'bindex,'varSort,'var,'opSym)qAbs \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qEnv \<Rightarrow> ('index,'bindex,'varSort,'var,'opSym)qAbs" ("_ $[[_]]") where "A $[[rho]] == qPsubstAbs rho A" lemma qPsubstAll_preserves_qGoodAll: fixes X::"('index,'bindex,'varSort,'var,'opSym)qTerm" and A::"('index,'bindex,'varSort,'var,'opSym)qAbs" and rho assumes GOOD_ENV: "qGoodEnv rho" shows "(qGood X \<longrightarrow> qGood (X #[[rho]])) \<and> (qGoodAbs A \<longrightarrow> qGoodAbs (A $[[rho]]))" proof(induction rule: qTerm_induct[of _ _ X A]) case (Var xs x) show ?case using GOOD_ENV unfolding qGoodEnv_iff liftAll_def by(cases "rho xs x", auto) next case (Op delta inp binp) show ?case proof safe assume g: "qGood (qOp delta inp binp)" hence 0: "liftAll qGood (lift (qPsubst rho) inp) \<and> liftAll qGoodAbs (lift (qPsubstAbs rho) binp)" using Op unfolding liftAll_lift_comp comp_def by (simp_all add: Let_def liftAll_mp) have "{i. lift (qPsubst rho) inp i \<noteq> None} = {i. inp i \<noteq> None} \<and> {i. lift (qPsubstAbs rho) binp i \<noteq> None} = {i. binp i \<noteq> None}" by simp (meson lift_Some) hence "|{i. \<exists>y. lift (qPsubst rho) inp i = Some y}| <o |UNIV:: 'var set|" and "|{i. \<exists>y. lift (qPsubstAbs rho) binp i = Some y}| <o |UNIV:: 'var set|" using g by (auto simp: liftAll_def) thus "qGood qOp delta inp binp #[[rho]]" using 0 by simp qed next case (Abs xs x X) show ?case proof safe assume g: "qGoodAbs (qAbs xs x X)" let ?x' = "pickQFreshEnv xs {x} {X} {rho}" let ?X' = "X #[[?x' \<and> x]]_xs" have "qGood ?X'" using g qSwap_preserves_qGood by auto moreover have "(X,?X') \<in> qSwapped" using qSwap_qSwapped by fastforce ultimately have "qGood (qPsubst rho ?X')" using Abs.IH by simp thus "qGoodAbs ((qAbs xs x X) $[[rho]])" by (simp add: Let_def) qed qed corollary qPsubst_preserves_qGood: "\<lbrakk>qGoodEnv rho; qGood X\<rbrakk> \<Longrightarrow> qGood (X #[[rho]])" using qPsubstAll_preserves_qGoodAll by auto corollary qPsubstAbs_preserves_qGoodAbs: "\<lbrakk>qGoodEnv rho; qGoodAbs A\<rbrakk> \<Longrightarrow> qGoodAbs (A $[[rho]])" using qPsubstAll_preserves_qGoodAll by auto lemma qPsubstAll_preserves_qFreshAll: fixes X::"('index,'bindex,'varSort,'var,'opSym)qTerm" and A::"('index,'bindex,'varSort,'var,'opSym)qAbs" and rho assumes GOOD_ENV: "qGoodEnv rho" shows "(qFresh zs z X \<longrightarrow> (qGood X \<and> qFreshEnv zs z rho \<longrightarrow> qFresh zs z (X #[[rho]]))) \<and> (qFreshAbs zs z A \<longrightarrow> (qGoodAbs A \<and> qFreshEnv zs z rho \<longrightarrow> qFreshAbs zs z (A $[[rho]])))" proof(induction rule: qTerm_induct[of _ _ X A]) case (Var xs x) then show ?case unfolding qFreshEnv_def liftAll_def by (cases "rho xs x") auto next case (Op delta inp binp) thus ?case by (auto simp add: lift_def liftAll_def qFreshEnv_def split: option.splits) next case (Abs xs x X) show ?case proof safe assume q: "qFreshAbs zs z (qAbs xs x X)" "qGoodAbs (qAbs xs x X)" "qFreshEnv zs z rho" let ?x' = "pickQFreshEnv xs {x} {X} {rho}" let ?X' = "X #[[?x' \<and> x]]_xs" have x': "qFresh xs ?x' X \<and> qFreshEnv xs ?x' rho" using q GOOD_ENV by(auto simp add: pickQFreshEnv) hence goodX': "qGood ?X'" using q qSwap_preserves_qGood by auto have XX': "(X,?X') \<in> qSwapped" using qSwap_qSwapped by fastforce have "(zs = xs \<and> z = ?x') \<or> qFresh zs z (qPsubst rho ?X')" by (meson qSwap_preserves_qFresh_distinct Abs.IH(1) XX' goodX' q qAbs_alphaAbs_qSwap_qFresh qFreshAbs.simps qFreshAbs_preserves_alphaAbs1 qSwap_preserves_qGood2 x') thus "qFreshAbs zs z ((qAbs xs x X) $[[rho]])" by simp (meson qFreshAbs.simps)+ qed qed lemma qPsubst_preserves_qFresh: "\<lbrakk>qGood X; qGoodEnv rho; qFresh zs z X; qFreshEnv zs z rho\<rbrakk> \<Longrightarrow> qFresh zs z (X #[[rho]])" by(simp add: qPsubstAll_preserves_qFreshAll) lemma qPsubstAbs_preserves_qFreshAbs: "\<lbrakk>qGoodAbs A; qGoodEnv rho; qFreshAbs zs z A; qFreshEnv zs z rho\<rbrakk> \<Longrightarrow> qFreshAbs zs z (A $[[rho]])" by(simp add: qPsubstAll_preserves_qFreshAll) text\<open>While in general we try to avoid proving facts in parallel, here we seem to have no choice -- it is the first time we must use mutual induction:\<close> lemma qPsubstAll_preserves_alphaAll_qSwapAll: fixes X::"('index,'bindex,'varSort,'var,'opSym)qTerm" and A::"('index,'bindex,'varSort,'var,'opSym)qAbs" and rho::"('index,'bindex,'varSort,'var,'opSym)qEnv" assumes goodRho: "qGoodEnv rho" shows "(qGood X \<longrightarrow> (\<forall> Y. X #= Y \<longrightarrow> (X #[[rho]]) #= (Y #[[rho]])) \<and> (\<forall> xs z1 z2. qFreshEnv xs z1 rho \<and> qFreshEnv xs z2 rho \<longrightarrow> ((X #[[z1 \<and> z2]]_xs) #[[rho]]) #= ((X #[[rho]]) #[[z1 \<and> z2]]_xs))) \<and> (qGoodAbs A \<longrightarrow> (\<forall> B. A $= B \<longrightarrow> (A $[[rho]]) $= (B $[[rho]])) \<and> (\<forall> xs z1 z2. qFreshEnv xs z1 rho \<and> qFreshEnv xs z2 rho \<longrightarrow> ((A $[[z1 \<and> z2]]_xs) $[[rho]]) $= ((A $[[rho]]) $[[z1 \<and> z2]]_xs)))" proof(induction rule: qGood_qTerm_induct_mutual) case (Var1 xs x) then show ?case by (metis alpha_refl goodRho qGood.simps(1) qPsubst_preserves_qGood qVar_alpha_iff) next case (Var2 xs x) show ?case proof safe fix s::'sort and zs z1 z2 assume FreshEnv: "qFreshEnv zs z1 rho" "qFreshEnv zs z2 rho" hence n: "rho zs z1 = None \<and> rho zs z2 = None" unfolding qFreshEnv_def by simp let ?Left = "qPsubst rho ((qVar xs x) #[[z1 \<and> z2]]_zs)" let ?Right = "(qPsubst rho (qVar xs x)) #[[z1 \<and> z2]]_zs" have "qGood (qVar xs x)" by simp hence "qGood ((qVar xs x) #[[z1 \<and> z2]]_zs)" using qSwap_preserves_qGood by blast hence goodLeft: "qGood ?Left" using goodRho qPsubst_preserves_qGood by blast show "?Left #= ?Right" proof(cases "rho xs x") case None hence "rho xs (x @xs[z1 \<and> z2]_zs) = None" using n unfolding sw_def by auto thus ?thesis using None by simp next case (Some X) hence "xs \<noteq> zs \<or> x \<notin> {z1,z2}" using n by auto hence "(x @xs[z1 \<and> z2]_zs) = x" unfolding sw_def by auto moreover {have "qFresh zs z1 X \<and> qFresh zs z2 X" using Some FreshEnv unfolding qFreshEnv_def liftAll_def by auto moreover have "qGood X" using Some goodRho unfolding qGoodEnv_def liftAll_def by auto ultimately have "X #= (X #[[z1 \<and> z2]]_zs)" by(auto simp: alpha_qFresh_qSwap_id alpha_sym) } ultimately show ?thesis using Some by simp qed qed next case (Op1 delta inp binp) show ?case proof safe fix Y assume q: "qOp delta inp binp #= Y" then obtain inp' binp' where Y: "Y = qOp delta inp' binp'" and *: "(\<forall>i. (inp i = None) = (inp' i = None)) \<and> (\<forall>i. (binp i = None) = (binp' i = None))" and **: "(\<forall>i X X'. inp i = Some X \<and> inp' i = Some X' \<longrightarrow> X #= X') \<and> (\<forall>i A A'. binp i = Some A \<and> binp' i = Some A' \<longrightarrow> A $= A')" unfolding qOp_alpha_iff sameDom_def liftAll2_def by auto show "(qOp delta inp binp) #[[rho]] #= (Y #[[rho]])" using Op1 ** by (simp add: Y sameDom_def liftAll2_def) (fastforce simp add: * lift_None lift_Some liftAll_def lift_def split: option.splits) qed next case (Op2 delta inp binp) thus ?case by (auto simp: sameDom_def liftAll2_def lift_None lift_def liftAll_def split: option.splits) next case (Abs1 xs x X) show ?case proof safe fix B assume alpha_xXB: "qAbs xs x X $= B" then obtain y Y where B: "B = qAbs xs y Y" unfolding qAbs_alphaAbs_iff by auto have "qGoodAbs B" using \<open>qGood X\<close> alpha_xXB alphaAbs_preserves_qGoodAbs by force hence goodY: "qGood Y" unfolding B by simp let ?x' = "pickQFreshEnv xs {x} {X} {rho}" let ?y' = "pickQFreshEnv xs {y} {Y} {rho}" obtain x' and y' where x'y'_def: "x' = ?x'" "y' = ?y'" and x'y'_rev: "?x' = x'" "?y' = y'" by blast have x'y'_freshXY: "qFresh xs x' X \<and> qFresh xs y' Y" unfolding x'y'_def using \<open>qGood X\<close> goodY goodRho by (auto simp add: pickQFreshEnv) have x'y'_fresh_rho: "qFreshEnv xs x' rho \<and> qFreshEnv xs y' rho" unfolding x'y'_def using \<open>qGood X\<close> goodY goodRho by (auto simp add: pickQFreshEnv) have x'y'_not_xy: "x' \<noteq> x \<and> y' \<noteq> y" unfolding x'y'_def using \<open>qGood X\<close> goodY goodRho using pickQFreshEnv[of "{x}" "{X}"] pickQFreshEnv[of "{y}" "{Y}"] by force have goodXx'x: "qGood (X #[[x' \<and> x]]_xs)" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence good: "qGood(qPsubst rho (X #[[x' \<and> x]]_xs))" using goodRho qPsubst_preserves_qGood by auto have goodYy'y: "qGood (Y #[[y' \<and> y]]_xs)" using goodY qSwap_preserves_qGood by auto obtain z where z_not: "z \<notin> {x,y,x',y'}" and z_fresh_XY: "qFresh xs z X \<and> qFresh xs z Y" and z_fresh_rho: "qFreshEnv xs z rho" using \<open>qGood X\<close> goodY goodRho using obtain_qFreshEnv[of "{x,y,x',y'}" "{X,Y}" "{rho}"] by auto (* Notations: *) let ?Xx'x = "X #[[x' \<and> x]]_xs" let ?Yy'y = "Y #[[y' \<and> y]]_xs" let ?Xx'xzx' = "?Xx'x #[[z \<and> x']]_xs" let ?Yy'yzy' = "?Yy'y #[[z \<and> y']]_xs" let ?Xzx = "X #[[z \<and> x]]_xs" let ?Yzy = "Y #[[z \<and> y]]_xs" (* Preliminary facts: *) have goodXx'x: "qGood ?Xx'x" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence goodXx'xzx': "qGood ?Xx'xzx'" using qSwap_preserves_qGood by auto have "qGood (?Xx'x #[[rho]])" using goodXx'x goodRho qPsubst_preserves_qGood by auto hence goodXx'x_rho_zx': "qGood ((?Xx'x #[[rho]]) #[[z \<and> x']]_xs)" using qSwap_preserves_qGood by auto have goodYy'y: "qGood ?Yy'y" using goodY qSwap_preserves_qGood by auto (* *) have skelXx'x: "qSkel ?Xx'x = qSkel X" using qSkel_qSwap by fastforce hence skelXx'xzx': "qSkel ?Xx'xzx' = qSkel X" by (auto simp add: qSkel_qSwap) have "qSkelAbs B = qSkelAbs (qAbs xs x X)" using alpha_xXB alphaAll_qSkelAll by fastforce hence "qSkel Y = qSkel X" unfolding B by(auto simp add: fun_eq_iff) hence skelYy'y: "qSkel ?Yy'y = qSkel X" by(auto simp add: qSkel_qSwap) (* Main proof: *) have "((?Xx'x #[[rho]]) #[[z \<and> x']]_xs) #= (?Xx'xzx' #[[rho]])" using skelXx'x goodXx'x z_fresh_rho x'y'_fresh_rho Abs1.IH(2)[of "?Xx'x"] by (auto simp add: alpha_sym) moreover {have "?Xx'xzx' #= ?Xzx" using \<open>qGood X\<close> x'y'_freshXY z_fresh_XY alpha_qFresh_qSwap_compose by fastforce moreover have "?Xzx #= ?Yzy" using alpha_xXB unfolding B using z_fresh_XY \<open>qGood X\<close> goodY by (simp only: alphaAbs_qAbs_iff_all_qFresh) moreover have "?Yzy #= ?Yy'yzy'" using goodY x'y'_freshXY z_fresh_XY by(auto simp add: alpha_qFresh_qSwap_compose alpha_sym) ultimately have "?Xx'xzx' #= ?Yy'yzy'" using goodXx'xzx' alpha_trans by blast hence "(?Xx'xzx' #[[rho]]) #= (?Yy'yzy' #[[rho]])" using goodXx'xzx' skelXx'xzx' Abs1.IH(1) by auto } moreover have "(?Yy'yzy' #[[rho]]) #= ((?Yy'y #[[rho]]) #[[z \<and> y']]_xs)" using skelYy'y goodYy'y z_fresh_rho x'y'_fresh_rho Abs1.IH(2)[of "?Yy'y"] alpha_sym by fastforce ultimately have "((?Xx'x #[[rho]]) #[[z \<and> x']]_xs) #= ((?Yy'y #[[rho]]) #[[z \<and> y']]_xs)" using goodXx'x_rho_zx' alpha_trans by blast thus "(qAbs xs x X) $[[rho]] $= (B $[[rho]])" unfolding B apply simp unfolding Let_def unfolding x'y'_rev using good z_not apply(simp only: alphaAbs_qAbs_iff_ex_qFresh) by (auto intro!: exI[of _ z] simp: alphaAbs_qAbs_iff_ex_qFresh goodRho goodXx'x qPsubstAll_preserves_qFreshAll qSwap_preserves_qFresh_distinct z_fresh_XY goodYy'y qPsubst_preserves_qFresh z_fresh_rho) qed next case (Abs2 xs x X) show ?case proof safe fix zs z1 z2 assume z1z2_fresh_rho: "qFreshEnv zs z1 rho" "qFreshEnv zs z2 rho" let ?x' = "pickQFreshEnv xs {x @xs[z1 \<and> z2]_zs} {X #[[z1 \<and> z2]]_zs} {rho}" let ?x'' = "pickQFreshEnv xs {x} {X} {rho}" obtain x' x'' where x'x''_def: "x' = ?x'" "x'' = ?x''" and x'x''_rev: "?x' = x'" "?x'' = x''" by blast let ?xa = "x @xs[z1 \<and> z2]_zs" let ?xa'' = "x'' @xs[z1 \<and> z2]_zs" obtain u where "u \<notin> {x,x',x'',z1,z2}" and u_fresh_X: "qFresh xs u X" and u_fresh_rho: "qFreshEnv xs u rho" using \<open>qGood X\<close> goodRho using obtain_qFreshEnv[of "{x,x',x'',z1,z2}" "{X}" "{rho}"] by auto hence u_not: "u \<notin> {x,x',x'',z1,z2,?xa,?xa''}" unfolding sw_def by auto let ?ua = "u @xs [z1 \<and> z2]_zs" let ?Xz1z2 = "X #[[z1 \<and> z2]]_zs" let ?Xz1z2x'xa = "?Xz1z2 #[[x' \<and> ?xa]]_xs" let ?Xz1z2x'xa_rho = "?Xz1z2x'xa #[[rho]]" let ?Xz1z2x'xa_rho_ux' = "?Xz1z2x'xa_rho #[[u \<and> x']]_xs" let ?Xz1z2x'xaux' = "?Xz1z2x'xa #[[u \<and> x']]_xs" let ?Xz1z2x'xaux'_rho = "?Xz1z2x'xaux' #[[rho]]" let ?Xz1z2uxa = "?Xz1z2 #[[u \<and> ?xa]]_xs" let ?Xz1z2uaxa = "?Xz1z2 #[[?ua \<and> ?xa]]_xs" let ?Xux = "X #[[u \<and> x]]_xs" let ?Xuxz1z2 = "?Xux #[[z1 \<and> z2]]_zs" let ?Xx''x = "X #[[x'' \<and> x]]_xs" let ?Xx''xux'' = "?Xx''x #[[u \<and> x'']]_xs" let ?Xx''xux''z1z2 = "?Xx''xux'' #[[z1 \<and> z2]]_zs" let ?Xx''xz1z2 = "?Xx''x #[[z1 \<and> z2]]_zs" let ?Xx''xz1z2uaxa'' = "?Xx''xz1z2 #[[?ua \<and> ?xa'']]_xs" let ?Xx''xz1z2uaxa''_rho = "?Xx''xz1z2uaxa'' #[[rho]]" let ?Xx''xz1z2uxa'' = "?Xx''xz1z2 #[[u \<and> ?xa'']]_xs" let ?Xx''xz1z2uxa''_rho = "?Xx''xz1z2uxa'' #[[rho]]" let ?Xx''xz1z2_rho = "?Xx''xz1z2 #[[rho]]" let ?Xx''xz1z2_rho_uxa'' = "?Xx''xz1z2_rho #[[u \<and> ?xa'']]_xs" let ?Xx''x_rho = "?Xx''x #[[rho]]" let ?Xx''x_rho_z1z2 = "?Xx''x_rho #[[z1 \<and> z2]]_zs" let ?Xx''x_rho_z1z2uxa'' = "?Xx''x_rho_z1z2 #[[u \<and> ?xa'']]_xs" (* Facts about x', x'', ?xa, ?ua, ?xa'': *) have goodXz1z2: "qGood ?Xz1z2" using \<open>qGood X\<close> qSwap_preserves_qGood by auto have x'x''_fresh_Xz1z2: "qFresh xs x' ?Xz1z2 \<and> qFresh xs x'' X" unfolding x'x''_def using \<open>qGood X\<close> goodXz1z2 goodRho by (auto simp add: pickQFreshEnv) have x'x''_fresh_rho: "qFreshEnv xs x' rho \<and> qFreshEnv xs x'' rho" unfolding x'x''_def using \<open>qGood X\<close> goodXz1z2 goodRho by (auto simp add: pickQFreshEnv) have ua_eq_u: "?ua = u" using u_not unfolding sw_def by auto (* Good: *) have goodXz1z2x'xa: "qGood ?Xz1z2x'xa" using goodXz1z2 qSwap_preserves_qGood by auto have goodXux: "qGood ?Xux" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence goodXuxz1z2: "qGood ?Xuxz1z2" using qSwap_preserves_qGood by auto have goodXx''x: "qGood ?Xx''x" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence goodXx''xz1z2: "qGood ?Xx''xz1z2" using qSwap_preserves_qGood by auto hence "qGood ?Xx''xz1z2_rho" using goodRho qPsubst_preserves_qGood by auto hence goodXx''xz1z2_rho: "qGood ?Xx''xz1z2_rho" using goodRho qPsubst_preserves_qGood by auto have goodXz1z2x'xaux': "qGood ?Xz1z2x'xaux'" using goodXz1z2x'xa qSwap_preserves_qGood by auto have goodXz1z2x'xa_rho: "qGood ?Xz1z2x'xa_rho" using goodXz1z2x'xa goodRho qPsubst_preserves_qGood by auto hence goodXz1z2x'xa_rho_ux': "qGood ?Xz1z2x'xa_rho_ux'" using qSwap_preserves_qGood by auto (* Fresh: *) have xa''_fresh_rho: "qFreshEnv xs ?xa'' rho" using x'x''_fresh_rho z1z2_fresh_rho unfolding sw_def by auto have u_fresh_Xz1z2: "qFresh xs u ?Xz1z2" using u_fresh_X u_not by(auto simp add: qSwap_preserves_qFresh_distinct) hence "qFresh xs u ?Xz1z2x'xa" using u_not by(auto simp add: qSwap_preserves_qFresh_distinct) hence u_fresh_Xz1z2x'xa_rho: "qFresh xs u ?Xz1z2x'xa_rho" using u_fresh_rho u_fresh_X goodRho goodXz1z2x'xa qPsubst_preserves_qFresh by auto have "qFresh xs u ?Xx''x" using u_fresh_X u_not by(auto simp add: qSwap_preserves_qFresh_distinct) hence "qFresh xs u ?Xx''x_rho" using goodRho goodXx''x u_fresh_rho by(auto simp add: qPsubst_preserves_qFresh) hence u_fresh_Xx''x_rho_z1z2: "qFresh xs u ?Xx''x_rho_z1z2" using u_not by(auto simp add: qSwap_preserves_qFresh_distinct) (* Skeleton: *) have skel_Xz1z2x'xa: "qSkel ?Xz1z2x'xa = qSkel X" by(auto simp add: qSkel_qSwap) hence skel_Xz1z2x'xaux': "qSkel ?Xz1z2x'xaux' = qSkel X" by(auto simp add: qSkel_qSwap) have skel_Xx''x: "qSkel ?Xx''x = qSkel X" by(auto simp add: qSkel_qSwap) hence skel_Xx''xz1z2: "qSkel ?Xx''xz1z2 = qSkel X" by(auto simp add: qSkel_qSwap) (* Main proof: *) have "?Xz1z2x'xaux'_rho #= ?Xz1z2x'xa_rho_ux'" using x'x''_fresh_rho u_fresh_rho skel_Xz1z2x'xa goodXz1z2x'xa using Abs2.IH(2)[of ?Xz1z2x'xa] by auto hence "?Xz1z2x'xa_rho_ux' #= ?Xz1z2x'xaux'_rho" using alpha_sym by auto moreover {have "?Xz1z2x'xaux' #= ?Xz1z2uxa" using goodXz1z2 u_fresh_Xz1z2 x'x''_fresh_Xz1z2 using alpha_qFresh_qSwap_compose by fastforce moreover have "?Xz1z2uxa = ?Xuxz1z2" using ua_eq_u qSwap_compose[of zs z1 z2 xs x u X] by(auto simp: qSwap_sym) moreover {have "?Xux #= ?Xx''xux''" using \<open>qGood X\<close> u_fresh_X x'x''_fresh_Xz1z2 by(auto simp: alpha_qFresh_qSwap_compose alpha_sym) hence "?Xuxz1z2 #= ?Xx''xux''z1z2" using goodXux by (auto simp add: qSwap_preserves_alpha) } moreover have "?Xx''xux''z1z2 = ?Xx''xz1z2uxa''" using ua_eq_u qSwap_compose[of zs z1 z2 _ _ _ ?Xx''x] by auto ultimately have "?Xz1z2x'xaux' #= ?Xx''xz1z2uxa''" using goodXz1z2x'xaux' alpha_trans by auto hence "?Xz1z2x'xaux'_rho #= ?Xx''xz1z2uxa''_rho" using goodXz1z2x'xaux' skel_Xz1z2x'xaux' Abs2.IH(1) by auto } moreover have "?Xx''xz1z2uxa''_rho #= ?Xx''xz1z2_rho_uxa''" using xa''_fresh_rho u_fresh_rho skel_Xx''xz1z2 goodXx''xz1z2 using Abs2.IH(2)[of ?Xx''xz1z2] by auto moreover {have "?Xx''xz1z2_rho #= ?Xx''x_rho_z1z2" using z1z2_fresh_rho skel_Xx''x goodXx''x using Abs2.IH(2)[of ?Xx''x] by auto hence "?Xx''xz1z2_rho_uxa'' #= ?Xx''x_rho_z1z2uxa''" using goodXx''xz1z2_rho by(auto simp add: qSwap_preserves_alpha) } ultimately have "?Xz1z2x'xa_rho_ux' #= ?Xx''x_rho_z1z2uxa''" using goodXz1z2x'xa_rho_ux' alpha_trans by blast thus "((qAbs xs x X) $[[z1 \<and> z2]]_zs) $[[rho]] $= (((qAbs xs x X) $[[rho]]) $[[z1 \<and> z2]]_zs)" using goodXz1z2x'xa_rho goodXz1z2x'xa u_not u_fresh_Xz1z2x'xa_rho u_fresh_Xx''x_rho_z1z2 apply(simp add: Let_def x'x''_rev del: alpha.simps alphaAbs.simps ) by (auto simp only: Let_def alphaAbs_qAbs_iff_ex_qFresh) qed qed corollary qPsubst_preserves_alpha1: assumes "qGoodEnv rho" and "qGood X \<or> qGood Y" and "X #= Y" shows "(X #[[rho]]) #= (Y #[[rho]])" using alpha_preserves_qGood assms qPsubstAll_preserves_alphaAll_qSwapAll by blast corollary qPsubstAbs_preserves_alphaAbs1: assumes "qGoodEnv rho" and "qGoodAbs A \<or> qGoodAbs B" and "A $= B" shows "(A $[[rho]]) $= (B $[[rho]])" using alphaAbs_preserves_qGoodAbs assms qPsubstAll_preserves_alphaAll_qSwapAll by blast corollary alpha_qFreshEnv_qSwap_qPsubst_commute: "\<lbrakk>qGoodEnv rho; qGood X; qFreshEnv zs z1 rho; qFreshEnv zs z2 rho\<rbrakk> \<Longrightarrow> ((X #[[z1 \<and> z2]]_zs) #[[rho]]) #= ((X #[[rho]]) #[[z1 \<and> z2]]_zs)" by(simp add: qPsubstAll_preserves_alphaAll_qSwapAll) corollary alphaAbs_qFreshEnv_qSwapAbs_qPsubstAbs_commute: "\<lbrakk>qGoodEnv rho; qGoodAbs A; qFreshEnv zs z1 rho; qFreshEnv zs z2 rho\<rbrakk> \<Longrightarrow> ((A $[[z1 \<and> z2]]_zs) $[[rho]]) $= ((A $[[rho]]) $[[z1 \<and> z2]]_zs)" by(simp add: qPsubstAll_preserves_alphaAll_qSwapAll) lemma qPsubstAll_preserves_alphaAll2: fixes X::"('index,'bindex,'varSort,'var,'opSym)qTerm" and A::"('index,'bindex,'varSort,'var,'opSym)qAbs" and rho'::"('index,'bindex,'varSort,'var,'opSym)qEnv" and rho'' assumes rho'_alpha_rho'': "rho' &= rho''" and goodRho': "qGoodEnv rho'" and goodRho'': "qGoodEnv rho''" shows "(qGood X \<longrightarrow> (X #[[rho']]) #= (X #[[rho'']])) \<and> (qGoodAbs A \<longrightarrow> (A $[[rho']]) $= (A $[[rho'']]))" proof(induction rule: qGood_qTerm_induct) case (Var xs x) then show ?case proof (cases "rho' xs x") case None hence "rho'' xs x = None" using rho'_alpha_rho'' unfolding alphaEnv_def sameDom_def by auto thus ?thesis using None by simp next case (Some X') then obtain X'' where rho'': "rho'' xs x = Some X''" using assms unfolding alphaEnv_def sameDom_def by force hence "X' #= X''" using Some rho'_alpha_rho'' unfolding alphaEnv_def liftAll2_def by auto thus ?thesis using Some rho'' by simp qed next case (Op delta inp binp) then show ?case by (auto simp: lift_def liftAll_def liftAll2_def sameDom_def Let_def split: option.splits) next case (Abs xs x X) let ?x' = "pickQFreshEnv xs {x} {X} {rho'}" let ?x'' = "pickQFreshEnv xs {x} {X} {rho''}" obtain x' x'' where x'x''_def: "x' = ?x'" "x'' = ?x''" and x'x''_rev: "?x' = x'" "?x'' = x''" by blast have x'x''_fresh_X: "qFresh xs x' X \<and> qFresh xs x'' X" unfolding x'x''_def using \<open>qGood X\<close> goodRho' goodRho'' by (auto simp add: pickQFreshEnv) have x'_fresh_rho': "qFreshEnv xs x' rho'" unfolding x'x''_def using \<open>qGood X\<close> goodRho' goodRho'' by (auto simp add: pickQFreshEnv) have x''_fresh_rho'': "qFreshEnv xs x'' rho''" unfolding x'x''_def using \<open>qGood X\<close> goodRho' goodRho'' by (auto simp add: pickQFreshEnv) obtain u where u_not: "u \<notin> {x,x',x''}" and u_fresh_X: "qFresh xs u X" and u_fresh_rho': "qFreshEnv xs u rho'" and u_fresh_rho'': "qFreshEnv xs u rho''" using \<open>qGood X\<close> goodRho' goodRho'' using obtain_qFreshEnv[of "{x,x',x''}" "{X}" "{rho',rho''}"] by auto (* Preliminary facts and notations: *) let ?Xx'x = "X #[[x' \<and> x]]_xs" let ?Xx'x_rho' = "?Xx'x #[[rho']]" let ?Xx'x_rho'_ux' = "?Xx'x_rho' #[[u \<and> x']]_xs" let ?Xx'xux' = "?Xx'x #[[u \<and> x']]_xs" let ?Xx'xux'_rho' = "?Xx'xux' #[[rho']]" let ?Xux = "X #[[u \<and> x]]_xs" let ?Xux_rho' = "?Xux #[[rho']]" let ?Xux_rho'' = "?Xux #[[rho'']]" let ?Xx''x = "X #[[x'' \<and> x]]_xs" let ?Xx''xux'' = "?Xx''x #[[u \<and> x'']]_xs" let ?Xx''xux''_rho'' = "?Xx''xux'' #[[rho'']]" let ?Xx''x_rho'' = "?Xx''x #[[rho'']]" let ?Xx''x_rho''_ux'' = "?Xx''x_rho'' #[[u \<and> x'']]_xs" (* Good: *) have goodXx'x: "qGood ?Xx'x" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence goodXx'x_rho': "qGood ?Xx'x_rho'" using \<open>qGood X\<close> goodRho' qPsubst_preserves_qGood by auto hence goodXx'x_rho'_ux': "qGood ?Xx'x_rho'_ux'" using \<open>qGood X\<close> qSwap_preserves_qGood by auto have goodXx'xux': "qGood ?Xx'xux'" using goodXx'x qSwap_preserves_qGood by auto have goodXux: "qGood ?Xux" using \<open>qGood X\<close> qSwap_preserves_qGood by auto have goodXx''x: "qGood ?Xx''x" using \<open>qGood X\<close> qSwap_preserves_qGood by auto hence goodXx''x_rho'': "qGood ?Xx''x_rho''" using \<open>qGood X\<close> goodRho'' qPsubst_preserves_qGood by auto (* Fresh: *) have "qFresh xs u ?Xx'x" using u_not u_fresh_X by(auto simp add: qSwap_preserves_qFresh_distinct) hence fresh_Xx'x_rho': "qFresh xs u ?Xx'x_rho'" using u_fresh_rho' goodXx'x goodRho' by(auto simp add: qPsubst_preserves_qFresh) have "qFresh xs u ?Xx''x" using u_not u_fresh_X by(auto simp add: qSwap_preserves_qFresh_distinct) hence fresh_Xx''x_rho'': "qFresh xs u ?Xx''x_rho''" using u_fresh_rho'' goodXx''x goodRho'' by(auto simp add: qPsubst_preserves_qFresh) (* qSwapped: *) have Xux: "(X,?Xux) :qSwapped" by(simp add: qSwap_qSwapped) (* Main proof: *) have "?Xx'x_rho'_ux' #= ?Xx'xux'_rho'" using goodRho' goodXx'x u_fresh_rho' x'_fresh_rho' by(auto simp: alpha_qFreshEnv_qSwap_qPsubst_commute alpha_sym) moreover {have "?Xx'xux' #= ?Xux" using \<open>qGood X\<close> u_fresh_X x'x''_fresh_X using alpha_qFresh_qSwap_compose by fastforce hence "?Xx'xux'_rho' #= ?Xux_rho'" using goodXx'xux' goodRho' using qPsubst_preserves_alpha1 by auto } moreover have "?Xux_rho' #= ?Xux_rho''" using Xux Abs.IH by auto moreover {have "?Xux #= ?Xx''xux''" using \<open>qGood X\<close> u_fresh_X x'x''_fresh_X by(auto simp add: alpha_qFresh_qSwap_compose alpha_sym) hence "?Xux_rho'' #= ?Xx''xux''_rho''" using goodXux goodRho'' using qPsubst_preserves_alpha1 by auto } moreover have "?Xx''xux''_rho'' #= ?Xx''x_rho''_ux''" using goodRho'' goodXx''x u_fresh_rho'' x''_fresh_rho'' by(auto simp: alpha_qFreshEnv_qSwap_qPsubst_commute) ultimately have "?Xx'x_rho'_ux' #= ?Xx''x_rho''_ux''" using goodXx'x_rho'_ux' alpha_trans by blast hence "qAbs xs ?x' (qPsubst rho' (X #[[?x' \<and> x]]_xs)) $= qAbs xs ?x''(qPsubst rho''(X #[[?x''\<and> x]]_xs))" unfolding x'x''_rev using goodXx'x_rho' fresh_Xx'x_rho' fresh_Xx''x_rho'' by (auto simp only: alphaAbs_qAbs_iff_ex_qFresh) thus ?case by (metis qPsubstAbs.simps) qed corollary qPsubst_preserves_alpha2: "\<lbrakk>qGood X; qGoodEnv rho'; qGoodEnv rho''; rho' &= rho''\<rbrakk> \<Longrightarrow> (X #[[rho']]) #= (X #[[rho'']])" by(simp add: qPsubstAll_preserves_alphaAll2) corollary qPsubstAbs_preserves_alphaAbs2: "\<lbrakk>qGoodAbs A; qGoodEnv rho'; qGoodEnv rho''; rho' &= rho''\<rbrakk> \<Longrightarrow> (A $[[rho']]) $= (A $[[rho'']])" by(simp add: qPsubstAll_preserves_alphaAll2) lemma qPsubst_preserves_alpha: assumes "qGood X \<or> qGood X'" and "qGoodEnv rho" and "qGoodEnv rho'" and "X #= X'" and "rho &= rho'" shows "(X #[[rho]]) #= (X' #[[rho']])" by (metis (no_types, lifting) assms alpha_trans qPsubst_preserves_alpha1 qPsubst_preserves_alpha2 qPsubst_preserves_qGood) end (* context FixVars *) end
{-# LANGUAGE GADTs, RankNTypes, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, KindSignatures, ScopedTypeVariables, ConstraintKinds, TemplateHaskell, GeneralizedNewtypeDeriving, TypeFamilies #-} module Numeric.Trainee.Types ( Gradee(..), Ow(..), params, forwardPass, Learnee(..), Loss, Regularization, HasNorm(..), Sample(..), (⇢), Samples, samples, module Numeric.Trainee.Params ) where import Prelude hiding (id, (.)) import Prelude.Unicode import Control.Category import Control.DeepSeq import Control.Lens import qualified Data.Vector as V import Numeric.LinearAlgebra (Normed(norm_1), R, Vector) import Numeric.Trainee.Params newtype Gradee a b = Gradee { runGradee ∷ Lens' a b } instance Category Gradee where id = Gradee id Gradee f . Gradee g = Gradee (g . f) class Category a ⇒ Ow a where first ∷ a b c → a (b, d) (c, d) first = flip stars id second ∷ a b c → a (d, b) (d, c) second = stars id stars ∷ a b c → a b' c' → a (b, b') (c, c') vstars ∷ a b c → a (V.Vector b) (V.Vector c) instance Ow Gradee where stars (Gradee f) (Gradee g) = Gradee $ lens g' s' where g' (x, y) = (view f x, view g y) s' (x, y) (x', y') = (set f x' x, set g y' y) vstars (Gradee f) = Gradee $ lens g' s' where g' = V.map (view f) s' = V.zipWith (flip (set f)) data Learnee a b = Learnee { _params ∷ Params, _forwardPass ∷ Params → a → (b, b → (Params, a)) } makeLenses ''Learnee instance NFData (Learnee a b) where rnf (Learnee ws _) = rnf ws instance Show (Learnee a b) where show (Learnee ws _) = show ws instance Category Learnee where id = Learnee (Params NoParams) fn where fn _ x = (x, const (Params NoParams, x)) Learnee rws g . Learnee lws f = lws `deepseq` rws `deepseq` Learnee (Params (lws, rws)) (h ∘ castParams) where h (lws', rws') x = x `seq` y `seq` lws' `deepseq` rws' `deepseq` (z, up) where (y, f') = f lws' x (z, g') = g rws' y up dz = dz `seq` dy `seq` lws'' `deepseq` rws'' `deepseq` (Params (lws'', rws''), dx) where (rws'', dy) = g' dz (lws'', dx) = f' dy type Loss b = b → b → (b, b) type Regularization b = b → (b, b) class HasNorm a where type Norm a norm ∷ a → Norm a instance HasNorm Float where type Norm Float = Float norm = id instance HasNorm Double where type Norm Double = Double norm = id instance Normed (Vector a) ⇒ HasNorm (Vector a) where type Norm (Vector a) = R norm = norm_1 data Sample a b = Sample { sampleInput ∷ a, sampleOutput ∷ b } deriving (Eq, Ord) (⇢) ∷ a → b → Sample a b (⇢) = Sample instance Bifunctor Sample where bimap f g (Sample x y) = Sample (f x) (g y) instance (Show a, Show b) ⇒ Show (Sample a b) where show (Sample xs ys) = show xs ++ " => " ++ show ys instance (NFData a, NFData b) ⇒ NFData (Sample a b) where rnf (Sample i o) = rnf i `seq` rnf o type Samples a b = V.Vector (Sample a b) samples ∷ [Sample a b] → Samples a b samples = V.fromList
State Before: R : Type u_1 inst✝⁶ : CommRing R S : Submonoid R P : Type u_3 inst✝⁵ : CommRing P inst✝⁴ : Algebra R P loc : IsLocalization S P P' : Type u_2 inst✝³ : CommRing P' inst✝² : Algebra R P' loc' : IsLocalization S P' P'' : Type ?u.574326 inst✝¹ : CommRing P'' inst✝ : Algebra R P'' loc'' : IsLocalization S P'' I✝ J : FractionalIdeal S P g✝ : P →ₐ[R] P' I : FractionalIdeal S P' g : P ≃ₐ[R] P' ⊢ map (↑g) (map (↑(AlgEquiv.symm g)) I) = I State After: no goals Tactic: rw [← map_comp, g.comp_symm, map_id]
{-# OPTIONS --cubical-compatible --sized-types #-} ------------------------------------------------------------------------ -- From the Agda standard library -- -- Sizes for Agda's sized types ------------------------------------------------------------------------ module Common.Size where open import Agda.Builtin.Size public
# The binomial distribution Copyright 2016 Allen Downey MIT License: http://opensource.org/licenses/MIT ```python from __future__ import print_function, division %matplotlib inline %precision 6 import matplotlib.pyplot as plt import numpy as np ``` ```python from inspect import getsourcelines def show_code(func): lines, _ = getsourcelines(func) for line in lines: print(line, end='') ``` ## Pmf Here's a Pmf class that represents a Probability Mass Function, implemented using a Python dictionary that maps from possible outcomes to their probabilities. ```python from distribution import Pmf show_code(Pmf) ``` class Pmf: def __init__(self, d=None): """Initializes the distribution. d: map from values to probabilities """ self.d = {} if d is None else d def items(self): """Returns a sequence of (value, prob) pairs.""" return self.d.items() def __repr__(self): """Returns a string representation of the object.""" cls = self.__class__.__name__ return '%s(%s)' % (cls, repr(self.d)) def __getitem__(self, value): """Looks up the probability of a value.""" return self.d.get(value, 0) def __setitem__(self, value, prob): """Sets the probability associated with a value.""" self.d[value] = prob def __add__(self, other): """Computes the Pmf of the sum of values drawn from self and other. other: another Pmf or a scalar returns: new Pmf """ if other == 0: return self pmf = Pmf() for v1, p1 in self.items(): for v2, p2 in other.items(): pmf[v1 + v2] += p1 * p2 return pmf __radd__ = __add__ def total(self): """Returns the total of the probabilities.""" return sum(self.d.values()) def normalize(self): """Normalizes this PMF so the sum of all probs is 1. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing """ total = self.total() for x in self.d: self.d[x] /= total return total def mean(self): """Computes the mean of a PMF.""" return sum(p * x for x, p in self.items()) def var(self, mu=None): """Computes the variance of a PMF. mu: the point around which the variance is computed; if omitted, computes the mean """ if mu is None: mu = self.mean() return sum(p * (x - mu) ** 2 for x, p in self.items()) def expect(self, func): """Computes the expectation of a given function, E[f(x)] func: function """ return sum(p * func(x) for x, p in self.items()) def display(self): """Displays the values and probabilities.""" for value, prob in self.items(): print(value, prob) def plot_pmf(self, **options): """Plots the values and probabilities.""" xs, ps = zip(*sorted(self.items())) plt.plot(xs, ps, **options) ## The infamous biased coin I'll create a Pmf that represents a biased coin, which has a 60% chance of landing heads and a 40% chance of landing tails. If you are bothered by the fact that it is physically very difficult to bias a coin toss in this way, imagine a 10-sided die with `H` on 6 sides and `T` on 4 sides. ```python coin = Pmf(dict(H=0.6, T=0.4)) coin.display() ``` H 0.6 T 0.4 We can use the `+` operator to compute the possible outcomes of two coin tosses and their probabilities. ```python twice = coin + coin twice.display() ``` HH 0.36 TT 0.16000000000000003 TH 0.24 HT 0.24 And similarly, the possible outcomes of three coin tosses. ```python thrice = sum([coin]*3) thrice.display() ``` TTT 0.06400000000000002 HTT 0.096 THT 0.096 HHH 0.216 HHT 0.144 HTH 0.144 TTH 0.09600000000000002 THH 0.144 Notice that the outcomes take the order of the tosses into account, so `HT` is considered a different outcome from `TH`. If we don't care about the order and we only care about the number of heads and tails, we can loop through the outcomes and count the number of heads. ```python from collections import Counter for val, prob in sorted(thrice.items()): heads = val.count('H') print(heads, prob) ``` 3 0.216 2 0.144 2 0.144 1 0.096 2 0.144 1 0.096 1 0.09600000000000002 0 0.06400000000000002 And we can make a new Pmf that maps from the total number of heads to the probability of that total. ```python def make_pmf_heads(coin, n): coins = sum([coin]*n) pmf = Pmf() for val, prob in coins.items(): heads = val.count('H') pmf[heads] += prob return pmf ``` Here's what it looks like: ```python pmf_heads = make_pmf_heads(coin, 3) pmf_heads.display() ``` 0 0.06400000000000002 1 0.28800000000000003 2 0.43199999999999994 3 0.216 **Exerise:** Create `pmf_heads` for a few different values of `n` and plot them using the `plot_pmf` method. ```python # Solution for n in [5, 10, 15]: make_pmf_heads(coin, n).plot_pmf() ``` **Exerise:** Run the following example and see how long it takes. Try it out with a few values of `n` and see how the run time depends on `n`. ```python n = 15 %time make_pmf_heads(coin, n).plot_pmf() ``` This way of computing `pmf_heads` is not very efficient. For `n` tosses, there are $2^n$ possible outcomes, and for large values of `n`, that is not tractable. In the next section we will figure out a better way. ## The symbolic version Looking at numerical output doesn't tell us much about how to generalize from this example. We can learn more by replacing the numbers with symbols. Here's a version of the Pmf where the probability of heads is the symbol `p`: ```python from sympy import symbols p = symbols('p') sym_coin = Pmf(dict(H=p, T=1-p)) sym_coin.display() ``` H p T -p + 1 Now we can see the distribution of the number of heads, which I'll call `k`, after a few tosses: ```python make_pmf_heads(sym_coin, 2).display() ``` 0 (-p + 1)**2 1 2*p*(-p + 1) 2 p**2 ```python make_pmf_heads(sym_coin, 3).display() ``` 0 (-p + 1)**3 1 3*p*(-p + 1)**2 2 3*p**2*(-p + 1) 3 p**3 ```python make_pmf_heads(sym_coin, 4).display() ``` 0 (-p + 1)**4 1 4*p*(-p + 1)**3 2 6*p**2*(-p + 1)**2 3 4*p**3*(-p + 1) 4 p**4 The general pattern is that probability of `k` heads after `n` tosses is the product of three terms * The probability of `k` heads, which is `p**k`. * The probability of `n-k` tails, which is `(1-p)**(n-k)`. * An integer coefficient. You might already know that the coefficient is the "binomial coefficient", which is written $n \choose k$ and pronounced "n choose k". But pretend for a moment that you don't know that and let's figure it out. ## The binomial coefficient To make the pattern easier to see, I'll create a fair coin where `p = 1-p = 1/2` ```python fair_coin = Pmf(dict(H=p, T=p)) fair_coin.display() ``` H p T p Now the probability of all outcomes is `p**n` ```python thrice = sum([fair_coin]*3) thrice.display() ``` TTT p**3 HTT p**3 THT p**3 HHH p**3 HHT p**3 HTH p**3 TTH p**3 THH p**3 So when we count the number of heads, it is easier to see the coefficients. ```python pmf_heads = make_pmf_heads(fair_coin, 3) pmf_heads.display() ``` 0 p**3 1 3*p**3 2 3*p**3 3 p**3 And even easier if we divide through by `p**n` ```python for val, prob in pmf_heads.items(): print(val, prob / p**3) ``` 0 1 1 3 2 3 3 1 We can assemble the code from the previous cells into a function that prints the coefficients for a given value of `n`: ```python def coefficients(n): fair_coin = Pmf(dict(H=p, T=p)) pmf_heads = make_pmf_heads(fair_coin, n) for val, prob in pmf_heads.items(): print(prob / p**n, end=' ') print() ``` Here are the coefficients for `n=3` ```python coefficients(3) ``` 1 3 3 1 And here they are for `n` in the range from `1` to `9` ```python for n in range(1, 10): coefficients(n) ``` 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 Now we can look for patterns. * If we flip the coin `n` times, the coefficient associated with getting `k` heads is `1` if `k` is `0` or `n`. * Otherwise, the `(n, k)` coefficient is the sum of two coefficients from the previous row: `(n-1, k)` and `(n-1, k-1)` We can use these observations to compute the binomial coefficient recursively: ```python def binomial_coefficient(n, k): if k==0 or k==n: return 1 return binomial_coefficient(n-1, k) + binomial_coefficient(n-1, k-1) ``` And it yields the same results. ```python binomial_coefficient(9, 5) ``` 126 Here are the results for `n` from 1 to 9 again. ```python for n in range(1, 10): for k in range(n+1): print(binomial_coefficient(n, k), end=' ') print() ``` 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 So far so good. **Exercise:** SciPy provides a "special" function called `binom` that you can import from `scipy.special`. Test it to confirm that it is consistent with our function. Note that `scipy.special.binom` returns a float, so for large values of `n` it is only approximate. ```python # Solution from scipy.special import binom binom(9, 5) ``` 126.000000 **Exercise:** The recursive implementation of `binomial_coefficient` is inefficient for large values of `n` because it computes the same intermediate results many times. You can speed it up (a lot!) by memoizing previously computed results. Write a version called `fast_binom` that caches results in a dictionary. ```python # Solution def fast_binom(n, k, cache={}): if k==0 or k==n: return 1 try: return cache[n, k] except KeyError: res = fast_binom(n-1, k) + fast_binom(n-1, k-1) cache[n, k] = res return res for n in range(1, 10): for k in range(n+1): print(binomial_coefficient(n, k), end=' ') print() ``` 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 ## The Binomial PMF Bringing it all together, we have $PMF(k; n,p) = {n \choose k} p^k (1-p)^{n-k}$ This equation can be interpreted at two levels: * If you want to know the probability of `k` heads in `n` tosses, where the probability of heads in each toss is `p`, you can use the formula on the right to compute it. * More abstractly, this equation states that the formula on the right is the PMF of `k` with the parameters `n` and `p`. To make the difference between these interpretations clear, let's look at two functions: 1. `eval_binomial_pmf` evaluates this formula for given values of `k`, `n`, and `p`. 2. `make_binomial_pmf` evaluates the formula for a range of values of `k`, and returns the resulting `Pmf` object. First, here's `eval_binomial_pmf`: ```python from scipy.special import binom def eval_binomial_pmf(k, n, p): return binom(n, k) * p**k * (1-p)**(n-k) ``` We can use it to compute probabilities for each value of `k` directly: ```python n = 3 p = 0.6 for k in range(n+1): print(k, eval_binomial_pmf(k, n, p)) ``` 0 0.064 1 0.288 2 0.432 3 0.216 And here's the corresponding `pmf_heads` for comparison ```python coin = Pmf(dict(H=p, T=1-p)) make_pmf_heads(coin, n).display() ``` 0 0.06400000000000002 1 0.28800000000000003 2 0.43199999999999994 3 0.216 They are the same, at least within floating point error. Now here's `make_binomial_pmf` ```python def make_binomial_pmf(n, p): pmf = Pmf() for k in range(n+1): pmf[k] = eval_binomial_pmf(k, n, p) return pmf ``` We can use it to make a Pmf that contains the possible values of `k` and their probabilities: ```python pmf = make_binomial_pmf(n, p) pmf.display() ``` 0 0.064 1 0.288 2 0.432 3 0.216 Here's what the distribution of `k` looks like for given values of `n` and `p`: ```python pmf.plot_pmf() plt.xlabel('k'); ``` If we hold `p` constant, we can see how the distribution of `k` changes as `n` increases ```python p = 0.6 for n in [5, 10, 15]: make_binomial_pmf(n, p).plot_pmf(label=n) plt.legend(); ``` **Exercise:** Keeping `n=10`, plot the distribution of `k` for a few different values of `p`. ```python # Solution n = 10 for p in [0.2, 0.5, 0.8]: make_binomial_pmf(n, p).plot_pmf(label=p) plt.legend(); ``` The Pmf objects we just created represent differnet distributions of `k` based on different values of the parameters `n` and `p`. As `make_binomial_pmf` demonstrates, if you give me `n` and `p`, I can compute a distribution of `k`. Speaking casually, people sometimes refer to this equation as the PMF of "the" binomial distribution: $PMF(k; n,p) = {n \choose k} p^k (1-p)^{n-k}$ More precisely, it is a "family" of distributions, where the parameters `n` and `p` specify a particular member of the family. **Exercise:** Suppose you toss a fair coin 10 times. What is the probability of getting 5 heads? If you run this experiment many times, what is the mean number of heads you expect? What is the variance in the number of heads? ```python # Solution n = 10 p = 0.5 pmf = make_binomial_pmf(n, p) print(pmf[5]) print(pmf.mean()) print(pmf.var()) ``` 0.24609375 5.0 2.5 **Exercise:** Suppose you toss a fair coin 10 times. What is the probability of getting fewer than 5 heads? If you run this experiment many times, what is the median number of heads you expect? What is the interquartile range (IQR) in the number of heads? Hint: You might want to make a CDF. ```python # Solution from distribution import compute_cumprobs, Cdf xs, ps = compute_cumprobs(pmf.d) cdf = Cdf(xs, ps) print(cdf[4]) low, median, high = cdf.values([0.25, 0.5, 0.75]) print(median, high-low) ``` 0.376953125 5 2 ```python ```
### following RWeka packages can be downloaded in site: http://sourceforge.net/projects/weka/files/weka-packages/ # RWeka::WPM("install-package", "./packages/linearForwardSelection1.0.1.zip") # RWeka::WPM("install-package", "./packages/ridor1.0.1.zip") # RWeka::WPM("install-package", "./packages/EMImputation1.0.1.zip") # RWeka::WPM("install-package", "./packages/citationKNN1.0.1.zip") # RWeka::WPM("install-package", "./packages/isotonicRegression1.0.1.zip") # RWeka::WPM("install-package", "./packages/paceRegression1.0.1.zip") # RWeka::WPM("install-package", "./packages/leastMedSquared1.0.1.zip") # RWeka::WPM("install-package", "./packages/RBFNetwork1.0.8.zip") # RWeka::WPM("install-package", "./packages/conjunctiveRule1.0.4.zip") # RWeka::WPM("install-package", "./packages/rotationForest1.0.2.zip") getWekaClassifier <- function(name) { WC <- NULL if (name %in% c("LinearRegression", "Logistic", "SMO", "IBk", "LBR", "AdaBoostM1", "Bagging", "LogitBoost", "MultiBoostAB", "Stacking", "CostSensitiveClassifier", "JRip", "M5Rules", "OneR", "PART", "J48", "LMT", "M5P", "DecisionStump", "SimpleKMeans")) { WC <- get(name, asNamespace("RWeka")) } else { if (name=="NaiveBayes") { WC <- RWeka::make_Weka_classifier("weka/classifiers/bayes/NaiveBayes") } else if (name %in% c("GaussianProcesses", "SimpleLogistic", "SimpleLinearRegression", "IsotonicRegression", "LeastMedSq", "MultilayerPerceptron", "PaceRegression", "PLSClassifier", "RBFNetwork", "SMOreg")) { WC <- RWeka::make_Weka_classifier(paste("weka/classifiers/functions/", name, sep="")) } else if (name %in% c("KStar", "LWL")) { WC <- RWeka::make_Weka_classifier(paste("weka/classifiers/lazy/", name, sep="")) } else if (name %in% c("Bagging", "AdaBoostM1", "RotationForest", "RandomSubSpace", "AdditiveRegression", "AttributeSelectedClassifier", "CVParameterSelection", "Grading", "GridSearch", "MultiScheme", "RegressionByDiscretization", "StackingC", "Vote")) { WC <- RWeka::make_Weka_classifier(paste("weka/classifiers/meta/", name, sep="")) } else if (name %in% c("ConjunctiveRule", "DecisionTable", "ZeroR", "Ridor")) { WC <- RWeka::make_Weka_classifier(paste("weka/classifiers/rules/", name, sep="")) } else if (name %in% c("REPTree", "UserClassifier", "RandomForest")) { WC <- RWeka::make_Weka_classifier(paste("weka/classifiers/trees/", name, sep="")) } } return(WC) }
We will replace or refund any bottle of wine that is damaged or flawed by either the winemaking or improper shipping of that wine from the winery. We ask that you return the unfinished portion of the original bottle for replacement. As wine is a natural food product, it is subject to spoilage, and each wine is unique. We are unable to replace wine which has been spoiled by improper storage, transportation, or extended aging. *You store and age wines at your own risk*. Please send an email to [email protected] to arrange for the return of any corked or otherwise inherantly flawed product, or if you have additional questions. Once the wine is received we will refund your credit card account for the cost of the wine less shipping and handling. A 25% restocking fee will be applied to all canceled orders or wines returned for quality issues stemming from conditions beyond our control, or for any cancelled wine club shipments. Wine Club Cancellation: 30 days written notice required. We will charge for any shipment scheduled to occur within thirty (30) days after the date a cancellation request is received; no further billing will occur thereafter.
If $A$ is a compact set, then the Lebesgue measure of $A$ is finite.
If $c \neq 0$, then a sequence $f$ is bounded if and only if the sequence $c f$ is bounded.
#ifndef FFG_EXT_XML_H_INCLUDED #define FFG_EXT_XML_H_INCLUDED #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <string> #include <vector> /***************************************************************************//** * A class that represents an XML tag. * * Example usage: * ----------------------------------------------------------------------------- * TODO: Add example usage. * ----------------------------------------------------------------------------- ******************************************************************************/ class FFG_XML_Tag { public: /***************************************************************************//** * The index of this tag's parent. ******************************************************************************/ int parent; /***************************************************************************//** * The index of this tag's first child. ******************************************************************************/ int first_child; /***************************************************************************//** * The number of children this tag has. ******************************************************************************/ int num_children; /***************************************************************************//** * The name of this tag. ******************************************************************************/ std::string name; /***************************************************************************//** * The inner text of this tag. ******************************************************************************/ std::string inner_text; /***************************************************************************//** * The attributes of this tag. ******************************************************************************/ std::vector<std::pair<std::string, std::string>> attributes; public: FFG_XML_Tag(); std::string get_attribute(const std::string& attribute_name, const std::string& default_value); }; /***************************************************************************//** * A class for parsing XML documents. A thin wrapper over boost's property_tree. * * Example usage: * ----------------------------------------------------------------------------- * TODO: Add example usage. * ----------------------------------------------------------------------------- ******************************************************************************/ class FFG_XML { public: /***************************************************************************//** * The tags of the parsed XML document. ******************************************************************************/ std::vector<FFG_XML_Tag> tags; private: bool is_tag(const std::string& name); void parse_tree(const boost::property_tree::ptree& tree, int parent_index); public: void parse(const std::string filepath); }; #endif // FFG_EXT_XML_H_INCLUDED
Update: Petland coupons are not available at the moment, you can check our Pet coupons for other pet stores and manufacturers. Coupon says its valid only at Pickerington store in Ohio, but you can this coupon at their other stores they will take them. Spend $30 at the petland store in Pickerington and get $10 off. Get a $100 discount on the original price of any new puppy. Print coupon for a $5 discount in store at your local petland pet store. Purchase must be over $25. Petland provides wholesale distribution for pet food, pet supplies for dogs, cats, Fish, Reptiles, and Birds. For more than 45 years, Petland has been one of our nations leading pet industry leader with in-store animal husbandry systems and community service programs aimed at placing homeless pets and curbing pet overpopulation in the community.
%!TEX program = pdflatex % Full chain: pdflatex -> bibtex -> pdflatex -> pdflatex \documentclass[lang=en,12pt]{elegantpaper} \usepackage{url} \usepackage[binary-units=true]{siunitx} \newcommand{\mysec}[1] { \SI[per-mode=symbol]{#1}{\second} } \title{Gomoku AI Based On Deep Learning} \author{Yechang WU (11711918), You Lin (11711809)} \institute{Southern University of Science and Technology} \date{\today} \begin{document} \maketitle \begin{abstract} Gomoku, also called Five in a Row, is an abstract strategy board game. It is traditionally played with Go pieces (black and white stones) on a Go board, using 15$\times$15 of the 19$\times$19 grid intersections. The game is known in several countries under different names.While playing Gomoku, players alternate turns placing a stone of their color on an empty intersection. The winner is the first player to form an unbroken chain of five stones horizontally, vertically, or diagonally. \keywords{Gomoku, Game AI, Deep neural network, Reinforcement learning} \end{abstract} \section{Introduction} \subsection{topic selected} a) : the application of the Gomoku based on the tensorflow. \subsection{data selection} \subsection{model selection} \subsection{performance goal} a) can win AI on the internet. \subsection{Prerequisites} \subsection{training process} a) deploy the program of AI written in tensorflow into the ModelArt, b) test the performance of the model with the times go \subsection{the method of evaluation} a) let the AI play with another AI on the internet and take the win rate of a large number of competition into consideration % \nocite{*} % \bibliography{wpref} \end{document}
/* fft/gsl_fft_real_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_FFT_REAL_FLOAT_H__ #define __GSL_FFT_REAL_FLOAT_H__ #include <stddef.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_fft.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS int gsl_fft_real_float_radix2_transform (float data[], const size_t stride, const size_t n) ; typedef struct { size_t n; size_t nf; size_t factor[64]; gsl_complex_float *twiddle[64]; gsl_complex_float *trig; } gsl_fft_real_wavetable_float; typedef struct { size_t n; float *scratch; } gsl_fft_real_workspace_float; gsl_fft_real_wavetable_float * gsl_fft_real_wavetable_float_alloc (size_t n); void gsl_fft_real_wavetable_float_free (gsl_fft_real_wavetable_float * wavetable); gsl_fft_real_workspace_float * gsl_fft_real_workspace_float_alloc (size_t n); void gsl_fft_real_workspace_float_free (gsl_fft_real_workspace_float * workspace); int gsl_fft_real_float_transform (float data[], const size_t stride, const size_t n, const gsl_fft_real_wavetable_float * wavetable, gsl_fft_real_workspace_float * work); int gsl_fft_real_float_unpack (const float real_float_coefficient[], float complex_coefficient[], const size_t stride, const size_t n); __END_DECLS #endif /* __GSL_FFT_REAL_FLOAT_H__ */
#include "project_build.hpp" #include "config.hpp" #include "filesystem.hpp" #include "json.hpp" #include "terminal.hpp" #include <boost/algorithm/string.hpp> #include <regex> std::unique_ptr<Project::Build> Project::Build::create(const boost::filesystem::path &path) { if(path.empty()) return std::make_unique<Project::Build>(); boost::system::error_code ec; auto search_path = boost::filesystem::is_directory(path, ec) ? path : path.parent_path(); while(true) { if(boost::filesystem::exists(search_path / "CMakeLists.txt", ec)) { std::unique_ptr<Project::Build> build(new CMakeBuild(path)); if(!build->project_path.empty()) return build; else return std::make_unique<Project::Build>(); } if(boost::filesystem::exists(search_path / "meson.build"), ec) { std::unique_ptr<Project::Build> build(new MesonBuild(path)); if(!build->project_path.empty()) return build; } if(boost::filesystem::exists(search_path / Config::get().project.default_build_path / "compile_commands.json", ec)) { std::unique_ptr<Project::Build> build(new CompileCommandsBuild()); build->project_path = search_path; return build; } if(boost::filesystem::exists(search_path / "Cargo.toml", ec)) { std::unique_ptr<Project::Build> build(new CargoBuild()); build->project_path = search_path; return build; } if(boost::filesystem::exists(search_path / "package.json", ec)) { std::unique_ptr<Project::Build> build(new NpmBuild()); build->project_path = search_path; return build; } if(boost::filesystem::exists(search_path / "__main__.py", ec)) { std::unique_ptr<Project::Build> build(new PythonMain()); build->project_path = search_path; return build; } if(boost::filesystem::exists(search_path / "go.mod", ec)) { std::unique_ptr<Project::Build> build(new GoBuild()); build->project_path = search_path; return build; } if(search_path == search_path.root_directory()) break; search_path = search_path.parent_path(); } return std::make_unique<Project::Build>(); } boost::filesystem::path Project::Build::get_default_path() { if(project_path.empty()) return boost::filesystem::path(); boost::filesystem::path default_build_path = Config::get().project.default_build_path; auto default_build_path_string = default_build_path.string(); boost::replace_all(default_build_path_string, "<project_directory_name>", project_path.filename().string()); default_build_path = default_build_path_string; if(default_build_path.is_relative()) default_build_path = project_path / default_build_path; return filesystem::get_normal_path(default_build_path); } boost::filesystem::path Project::Build::get_debug_path() { if(project_path.empty()) return boost::filesystem::path(); boost::filesystem::path debug_build_path = Config::get().project.debug_build_path; auto debug_build_path_string = debug_build_path.string(); boost::replace_all(debug_build_path_string, "<default_build_path>", Config::get().project.default_build_path); boost::replace_all(debug_build_path_string, "<project_directory_name>", project_path.filename().string()); debug_build_path = debug_build_path_string; if(debug_build_path.is_relative()) debug_build_path = project_path / debug_build_path; return filesystem::get_normal_path(debug_build_path); } std::vector<std::string> Project::Build::get_exclude_folders() { auto default_build_path = Config::get().project.default_build_path; boost::replace_all(default_build_path, "<project_directory_name>", ""); auto debug_build_path = Config::get().project.debug_build_path; boost::replace_all(debug_build_path, "<default_build_path>", Config::get().project.default_build_path); boost::replace_all(debug_build_path, "<project_directory_name>", ""); return std::vector<std::string>{ ".git", "build", "debug", // Common exclude folders boost::filesystem::path(default_build_path).filename().string(), boost::filesystem::path(debug_build_path).filename().string(), // C/C++ "target", // Rust "node_modules", "dist", "coverage", ".expo", // JavaScript ".mypy_cache", "__pycache__" // Python }; } Project::CMakeBuild::CMakeBuild(const boost::filesystem::path &path) : Project::Build(), cmake(path) { project_path = cmake.project_path; } bool Project::CMakeBuild::update_default(bool force) { return cmake.update_default_build(get_default_path(), force); } bool Project::CMakeBuild::update_debug(bool force) { return cmake.update_debug_build(get_debug_path(), force); } std::string Project::CMakeBuild::get_compile_command() { return Config::get().project.cmake.compile_command; } boost::filesystem::path Project::CMakeBuild::get_executable(const boost::filesystem::path &path) { auto default_path = get_default_path(); auto executable = cmake.get_executable(default_path, path); if(executable.empty()) { auto src_path = project_path / "src"; boost::system::error_code ec; if(boost::filesystem::is_directory(src_path, ec)) executable = CMake(src_path).get_executable(default_path, src_path); } return executable; } bool Project::CMakeBuild::is_valid() { if(project_path.empty()) return true; auto default_path = get_default_path(); if(default_path.empty()) return true; std::ifstream input((default_path / "CMakeCache.txt").string(), std::ios::binary); if(!input) return true; std::string line; while(std::getline(input, line)) { const static std::regex regex("^.*_SOURCE_DIR:STATIC=(.*)$", std::regex::optimize); std::smatch sm; if(std::regex_match(line, sm, regex)) return boost::filesystem::path(sm[1].str()) == project_path; } return true; } Project::MesonBuild::MesonBuild(const boost::filesystem::path &path) : Project::Build(), meson(path) { project_path = meson.project_path; } bool Project::MesonBuild::update_default(bool force) { return meson.update_default_build(get_default_path(), force); } bool Project::MesonBuild::update_debug(bool force) { return meson.update_debug_build(get_debug_path(), force); } std::string Project::MesonBuild::get_compile_command() { return Config::get().project.meson.compile_command; } boost::filesystem::path Project::MesonBuild::get_executable(const boost::filesystem::path &path) { auto default_path = get_default_path(); auto executable = meson.get_executable(default_path, path); if(executable.empty()) { auto src_path = project_path / "src"; boost::system::error_code ec; if(boost::filesystem::is_directory(src_path, ec)) executable = meson.get_executable(default_path, src_path); } return executable; } bool Project::MesonBuild::is_valid() { if(project_path.empty()) return true; auto default_path = get_default_path(); if(default_path.empty()) return true; try { JSON info(default_path / "meson-info" / "meson-info.json"); return boost::filesystem::path(info.object("directories").string("source")) == project_path; } catch(...) { } return true; } bool Project::CargoBuild::update_default(bool force) { auto default_build_path = get_default_path(); if(default_build_path.empty()) return false; boost::system::error_code ec; if(!boost::filesystem::exists(default_build_path, ec)) { boost::system::error_code ec; boost::filesystem::create_directories(default_build_path, ec); if(ec) { Terminal::get().print("\e[31mError\e[m: could not create " + filesystem::get_short_path(default_build_path).string() + ": " + ec.message() + "\n", true); return false; } } return true; } bool Project::CargoBuild::update_debug(bool force) { return update_default(force); } std::string Project::CargoBuild::get_compile_command() { return Config::get().project.cargo_command + " build"; } boost::filesystem::path Project::CargoBuild::get_executable(const boost::filesystem::path &path) { auto project_name = project_path.filename().string(); for(auto &chr : project_name) { if(chr == ' ') chr = '_'; } return get_debug_path() / project_name; }
section\<open>Generalize Simple Firewall\<close> theory Generic_SimpleFw imports SimpleFw_Semantics "Common/List_Product_More" "Common/Option_Helpers" begin subsection\<open>Semantics\<close> text\<open>The semantics of the @{term simple_fw} is quite close to @{const List.find}. The idea of the generalized @{term simple_fw} semantics is that you can have anything as the resulting action, not only a @{type simple_action}.\<close> definition generalized_sfw :: "('i::len simple_match \<times> 'a) list \<Rightarrow> ('i, 'pkt_ext) simple_packet_scheme \<Rightarrow> ('i simple_match \<times> 'a) option" where "generalized_sfw l p \<equiv> find (\<lambda>(m,a). simple_matches m p) l" subsection\<open>Lemmas\<close> lemma generalized_sfw_simps: "generalized_sfw [] p = None" "generalized_sfw (a # as) p = (if (case a of (m,_) \<Rightarrow> simple_matches m p) then Some a else generalized_sfw as p)" unfolding generalized_sfw_def by simp_all lemma generalized_sfw_append: "generalized_sfw (a @ b) p = (case generalized_sfw a p of Some x \<Rightarrow> Some x | None \<Rightarrow> generalized_sfw b p)" by(induction a) (simp_all add: generalized_sfw_simps) lemma simple_generalized_undecided: "simple_fw fw p \<noteq> Undecided \<Longrightarrow> generalized_sfw (map simple_rule_dtor fw) p \<noteq> None" by(induction fw) (clarsimp simp add: generalized_sfw_def simple_fw_alt simple_rule_dtor_def split: prod.splits if_splits simple_action.splits simple_rule.splits)+ lemma generalized_sfwSomeD: "generalized_sfw fw p = Some (r,d) \<Longrightarrow> (r,d) \<in> set fw \<and> simple_matches r p" unfolding generalized_sfw_def by(induction fw) (simp split: if_split_asm)+ lemma generalized_sfw_NoneD: "generalized_sfw fw p = None \<Longrightarrow> \<forall>(a,b) \<in> set fw. \<not> simple_matches a p" by(induction fw) (clarsimp simp add: generalized_sfw_simps split: if_splits)+ lemma generalized_fw_split: "generalized_sfw fw p = Some r \<Longrightarrow> \<exists>fw1 fw3. fw = fw1 @ r # fw3 \<and> generalized_sfw fw1 p = None" apply(induction fw rule: rev_induct) apply(simp add: generalized_sfw_simps generalized_sfw_append split: option.splits;fail) apply(clarsimp simp add: generalized_sfw_simps generalized_sfw_append split: option.splits if_splits) apply blast+ done lemma generalized_sfw_filterD: "generalized_sfw (filter f fw) p = Some (r,d) \<Longrightarrow> simple_matches r p \<and> f (r,d)" by(induction fw) (simp_all add: generalized_sfw_simps split: if_splits) lemma generalized_sfw_mapsnd: "generalized_sfw (map (apsnd f) fw) p = map_option (apsnd f) (generalized_sfw fw p)" by(induction fw) (simp add: generalized_sfw_simps split: prod.splits)+ subsection\<open>Equality with the Simple Firewall\<close> text\<open>A matching action of the simple firewall directly corresponds to a filtering decision\<close> definition simple_action_to_decision :: "simple_action \<Rightarrow> state" where "simple_action_to_decision a \<equiv> case a of Accept \<Rightarrow> Decision FinalAllow | Drop \<Rightarrow> Decision FinalDeny" text\<open>The @{const simple_fw} and the @{const generalized_sfw} are equal, if the state is translated appropriately.\<close> lemma simple_fw_iff_generalized_fw: "simple_fw fw p = simple_action_to_decision a \<longleftrightarrow> (\<exists>r. generalized_sfw (map simple_rule_dtor fw) p = Some (r,a))" by(induction fw) (clarsimp simp add: generalized_sfw_simps simple_rule_dtor_def simple_fw_alt simple_action_to_decision_def split: simple_rule.splits if_splits simple_action.splits)+ lemma simple_fw_iff_generalized_fw_accept: "simple_fw fw p = Decision FinalAllow \<longleftrightarrow> (\<exists>r. generalized_sfw (map simple_rule_dtor fw) p = Some (r, Accept))" by(fact simple_fw_iff_generalized_fw[where a = simple_action.Accept, unfolded simple_action_to_decision_def simple_action.simps]) lemma simple_fw_iff_generalized_fw_drop: "simple_fw fw p = Decision FinalDeny \<longleftrightarrow> (\<exists>r. generalized_sfw (map simple_rule_dtor fw) p = Some (r, Drop))" by(fact simple_fw_iff_generalized_fw[where a = simple_action.Drop, unfolded simple_action_to_decision_def simple_action.simps]) subsection\<open>Joining two firewalls, i.e. a packet is send through both sequentially.\<close> definition generalized_fw_join :: "('i::len simple_match \<times> 'a) list \<Rightarrow> ('i simple_match \<times> 'b) list \<Rightarrow> ('i simple_match \<times> 'a \<times> 'b) list" where "generalized_fw_join l1 l2 \<equiv> [(u,(a,b)). (m1,a) \<leftarrow> l1, (m2,b) \<leftarrow> l2, u \<leftarrow> option2list (simple_match_and m1 m2)]" lemma generalized_fw_join_1_Nil[simp]: "generalized_fw_join [] f2 = []" unfolding generalized_fw_join_def by(induction f2) simp+ lemma generalized_fw_join_2_Nil[simp]: "generalized_fw_join f1 [] = []" unfolding generalized_fw_join_def by(induction f1) simp+ lemma generalized_fw_join_cons_1: "generalized_fw_join ((am,ad) # l1) l2 = [(u,(ad,b)). (m2,b) \<leftarrow> l2, u \<leftarrow> option2list (simple_match_and am m2)] @ generalized_fw_join l1 l2" unfolding generalized_fw_join_def by(simp) lemma generalized_fw_join_1_nomatch: "\<not> simple_matches am p \<Longrightarrow> generalized_sfw [(u,(ad,b)). (m2,b) \<leftarrow> l2, u \<leftarrow> option2list (simple_match_and am m2)] p = None" by(induction l2) (clarsimp simp add: generalized_sfw_simps generalized_sfw_append option2list_def simple_match_and_SomeD split: prod.splits option.splits)+ lemma generalized_fw_join_2_nomatch: "\<not> simple_matches bm p \<Longrightarrow> generalized_sfw (generalized_fw_join as ((bm, bd) # bs)) p = generalized_sfw (generalized_fw_join as bs) p" proof(induction as) case (Cons a as) note mIH = Cons.IH[OF Cons.prems] obtain am ad where a[simp]: "a = (am, ad)" by(cases a) have *: "generalized_sfw (concat (map (\<lambda>(m2, b). map (\<lambda>u. (u, ad, b)) (option2list (simple_match_and am m2))) ((bm, bd) # bs))) p = generalized_sfw (concat (map (\<lambda>(m2, b). map (\<lambda>u. (u, ad, b)) (option2list (simple_match_and am m2))) bs)) p" unfolding list.map prod.simps apply(cases "simple_match_and am bm") apply(simp add: option2list_def; fail) apply(frule simple_match_and_SomeD[of _ _ _ p]) apply(subst option2list_def) apply(unfold concat.simps) apply(simp add: generalized_sfw_simps Cons.prems) done show ?case unfolding a unfolding generalized_fw_join_cons_1 unfolding generalized_sfw_append unfolding mIH unfolding * .. qed(simp add: generalized_fw_join_def) lemma generalized_fw_joinI: "\<lbrakk>generalized_sfw f1 p = Some (r1,d1); generalized_sfw f2 p = Some (r2,d2)\<rbrakk> \<Longrightarrow> generalized_sfw (generalized_fw_join f1 f2) p = Some (the (simple_match_and r1 r2), d1,d2)" proof(induction f1) case (Cons a as) obtain am ad where a[simp]: "a = Pair am ad" by(cases a) show ?case proof(cases "simple_matches am p") case True hence dra: "d1 = ad" "r1 = am" using Cons.prems by(simp_all add: generalized_sfw_simps) from Cons.prems(2) show ?thesis unfolding a dra proof(induction f2) case (Cons b bs) obtain bm bd where b[simp]: "b = Pair bm bd" by(cases b) thus ?case proof(cases "simple_matches bm p") case True hence drb: "d2 = bd" "r2 = bm" using Cons.prems by(simp_all add: generalized_sfw_simps) from True \<open>simple_matches am p\<close> obtain ruc where sma[simp]: "simple_match_and am bm = Some ruc" "simple_matches ruc p" using simple_match_and_correct[of am p bm] by(simp split: option.splits) show ?thesis unfolding b by(simp add: generalized_fw_join_def option2list_def generalized_sfw_simps drb) next case False with Cons.prems have bd: "generalized_sfw (b # bs) p = generalized_sfw bs p" "generalized_sfw (b # bs) p = Some (r2, d2)" by(simp_all add: generalized_sfw_simps) note mIH = Cons.IH[OF bd(2)[unfolded bd(1)]] show ?thesis unfolding mIH[symmetric] b using generalized_fw_join_2_nomatch[OF False, of "(am, ad) # as" bd bs] . qed qed(simp add: generalized_sfw_simps generalized_fw_join_def) (*and empty_concat: "concat (map (\<lambda>x. []) ms) = []" by simp*) next case False with Cons.prems have "generalized_sfw (a # as) p = generalized_sfw as p" by(simp add: generalized_sfw_simps) with Cons.prems have "generalized_sfw as p = Some (r1, d1)" by simp note mIH = Cons.IH[OF this Cons.prems(2)] show ?thesis unfolding mIH[symmetric] a unfolding generalized_fw_join_cons_1 unfolding generalized_sfw_append unfolding generalized_fw_join_1_nomatch[OF False, of ad f2] by simp qed qed(simp add: generalized_fw_join_def generalized_sfw_simps;fail) (* The structure is nearly the same as with generalized_fw_joinI, so it should be possible to show it in one proof. But I felt like this is the better way *) lemma generalized_fw_joinD: "generalized_sfw (generalized_fw_join f1 f2) p = Some (u, d1,d2) \<Longrightarrow> \<exists>r1 r2. generalized_sfw f1 p = Some (r1,d1) \<and> generalized_sfw f2 p = Some (r2,d2) \<and> Some u = simple_match_and r1 r2" proof(induction f1) case (Cons a as) obtain am ad where a[simp]: "a = Pair am ad" by(cases a) show ?case proof(cases "simple_matches am p", rule exI) case True show "\<exists>r2. generalized_sfw (a # as) p = Some (am, d1) \<and> generalized_sfw f2 p = Some (r2, d2) \<and> Some u = simple_match_and am r2" using Cons.prems proof(induction f2) case (Cons b bs) obtain bm bd where b[simp]: "b = Pair bm bd" by(cases b) show ?case proof(cases "simple_matches bm p", rule exI) case True with \<open>simple_matches am p\<close> obtain u' (* u' = u, but I don't need that yet. *) where sma: "simple_match_and am bm = Some u' \<and> simple_matches u' p" using simple_match_and_correct[of am p bm] by(simp split: option.splits) show "generalized_sfw (a # as) p = Some (am, d1) \<and> generalized_sfw (b # bs) p = Some (bm, d2) \<and> Some u = simple_match_and am bm" using Cons.prems True \<open>simple_matches am p\<close> by(simp add: generalized_fw_join_def generalized_sfw_append sma generalized_sfw_simps) next case False have "generalized_sfw (generalized_fw_join (a # as) bs) p = Some (u, d1, d2)" using Cons.prems unfolding b unfolding generalized_fw_join_2_nomatch[OF False] . note Cons.IH[OF this] moreover have "generalized_sfw (b # bs) p = generalized_sfw bs p" using False by(simp add: generalized_sfw_simps) ultimately show ?thesis by presburger qed qed(simp add: generalized_sfw_simps) next case False with Cons.prems have "generalized_sfw (generalized_fw_join as f2) p = Some (u, d1, d2)" by(simp add: generalized_fw_join_cons_1 generalized_sfw_append generalized_fw_join_1_nomatch) note Cons.IH[OF this] moreover have "generalized_sfw (a # as) p = generalized_sfw as p" using False by(simp add: generalized_sfw_simps) ultimately show ?thesis by presburger qed qed(simp add: generalized_fw_join_def generalized_sfw_simps) text\<open>We imagine two firewalls are positioned directly after each other. The first one has ruleset rs1 installed, the second one has ruleset rs2 installed. A packet needs to pass both firewalls.\<close> theorem simple_fw_join: defines "rule_translate \<equiv> map (\<lambda>(u,a,b). SimpleRule u (if a = Accept \<and> b = Accept then Accept else Drop))" shows "simple_fw rs1 p = Decision FinalAllow \<and> simple_fw rs2 p = Decision FinalAllow \<longleftrightarrow> simple_fw (rule_translate (generalized_fw_join (map simple_rule_dtor rs1) (map simple_rule_dtor rs2))) p = Decision FinalAllow" proof - have hlp1: "simple_rule_dtor \<circ> (\<lambda>(u, a, b). SimpleRule u (if a = Accept \<and> b = Accept then Accept else Drop)) = apsnd (\<lambda>(a, b). if a = Accept \<and> b = Accept then Accept else Drop)" unfolding fun_eq_iff comp_def by(simp add: simple_rule_dtor_def) show ?thesis unfolding simple_fw_iff_generalized_fw_accept apply(rule) apply(clarify) apply(drule (1) generalized_fw_joinI) apply(simp add: hlp1 rule_translate_def generalized_sfw_mapsnd ;fail) apply(clarsimp simp add: hlp1 generalized_sfw_mapsnd rule_translate_def) apply(drule generalized_fw_joinD) apply(clarsimp split: if_splits) done qed theorem simple_fw_join2: --\<open>translates a @{text "(match, action1, action2)"} tuple of the joined generalized firewall to a @{typ "'i::len simple_rule list"}. The two actions are translated such that you only get @{const Accept} if both actions are @{const Accept}\<close> defines "to_simple_rule_list \<equiv> map (apsnd (\<lambda>(a,b) \<Rightarrow> (case a of Accept \<Rightarrow> b | Drop \<Rightarrow> Drop)))" shows "simple_fw rs1 p = Decision FinalAllow \<and> simple_fw rs2 p = Decision FinalAllow \<longleftrightarrow> (\<exists>m. (generalized_sfw (to_simple_rule_list (generalized_fw_join (map simple_rule_dtor rs1) (map simple_rule_dtor rs2))) p) = Some (m, Accept))" unfolding simple_fw_iff_generalized_fw_accept apply(rule) apply(clarify) apply(drule (1) generalized_fw_joinI) apply(clarsimp simp add: to_simple_rule_list_def generalized_sfw_mapsnd; fail) apply(clarsimp simp add: to_simple_rule_list_def generalized_sfw_mapsnd) apply(drule generalized_fw_joinD) apply(clarsimp split: if_splits simple_action.splits) done lemma generalized_fw_join_1_1: "generalized_fw_join [(m1,d1)] fw2 = foldr (\<lambda>(m2,d2). op @ (case simple_match_and m1 m2 of None \<Rightarrow> [] | Some mu \<Rightarrow> [(mu,d1,d2)])) fw2 []" proof - have concat_map_foldr: "concat (map (\<lambda>x. f x) l) = foldr (\<lambda>x. op @ (f x)) l []" for f :: "'x \<Rightarrow> 'y list" and l by(induction l) simp_all show ?thesis apply(simp add: generalized_fw_join_cons_1 option2list_def) apply(simp add: concat_map_foldr) apply(unfold list.map prod.case_distrib option.case_distrib) by simp qed lemma generalized_sfw_2_join_None: "generalized_sfw fw2 p = None \<Longrightarrow> generalized_sfw (generalized_fw_join fw1 fw2) p = None" by(induction fw2) (simp_all add: generalized_sfw_simps generalized_sfw_append generalized_fw_join_2_nomatch split: if_splits option.splits prod.splits) lemma generalized_sfw_1_join_None: "generalized_sfw fw1 p = None \<Longrightarrow> generalized_sfw (generalized_fw_join fw1 fw2) p = None" by(induction fw1) (simp_all add: generalized_sfw_simps generalized_fw_join_cons_1 generalized_sfw_append generalized_fw_join_1_nomatch split: if_splits option.splits prod.splits) lemma generalized_sfw_join_set: "(a, b1, b2) \<in> set (generalized_fw_join f1 f2) \<longleftrightarrow> (\<exists>a1 a2. (a1, b1) \<in> set f1 \<and> (a2, b2) \<in> set f2 \<and> simple_match_and a1 a2 = Some a)" unfolding generalized_fw_join_def apply(rule iffI) subgoal unfolding generalized_fw_join_def by(clarsimp simp: option2set_def split: option.splits) blast by(clarsimp simp: option2set_def split: option.splits) fastforce subsection\<open>Validity\<close> text\<open>There's validity of matches on @{const generalized_sfw}, too, even on the join.\<close> definition gsfw_valid :: "('i::len simple_match \<times> 'c) list \<Rightarrow> bool" where "gsfw_valid \<equiv> list_all (simple_match_valid \<circ> fst)" lemma gsfw_join_valid: "gsfw_valid f1 \<Longrightarrow> gsfw_valid f2 \<Longrightarrow> gsfw_valid (generalized_fw_join f1 f2)" unfolding gsfw_valid_def apply(induction f1) apply(simp;fail) apply(simp) apply(rename_tac a f1) apply(case_tac a) apply(simp add: generalized_fw_join_cons_1) apply(clarify) apply(thin_tac "list_all _ f1") apply(thin_tac "list_all _ (generalized_fw_join _ _)") apply(induction f2) apply(simp;fail) apply(simp) apply(clarsimp simp add: option2list_def list_all_iff) using simple_match_and_valid apply metis done lemma gsfw_validI: "simple_fw_valid fw \<Longrightarrow> gsfw_valid (map simple_rule_dtor fw)" unfolding gsfw_valid_def simple_fw_valid_def by(clarsimp simp add: simple_rule_dtor_def list_all_iff split: simple_rule.splits) fastforce end
! <cwdeprate.f90 - A component of the City-scale ! Chemistry Transport Model EPISODE-CityChem> !*****************************************************************************! !* !* EPISODE - An urban-scale air quality model !* ========================================== !* Copyright (C) 2018 NILU - Norwegian Institute for Air Research !* Instituttveien 18 !* PO Box 100 !* NO-2027 Kjeller !* Norway !* !* Contact persons: Gabriela Sousa Santos - [email protected] !* Paul Hamer - [email protected] !* !* Unless explicitly acquired and licensed from Licensor under another license, !* the contents of this file are subject to the Reciprocal Public License ("RPL") !* Version 1.5, https://opensource.org/licenses/RPL-1.5 or subsequent versions as !* allowed by the RPL, and You may not copy or use this file in either source code !* or executable form, except in compliance with the terms and conditions of the RPL. !* !* All software distributed under the RPL is provided strictly on an "AS IS" basis, !* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND LICENSOR HEREBY !* DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF !* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. !* See the RPL for specific language governing rights and limitations under the RPL. !* !* ========================================== !* The dispersion model EPISODE (Grønskei et. al., 1993; Larssen et al., 1994; !* Walker et al., 1992, 1999; Slørdal et al., 2003, 2008) is an Eulerian grid model !* with embedded subgrid models for calculations of pollutant concentrations resulting !* from different types of sources (area-, line- and point sources). EPISODE solves the !* time dependent advection/-diffusion equation on a 3 dimensional grid. !* Finite difference numerical methods are applied to integrate the solution forward in time. !* It also includes extensions as the implementation of a simplified EMEP photochemistry !* scheme for urban areas (Walker et al. 2004) and a scheme for Secondary Organic Aerosol !* implemented by Håvard Slørdal !* !* Grønskei, K.E., Walker, S.E., Gram, F. (1993) Evaluation of a model for hourly spatial !* concentrations distributions. Atmos. Environ., 27B, 105-120. !* Larssen, S., Grønskei, K.E., Gram, F., Hagen, L.O., Walker, S.E. (1994) Verification of !* urban scale time-dependent dispersion model with sub-grid elements in Oslo, Norway. !* In: Air poll. modelling and its appl. X. New York, Plenum Press. !* Slørdal, L.H., McInnes, H., Krognes, T. (2008): The Air Quality Information System AirQUIS. !* Info. Techn. Environ. Eng., 1, 40-47, 2008. !* Slørdal, L.H., Walker, S.-E., Solberg, S. (2003) The Urban Air Dispersion Model EPISODE !* applied in AirQUIS. Technical Description. NILU TR 12/2003. ISBN 82-425-1522-0. !* Walker, S.E., Grønskei, K.E. (1992) Spredningsberegninger for on-line overvåking i Grenland. !* Programbeskrivelse og brukerveiledning. Lillestrøm, !* Norwegian Institute for Air Research (NILU OR 55/92). !* Walker, S.E., Slørdal, L.H., Guerreiro, C., Gram, F., Grønskei, K.E. (1999) Air pollution !* exposure monitoring and estimation. Part II. Model evaluation and population exposure. !* J. Environ. Monit, 1, 321-326. !* Walker, S.-E., Solberg, S., Denby, B. (2003) Development and implementation of a !* simplified EMEP photochemistry scheme for urban areas in EPISODE. NILU TR 13/2013. !* ISBN 82-425-1524-7 !*****************************************************************************! subroutine cwdeprate ! The subroutine calculates wet deposition rates assuming that ! wet deposition can be described by a first order ordinary ! differential equation of the type: dc/dt = - const * c. ! ---------------------------------------------------------------------------------- ! Based on: ! Version Episode 5.5 (May29, 2012) prepared for BB-Stand-Alone ! Original source code of EPISODE by Sam-Erik Walker (NILU) ! ! Sam-Erik Walker ! Norwegian Institute for Air Research (NILU) ! Instituttveien 18 P.O. Box 100 ! N-2027 Kjeller, NORWAY ! Tel: +47 63898000 Fax: +47 63898050 ! E-mail: [email protected] ! ! ---------------------------------------------------------------------------------- ! ---------------------------------------------------------------------------------- ! REVISION HISTORY ! ! 2016 M. Karl: Moved EXP4 into mod_util.f90 ! Allocation of WDEPRATE2D ! ! ---------------------------------------------------------------------------------- use mod_site use mod_mete use mod_conc use mod_depo implicit none ! External functions !MSK EXP4 is included in mod_util !MSK REAL EXP4 ! Local variables integer :: IC integer :: IX integer :: IY ! IC - Compound index ! IX - Grid model grid index in x-direction ! IY - Grid model grid index in y-direction real :: PRECV real :: CL_H real :: RHO_W real :: V_drop real :: A_MA_PA real :: E_C_EFF real :: C_FAC1,C_FAC2 !MSK start if (.not. allocated(WDEPRATE2D)) allocate (WDEPRATE2D(NC,NX,NY)) !MSK end ! PRECV - Precipitation value ! CL_H - Height of cloud base. For this version we set ! CL_H = MOD_H, i.e. the maximum model height. ! This is consistent with the way the wet deposition ! is included in the vertical turbulent flux routines: ! ADIV, V_DIF and DIFV_CN. ! ! Note that the variables below and their values are taken from ! page 64 in the Unified EMEP Model Description, Emep Report 1/2003. ! ! RHO_W - Density of rain water (1000 kg m^-3). ! V_drop - Raindrop fall speed (5 m/s). ! A_MA_PA - Empirical coefficient assuming a Marshall-Palmer size ! distribution for the rain drops (5.2 m^3 kg^-1 s^-1). ! E_C_EFF - The size dependent collection efficiency of ! aerosols by the raindrops (dimless) ! (= 0.1 for PM2.5 and = 0.4 for the coarse fraction, i.e. ! for PM10 - PM2.5). We apply 0.4 for PM10 here? Should ! probably be somewhere between 0.1 and 0.4 ????? ! C_FAC1 - Dummy factor. ! C_FAC2 - Dummy factor. ! RHO_W = 1000.0 V_drop = 5.0 A_MA_PA = 5.2 !_LHS_08_Oct_2004_Start: ! !_LHS The Wet-Deposition parameterizations below are only valid !_LHS as long as the height of the cloud is equal to the total !_LHS model height. If real (2-D) cloud base values are to be !_LHS included the parameterisations must be improved so that !_LHS wet deposition only affects the layers within or below !_LHS the raining clouds. CL_H = MOD_H !_LHS_08_Oct_2004_End. C_FAC1 = RHO_W * A_MA_PA / V_drop ! Go through all componds and compute the wet scavenging rate ! for particulates (Based on the EMEP Unified Model expression): DO IC = 1,NC IF(TRIM(CMPND(IC)) .EQ. 'PM10')THEN E_C_EFF = 0.4 C_FAC2 = C_FAC1 * E_C_EFF ELSEIF(TRIM(CMPND(IC)) .EQ. 'PM2.5')THEN E_C_EFF = 0.1 C_FAC2 = C_FAC1 * E_C_EFF ELSEIF(TRIM(CMPND(IC)) .EQ. 'EP')THEN E_C_EFF = 0.1 C_FAC2 = C_FAC1 * E_C_EFF ELSEIF(TRIM(CMPND(IC)) .EQ. 'TSP')THEN E_C_EFF = 0.4 C_FAC2 = C_FAC1 * E_C_EFF ELSE ! For Gaseous compounds the Scavenging ratio is given ! as a constant for each comound (NOTE: If CL_H values ! less than MOD_H are to be used the logic below must ! be changed. C_FAC2 = WDEPSR(IC) / CL_H ENDIF ! The C_FAC2 value above is now defined in such a way that ! the Wet-Deposition Rate, WDEPRATE2D(IC,IX,IY), emerge as ! the product of C_FAC2 and the precipitation, PRECV (in m/s). ! Thus: ! Go through all grid squares DO IY = 1,NY DO IX = 1,NX ! Convert precipitation from mm/h to m/s PRECV = PREC(IX,IY)/3.6E+6 ! Calculate wet deposition velocity (m/s): WDEPRATE2D(IC,IX,IY) = C_FAC2 * PRECV !MSK print *,'cwdeprate: ', WDEPRATE2D(IC,IX,IY) ! Next grid model grid square ENDDO ENDDO ! Next compound. ENDDO RETURN ! End of subroutine CWDEPRATE end subroutine cwdeprate
/* Internal header file for cminpack, by Frederic Devernay. */ #ifndef __CMINPACKP_H__ #define __CMINPACKP_H__ #ifndef __CMINPACK_H__ #error "cminpackP.h in an internal cminpack header, and must be included after all other headers (including cminpack.h)" #endif #if (defined (USE_CBLAS) || defined (USE_LAPACK)) && !defined (__cminpack_double__) && !defined (__cminpack_float__) #error "cminpack can use cblas and lapack only in double or single precision mode" #endif #ifdef USE_CBLAS #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #define __cminpack_enorm__(n,x) __cminpack_cblas__(nrm2)(n,x,1) #else #define __cminpack_enorm__(n,x) __cminpack_func__(enorm)(n,x) #endif #ifdef USE_LAPACK #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #if defined(__LP64__) /* In LP64 match sizes with the 32 bit ABI */ typedef int __CLPK_integer; typedef int __CLPK_logical; typedef __CLPK_logical (*__CLPK_L_fp)(); typedef int __CLPK_ftnlen; #else typedef long int __CLPK_integer; typedef long int __CLPK_logical; typedef __CLPK_logical (*__CLPK_L_fp)(); typedef long int __CLPK_ftnlen; #endif int __cminpack_lapack__(lartg_)( __cminpack_real__ *f, __cminpack_real__ *g, __cminpack_real__ *cs, __cminpack_real__ *sn, __cminpack_real__ *r__); int __cminpack_lapack__(geqp3_)( __CLPK_integer *m, __CLPK_integer *n, __cminpack_real__ *a, __CLPK_integer * lda, __CLPK_integer *jpvt, __cminpack_real__ *tau, __cminpack_real__ *work, __CLPK_integer *lwork, __CLPK_integer *info); int __cminpack_lapack__(geqrf_)( __CLPK_integer *m, __CLPK_integer *n, __cminpack_real__ *a, __CLPK_integer * lda, __cminpack_real__ *tau, __cminpack_real__ *work, __CLPK_integer *lwork, __CLPK_integer *info); #endif #endif #include "minpackP.h" #endif /* !__CMINPACKP_H__ */
import cv2 import numpy as np def func(x): pass if __name__ == '__main__': img = cv2.imread("1.png") cv2.namedWindow('image') cv2.createTrackbar('threshold 1','image', 0, 255, func) cv2.createTrackbar('threshold 2','image', 0, 255, func) switch = 'Canny 1 : ON\n0 : OFF' cv2.createTrackbar(switch, 'image', 0, 1, func) cv2.setTrackbarPos(switch,'image',1) while(1): # cv2.setTrackbarPos('R','image',128) threshold_1 = cv2.getTrackbarPos('threshold 1','image') threshold_2 = cv2.getTrackbarPos('threshold 2','image') # b = cv2.getTrackbarPos('B','image') s = cv2.getTrackbarPos(switch,'image') if s == 0: cv2.imshow('image', img) else: edges = cv2.Canny(img,threshold_1,threshold_2) cv2.imshow('image', edges) k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows()
module Dot import Graph.Core import Graph.API -- %default total data Kind = Undirected | Directed data Attribute : Type where Color : String -> Attribute Label : String -> Attribute data EdgeDef : (kind : Kind) -> Type where SimpleEdge : (target : String) -> (source : String) -> EdgeDef kind (::) : String -> EdgeDef kind -> EdgeDef kind data Statement : (kind : Kind) -> Type where Node : String -> List Attribute -> Statement kind Edge : EdgeDef kind -> List Attribute -> Statement kind record Dot (kind : Kind) where constructor MkDot strict : Bool id : Maybe String body : List (Statement kind) Show Kind where show Undirected = "graph" show Directed = "digraph" Show Attribute where show (Color col) = "color=" ++ col show (Label lab) = "label=" ++ lab edgeConnector : Kind -> String edgeConnector Undirected = "--" edgeConnector Directed = "->" Show (EdgeDef kind) where show (SimpleEdge target source) = unwords [source, edgeConnector kind, target] show (target :: def) = unwords [show def, edgeConnector kind, target] appendAttrs : List Attribute -> String -> String appendAttrs [] str = str appendAttrs attrs str = str ++ (" [" ++ tags ++ "]") where tags = unwords (map show attrs) Show (Statement kind) where show (Node node attrs) = appendAttrs attrs (node) show (Edge def attrs) = appendAttrs attrs (show def) showDeclaration : Dot kind -> String showDeclaration dot = unwords . putStrict . putKind . putId $ [] where putKind : List String -> List String putKind ws = (show kind) :: ws putId : List String -> List String putId ws = case id dot of Nothing => ws Just identifier => identifier :: ws putStrict : List String -> List String putStrict ws = if strict dot then "strict" :: ws else ws showBody : Dot kind -> String showBody dot = unlines (map show (body dot)) Show (Dot kind) where show dot = showDeclaration dot ++ " {\n" ++ showBody dot ++ "\n}" test : Dot Directed test = MkDot True (Just "yo") [ Node "a" [], Node "b" [], Edge (SimpleEdge "a" "b") [] ] fromGraph : (Show a, Show b) => Graph a b -> Dot Directed fromGraph graph = MkDot False Nothing (nodes ++ edges) where nodes : List (Statement Directed) nodes = map (\(id, l) => Node (show id) [Label (show l)]) (labNodes graph) edges : List (Statement Directed) edges = map f (labEdges graph) where f : Show b => (Int, Int, b) -> Statement Directed f (source, target, l) = Edge (SimpleEdge (show target) (show source)) [Label (show l)] export graphToDot : (Show a, Show b) => Graph a b -> String graphToDot = show . fromGraph
using Test using Permutations @testset "Permutation" begin p = Permutation(7:-1:1) i = Permutation(7) @test p * p == i @test p == inv(p) a = [2, 3, 1, 6, 7, 8, 5, 4, 9] p = Permutation(a) @test order(p) == 6 @test p^6 == Permutation(9) @test p^-5 == p @test p.data == a q = Permutation([1, 5, 3, 9, 4, 8, 6, 7, 2]) @test p * q != q * p @test q[2] == 5 @test q(2) == 5 P = Matrix(p) Q = Matrix(q) @test P * Q == Matrix(p * q) @test P' == Matrix(inv(p)) row = [1, 3, 5, 2, 4, 6] p = Permutation(row) @test length(p) == 6 @test p[1] == 1 @test length(longest_increasing(p)) == 4 @test length(longest_decreasing(p)) == 2 @test length(fixed_points(p)) == 2 @test sign(p) == -1 @test hash(p) == hash(p.data) M = two_row(p) @test M[2, :] == row @test Permutation(6, 1) == Permutation(6) p = RandomPermutation(10) @test p * inv(p) == Permutation(10) @test p' * p == Permutation(10) @test reverse(reverse(p)) == p a, b, c, d = Permutation([2, 1, 3, 4]), Permutation([1, 2, 4, 3]), Permutation([1, 3, 2, 4]), Permutation([2, 1, 3, 4]) @test Matrix(a * b * c * d) == Matrix(a) * Matrix(b) * Matrix(c) * Matrix(d) p = RandomPermutation(12) d = dict(p) for k = 1:12 @test p(k) == d[k] end p = RandomPermutation(12) pp = p * p q = sqrt(pp) @test q * q == pp end @testset "Cycles" begin p = Permutation(10) @test length(cycles(p)) == 10 p = Permutation([2, 3, 4, 5, 1]) @test length(cycles(p)) == 1 for i = 1:10 p = RandomPermutation(20) cp = cycles(p) @test Permutation(cp) == p end end @testset "Transposition function" begin p = Transposition(10, 3, 6) @test p == inv(p) end @testset "Matrix conversion" begin p = RandomPermutation(10) M = Matrix(p) q = Permutation(M) @test p == q end @testset "CoxeterDecomposition" begin n = 10 p = RandomPermutation(n) c = CoxeterDecomposition(p) @test p == Permutation(c) @test inv(c) * c == CoxeterDecomposition(n, Int[]) @test inv(c) == c' @test CoxeterDecomposition(5, [3, 4, 1]) == CoxeterDecomposition(5, [1, 3, 4]) @test CoxeterDecomposition(5, [2, 1, 3, 4, 1]) == CoxeterDecomposition(5, [2, 3, 4]) @test CoxeterDecomposition(5, [1, 3, 4, 3, 4, 3, 4, 1]) == CoxeterDecomposition(5, Int[]) @test Permutation(CoxeterDecomposition(5, Int[])).data ≈ 1:5 @test Permutation(CoxeterDecomposition(5, [1])).data == [2; 1; 3:5] @test inv(CoxeterDecomposition(6, [1, 3, 5])) == CoxeterDecomposition(6, [1, 3, 5]) @test CoxeterDecomposition(RandomPermutation(100)) isa CoxeterDecomposition # check for stack overflow end @testset "PermGen" begin X = PermGen(4) @test length(X) == factorial(4) d = [[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]] X = PermGen(d) @test sum(length(fixed_points(p)) for p in X) == 0 X = DerangeGen(5) @test length(collect(X)) == 44 end
Letterpress Printing in Canada Eh! While we're updating our site, please check out our Flickr page for lots of Letterpress Inspiration! FYI : We take privacy seriously and will never sell client information and please don't copy our stuff-that's rude.
#include <algorithm> #include <vector> #include <fstream> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Surface_mesh.h> #include <CGAL/box_intersection_d.h> #include <CGAL/Timer.h> #include <boost/bind.hpp> #include <boost/functional/value_factory.hpp> #include <boost/range/algorithm/transform.hpp> #include <algorithm> #include <vector> #include <fstream> typedef CGAL::Exact_predicates_exact_constructions_kernel K; typedef K::Triangle_3 Triangle_3; typedef K::Point_3 Point_3; typedef CGAL::Surface_mesh<K::Point_3> Mesh; typedef CGAL::Bbox_3 Bbox_3; typedef CGAL::Timer Timer; typedef Mesh::Face_index Face_descriptor; typedef Mesh::Halfedge_index Halfedge_descriptor; /// small helper to extract a triangle from a face Triangle_3 triangle(const Mesh& sm, Face_descriptor f) { Halfedge_descriptor hf = sm.halfedge(f); Point_3 a = sm.point(sm.target(hf)); hf = sm.next(hf); Point_3 b = sm.point(sm.target(hf)); hf = sm.next(hf); Point_3 c = sm.point(sm.target(hf)); hf = sm.next(hf); return Triangle_3(a, b, c); } class Box : public CGAL::Box_intersection_d::Box_d<double, 3, CGAL::Box_intersection_d::ID_NONE> { private: typedef CGAL::Box_intersection_d::Box_d< double, 3, CGAL::Box_intersection_d::ID_NONE> Base; Face_descriptor fd; public: typedef double NT; typedef std::size_t ID; Box(Face_descriptor f, const Mesh& sm) : Base(triangle(sm, f).bbox()), fd(f) {} Box(const Bbox_3& b, Face_descriptor fd) : Base(b), fd(fd) {} Face_descriptor f() const { return fd; } ID id() const { return static_cast<ID>(fd); } }; struct Callback { Callback(const Mesh& P, const Mesh& Q, unsigned int& i) : P(P), Q(Q), count(i) {} void operator()(const Box* bp, const Box* bq) { Face_descriptor fp = bp->f(); Triangle_3 tp = triangle(P, fp); Face_descriptor fq = bq->f(); Triangle_3 tq = triangle(Q, fq); if(do_intersect( tp, tq)) { ++(count); } } const Mesh& P; const Mesh& Q; unsigned int& count; }; const Box* address_of_box(const Box& b) { return &b; } unsigned int intersect(const Mesh& P, const Mesh& Q) { std::vector<Box> P_boxes, Q_boxes; std::vector<const Box*> P_box_ptr, Q_box_ptr; P_boxes.reserve(P.number_of_faces()); P_box_ptr.reserve(P.number_of_faces()); Q_boxes.reserve(Q.number_of_faces()); Q_box_ptr.reserve(Q.number_of_faces()); // build boxes and pointers to boxes for(auto f : P.faces()) P_boxes.push_back( Box(f, P) ); std::transform(P_boxes.begin(), P_boxes.end(), std::back_inserter(P_box_ptr), &address_of_box); for(auto f : Q.faces()) Q_boxes.push_back( Box(f, Q) ); std::transform(Q_boxes.begin(), Q_boxes.end(), std::back_inserter(Q_box_ptr), &address_of_box); unsigned int i = 0; Callback c(P,Q, i); CGAL::box_intersection_d(P_box_ptr.begin(), P_box_ptr.end(), Q_box_ptr.begin(), Q_box_ptr.end(), c); return i; } int main(int argc, char* argv[]) { if(argc < 3) { std::cerr << "Usage: do_intersect <mesh_1.off> <mesh_2.off>" << std::endl; return EXIT_FAILURE; } std::cout.precision(17); Mesh P, Q; if(!CGAL::read_polygon_mesh(argv[1], P) || !CGAL::read_polygon_mesh(argv[2], Q)) { std::cerr << "Invalid input files." << std::endl; return EXIT_FAILURE; } Timer timer; timer.start(); unsigned int num_intersections = intersect(P,Q); timer.stop(); std::cout << "Counted " << num_intersections << " in " << timer.time() << " seconds." << std::endl; return 0; }
ABOVE: A vintage cabriolet on a corniche road in Luxembourg. INSET BELOW: Minicars in Montmarte, Parisian parking. Car travel in Europe can be a joy or a nightmare, depending on where and when you drive. During August, when countless millions of Europeans pack up their family cars and drive to the beaches or mountains, traffic jams can rob even the most scenic European touring routes of their charm. And at any time of year, driving in a major city like London, Paris, or Rome can be nerve-wracking (or at least unpleasant) to the foreign tourist. Spring and fall are the best times for a motoring vacation in Northern and Central Europe. In Southern Europe, winter can also be pleasant if you avoid the Christmas break. If your vacation is tied to the school calendar, try visiting in June, before the summer season reaches its peak. Many tourists, especially those from North America, make the mistake of planning car itineraries built around Europe's largest cities. They end up having to cope with nerve-wracking traffic, scarce parking, and unfamiliar regulations--all while trying to catch a glimpse of the sights through a mass of cars, motorscooters, bikes, and tour buses. Take the train between major cities. Rent cars for local or regional excursions, or for legs of your trip (e.g., Paris to the Riviera) where you want to stop and enjoy sights along the way. Visit a country like Denmark, Norway, or Sweden where even the largest cities are relatively car-friendly and you can leave town for driving excursions with a minimum of hassle. ABOVE: The Peugeot Traveller van on a European highway. Residents of countries outside the U.S. can save money with short-term tourist leases from Peugeot. Comparison shop. Check prices at European brokers that specialize in leisure rentals and short-term leasing programs. Check each company's age restrictions if you're under 25 or over 65, and see "Lease for longer trips" below. Plan carefully. Rent a car for only as long as you'll need it, to avoid early-return penalties. If you're on a budget, avoid drop-off charges by planning a circular itinerary. Book ahead. If you live outside Europe, you're likely to get a better deal by making arrangements from abroad. Lease for longer trips. A short-term car lease can save money on rentals of 21 days or more. Such "buy back" or "purchase-repurchase" leases are especially useful for students and senior citizens, since age restrictions are minimal. Buy a pass. A Rail 'n Drive Pass combines the speed and comfort of train travel with the convenience of a vehicle for local excursions. Think small. Fuel is expensive in Europe, streets are narrow in many cities, and small cars are easier to park than large ones. Unless you need a large car or van, stick with a small to midsize car. Important note: If you're picking up a car outside the European Union, you may encounter bureaucratic hassles if you later decide to drop the car off in an EU country. To avoid potential problems, ask for a car that's regisftered in the EU if you plan to drive there. Prepare at home. European regulations, driving customs, and road signs can be confusing to foreigners, so use the information resources below to learn the basics ahead of time. Be alert. If you're from North America, forget about turning on the cruise control and floating along in the left lane while listening to Santana and slurping coffee from your MegaMug. You could have a panic attack when a BMW comes tearing up behind you, left flasher blinking, at 250 km/h (156 mph) or faster. And if you've never had to enter or exit a traffic circle (a.k.a. rotary or roundabout) in heavy traffic, get ready for a new experience--especially if local laws give priority to traffic coming from the right. Carry an International Driving Permit. This passport-like document (sometimes called an International Driver's License) is a translation of your home license. It's required in some countries and optional in others, but it's well worth having to avoid problems if you're stopped by the police or want to rent a car in a foreign country. See our International Driving Permit article. ABOVE: The Peugeot Partner is a popular crossover vehicle in Europe. Do you need liability insurance in Europe? Should you pay extra for a Collision Damage Waiver, or can you rely on your credit card's free coverage? This Europe for Visitors article has the answers. The interface may be more confusing than a Parisian roundabout, but be patient--and scroll down for links to pages on traffic signs. Icarehireinsurance has put together an infographic that shows parking signs and markings. The page also discusses parking laws and etiquette in several Western European countries. Brian Lucas describes his informative and entertaining article as "an attempt to list which side of the road people drive on around the world, and to find some reasons why." ABOVE: A classic Mercedes 300SL gullwing sports car outside the Mercedes-Benz Museum in Stuttgart, Germany. Jeff Steiner, an American resident of Strasbourg, wrote these pages for Americans in France. Read our articles about car museums and factory tours, a high-speed "race taxi," a self-drive "Trabi Safari" tour in Dresden or Berlin, and more. If you can't read the German text, try The Autobahn, from Brian's Guide to Getting Around Germany, and Hyde Flippo's Autobahn articles from The German Way and More. See what facilities are available at the 338 gas stations, 382 service areas, and 51 hotels on Germany's Autobahn network. DeTraci Regula's article is at Tripsavvy.com. Use the journey planner to design an itinerary or check traffic conditions at the official Italian motorway site, where you'll also find a handful of articles in English. Joseph F. Lomax wrote this article for InItaly.com. Learn basic rules, regulations, and other facts from Portugal-info.net. Most of this advice from Andalucia.com is applicable to Spain as a whole. This article is from our Switzerland for Visitors subsite. The country's national tourist office tells everything you need to know before hitting the road in Britain. ABOVE: You can drive a VW Touareg on the off-road course at Volkswagen's Autostadt in Wolfsburg, Germany. Use the "Driving Directions" form to plan your trip, or request an online map from the ViaMichelin database. Renault has been in the tourist car-lease business since 1954. It offers a full range of vehicles, from subcompacts like the Dacia and Clio to the Espace 7-seat luxury crossover and the Trafic 9-seat van. GPS is standard on all models. Peugeot is represented by our partner, Auto Europe. Peugeot's car models range from econocars to luxury sedans, vans, and the Peugeot Partner, which squeezes a lot of interior space into a boxy SUV-like body. Rent a car in any of 4,000+ locations, with guaranteed low rates for equivalent cars.
<a href="https://colab.research.google.com/github/Astraplas/LinearAlgebra_2ndSem/blob/main/Assignment_5.ipynb" target="_parent"></a> # Linear Algebra for CHE ## Laboratory 6 : Matrix Operations Now that you have a fundamental knowledge about representing and operating with vectors as well as the fundamentals of matrices, we'll try to the same operations with matrices and even more. ## Objectives At the end of this activity you will be able to: 1. Be familiar with the fundamental matrix operations. 2. Apply the operations to solve intemrediate equations. 3. Apply matrix algebra in engineering solutions. # Discussion The codes below will serve as the foundation to be used in the matrix operation codes to be created. ```python import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` # Transposition One of the fundamental operations in matrix algebra is Transposition. The transpose of a matrix is done by flipping the values of its elements over its diagonals. With this, the rows and columns from the original matrix will be switched. So for a matrix $A$ its transpose is denoted as $A^T$. So for example: :$$ A=\begin{bmatrix} 1 & 2 & 5 \\ 5 & -1 & 0 \\ 0 & -3 & 3\end{bmatrix} \\ A^T=\begin{bmatrix} 1 & 5 & 0\\ 2 & -1 & -3\\ 5 & 0 & 3\end{bmatrix} $$ his can now be achieved programmatically by using np.transpose() or using the T method. ```python A = np.array([ [1 ,2, 5], [5, -1, 0], [0, -3, 3] ]) A ``` array([[ 1, 2, 5], [ 5, -1, 0], [ 0, -3, 3]]) ```python AT1 = np.transpose(A) AT1 ``` array([[ 1, 5, 0], [ 2, -1, -3], [ 5, 0, 3]]) ```python AT2 = A.T ``` ```python np.array_equiv(AT1, AT2) ``` True ```python B = np.array([ [40,13,55,32], [32,12,64,21], ]) B.shape ``` (2, 4) ```python np.transpose(B).shape ``` (4, 2) ```python B.T.shape ``` (4, 2) The codes mentioned above have simply interconverted the rows and columns of the given matrices ##### Try to create your own matrix (you can try non-squares) to test transposition. ```python ``` ## Dot Product / Inner Product If you recall the dot product from laboratory activity before, we will try to implement the same operation with matrices. In matrix dot product we are going to get the sum of products of the vectors by row-column pairs. So if we have two matrices $X$ and $Y$: $$X=\begin{bmatrix} x_{(0,0)}& x_{(0,1)}\\ x_{(1,0)}& x_{(1,1)}\\ \end{bmatrix} , Y=\begin{bmatrix} y_{(0,0)}& y_{(0,1)}\\ y_{(1,0)}& y_{(1,1)}\\ \end{bmatrix} $$ The dot product will then be computed as: $$X=\begin{bmatrix} x_{(0,0)}*y_{(0,0)} + x_{(0,1)}*y_{(1,0)} & x_{(0,0)}*y_{(0,1)} + x_{(0,1)}*y_{(1,1)}\\ x_{(1,0)}*y_{(0,0)} + x_{(1,1)}*y_{(1,0)} & x_{(1,0)}*y_{(0,1)} + x_{(1,1)}*y_{(1,1)}\\ \end{bmatrix} $$ So if we assign values to $X$ and $Y$: :$$ X=\begin{bmatrix} 1 & 2\\ 0 & 1\end{bmatrix} , Y=\begin{bmatrix} -1 & 0\\ 2 & 2\end{bmatrix} $$ :$$ X⋅Y=\begin{bmatrix} 1*-1 + 2*2 & 1*0 + 2*2\\ 0*-1 + 1*2 & 0*0 + 1*2\end{bmatrix} = \begin{bmatrix} 3 & 4\\ 2 & 2\end{bmatrix} $$ This could be achieved programmatically using np.dot(), np.matmul() or the @ operator. ```python X = np.array([ [3,4,6], [1,6,7], [6,3,0] ]) Y = np.array([ [4,-2,5], [5,7,-4], [5,1,-8] ]) ``` ```python np.dot(X,Y) ``` array([[ 62, 28, -49], [ 69, 47, -75], [ 39, 9, 18]]) ```python X.dot(Y) ``` array([[ 62, 28, -49], [ 69, 47, -75], [ 39, 9, 18]]) ```python X @ Y ``` array([[ 62, 28, -49], [ 69, 47, -75], [ 39, 9, 18]]) ```python np.matmul(X,Y) ``` array([[ 62, 28, -49], [ 69, 47, -75], [ 39, 9, 18]]) In matrix dot products there are additional rules compared with vector dot products. Since vector dot products were just in one dimension there are less restrictions. Since now we are dealing with Rank 2 vectors we need to consider some rules: ## Rule 1: The inner dimensions of the two matrices in question must be the same. So given a matrix $A$ with a shape of $(a,b)$ where $a$ and $b$ are any integers. If we want to do a dot product between $A$ and $B$ another matrix , then matrix $B$ should have a shape of $(b,c)$ where $b$ and $c$ are any integers. So for given the following matrices: $$ Q=\begin{bmatrix} 5 & 5 & 5\\ 6 & 7 & -2\end{bmatrix}, R=\begin{bmatrix} 4 & 5 & 6\\ 9 & 0 & 1\end{bmatrix}, S=\begin{bmatrix} 1 & 6\\ 3 & 2\\ 4 & 6\end{bmatrix} $$ So in this case $A$ has a shape of $(3,2)$, $B$ has a shape of $(3,2)$ and $C$ has a shape of $(2,3)$ . So the only matrix pairs that is eligible to perform dot product is matrices $A⋅C$ or $B⋅C$. ```python Q = np.array([ [5, 5, 5], [6, 7, -2] ]) R = np.array([ [4,5,6], [9,0,1] ]) S = np.array([ [1,6], [3,2], [4,6] ]) print(Q.shape) print(R.shape) print(S.shape) ``` (2, 3) (2, 3) (3, 2) ```python Q @ S ``` array([[40, 70], [19, 38]]) ```python R @ S ``` array([[43, 70], [13, 60]]) If you would notice the shape of the dot product changed and its shape is not the same as any of the matrices we used. The shape of a dot product is actually derived from the shapes of the matrices used. So recall matrix $A$ with a shape of $(a,b)$ and matrix $B$ with a shape of $(b,c)$, $A⋅B$ should have a shape $(a,c)$. ```python Q @ R.T ``` array([[75, 50], [47, 52]]) ```python X = np.array([ [1,2,3,0] ]) Y = np.array([ [1,0,4,-1] ]) print(X.shape) print(Y.shape) ``` (1, 4) (1, 4) ```python R.T @ Q ``` array([[74, 83, 2], [25, 25, 25], [36, 37, 28]]) And you can see that when you try to multiply A and B, it returns ValueError pertaining to matrix shape mismatch. ## Rule 2: Dot Product has special properties Dot products are prevalent in matrix algebra, this implies that it has several unique properties and it should be considered when formulation solutions: 1. $A \cdot B \neq B \cdot A$ 2. $A \cdot (B \cdot C) = (A \cdot B) \cdot C$ 3. $A\cdot(B+C) = A\cdot B + A\cdot C$ 4. $(B+C)\cdot A = B\cdot A + C\cdot A$ 5. $A\cdot I = A$ 6. $A\cdot \emptyset = \emptyset$ I'll be doing just one of the properties and I'll leave the rest to test your skills! ```python H = np.array([ [5,6,11], [7,4,10], [8,7,0] ]) I = np.array([ [7,18,26], [44,31,0], [5,5,6] ]) J = np.array([ [3,0,1], [6,0,2], [7,8,8] ]) ``` ```python H.dot(np.zeros(H.shape)) ``` array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) ```python l_mat = np.zeros(H.shape) l_mat ``` array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) ```python r_dot_l = H.dot(np.zeros(H.shape)) r_dot_l ``` array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) ```python np.array_equal(r_dot_l,l_mat) ``` True ```python null_mat = np.empty(H.shape, dtype=float) null = np.array(null_mat,dtype=float) print(null) np.allclose(r_dot_l,null) ``` [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] True ```python K = H.dot(I) L = I.dot(H) print(K) print(L) row1 = len(K); col1 = len(K[0]); row2 = len(L); col2 = len(L[0]); if(row1 != row2 or col1 != col2): print("Matrices are not equal"); else: for i in range(0, row1): for j in range(0, col1): if(K[i][j] != L[i][j]): flag = False; break; if(flag): print("Matrices are equal"); else: print("Matrices are not equal. Therefore A⋅B ≠ B⋅A"); ``` [[354 331 196] [275 300 242] [364 361 208]] [[369 296 257] [437 388 794] [108 92 105]] Matrices are not equal. Therefore A⋅B ≠ B⋅A ```python v = print(H*(I*J)) w = print((H*I)*J) if v == w: print("Thus, A⋅(B⋅C)=(A⋅B)⋅C") ``` [[ 105 0 286] [1848 0 0] [ 280 280 0]] [[ 105 0 286] [1848 0 0] [ 280 280 0]] Thus, A⋅(B⋅C)=(A⋅B)⋅C ```python a = print(H*(I+J)) b = print(H*I+H*J) if a == b: print("Thus, A⋅(B+C)=A⋅B+A⋅C") ``` [[ 50 108 297] [350 124 20] [ 96 91 0]] [[ 50 108 297] [350 124 20] [ 96 91 0]] Thus, A⋅(B+C)=A⋅B+A⋅C ```python c = print((I+J)*H) d= print(I*H+J*H) if c == d: print("Thus, (B+C)⋅A=B⋅A+C⋅A") ``` [[ 50 108 297] [350 124 20] [ 96 91 0]] [[ 50 108 297] [350 124 20] [ 96 91 0]] Thus, (B+C)⋅A=B⋅A+C⋅A ```python H.dot(1) ``` array([[ 5, 6, 11], [ 7, 4, 10], [ 8, 7, 0]]) ```python H.dot(0) ``` array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) The codes mentioned above proves that the rule established for the special properties of the dot products are true. ## Determinant A determinant is a scalar value derived from a square matrix. The determinant is a fundamental and important value used in matrix algebra. Although it will not be evident in this laboratory on how it can be used practically, but it will be reatly used in future lessons. The determinant of some matrix $A$ is denoted as $det(A)$ or $|A|$. So let's say $A$ is represented as: $$A=\begin{bmatrix} a_{(0,0)}& a_{(0,1)}\\ a_{(1,0)}& a_{(1,1)}\\ \end{bmatrix} $$ We can compute for the determinant as: $$ |A| = a_{(0,0)} * a_{(1,1)} - a_{(1,0)} * a_{(0,1)} $$ So if we have $A$ as: $$A=\begin{bmatrix} 1 & 4\\ 0 & 3\\ \end{bmatrix}, |A| = 3 $$ But you might wonder how about square matrices beyond the shape ? We can approach this problem by using several methods such as co-factor expansion and the minors method. This can be taught in the lecture of the laboratory but we can achieve the strenuous computation of high-dimensional matrices programmatically using Python. We can achieve this by using np.linalg.det(). ```python ``` ```python A = np.array([ [58,32], [71,36] ]) np.linalg.det(A) ``` -184.00000000000006 ```python ## Now other mathematics classes would require you to solve this by hand, ## and that is great for practicing your memorization and coordination skills ## but in this class we aim for simplicity and speed so we'll use programming ## but it's completely fine if you want to try to solve this one by hand. B = np.array([ [54,321,53], [90,13,10], [34,192,81] ]) np.linalg.det(B) ``` -1385353.9999999995 ## Inverse The inverse of a matrix is another fundamental operation in matrix algebra. Determining the inverse of a matrix let us determine if its solvability and its characteristic as a system of linear equation — we'll expand on this in the nect module. Another use of the inverse matrix is solving the problem of divisibility between matrices. Although element-wise division exists but dividing the entire concept of matrices does not exists. Inverse matrices provides a related operation that could have the same concept of "dividing" matrices. Now to determine the inverse of a matrix we need to perform several steps. So let's say we have a matrix $M$: $$A=\begin{bmatrix} 1 & 7\\ -3 & 5\\ \end{bmatrix}, |A| = 3 $$ First, we need to get the determinant of $M$. $$ |M| = (1)(5) - (-3)(7) = 26 $$ Next, we need to reform the matrix into the inverse form $$ M^{-1} = \begin{align} \frac{1}{|M|} \end{align} \begin{bmatrix} m_{(1,1)}& -m_{(0,1)}\\ -m_{(1,0)}& m_{(0,0)}\\ \end{bmatrix} $$ So that will be: $$M^{-1} = \frac{1}{26} \begin{bmatrix} 5 & -7 \\ 3 & 1\end{bmatrix} = \begin{bmatrix} \frac{5}{26} & \frac{-7}{26} \\ \frac{3}{26} & \frac{1}{26}\end{bmatrix}$$ For higher-dimension matrices you might need to use co-factors, minors, adjugates, and other reduction techinques. To solve this programmatially we can use np.linalg.inv(). ```python M = np.array([ [17,57], [23, 45] ]) np.array(M @ np.linalg.inv(M), dtype=int) ``` array([[0, 0], [0, 0]]) ```python ## And now let's test your skills in solving a matrix with high dimensions: N = np.array([ [12,45,423,121,10,533,553], [560,255,34,513,524,242,23], [55,49,220,235,205,10,356], [61,56,24,24,38,443,15], [86,426,283,724,12,624,241], [-5,-165,222,230,-310,356,330], [224,521,132,246,146,-225,132], ]) N_inv = np.linalg.inv(N) np.array(N @ N_inv,dtype=int) ``` array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]]) To validate the wether if the matric that you have solved is really the inverse, we follow this dot product property for a matrix $M$: $$ M⋅M^{-1} = I $$ ```python squad = np.array([ [1.0, 1.0, 0.5], [0.7, 0.7, 0.9], [0.3, 0.3, 1.0] ]) weights = np.array([ [0.2, 0.2, 0.6] ]) p_grade = squad @ weights.T p_grade ``` array([[0.7 ], [0.82], [0.72]]) ## Activity ### Task 1 Prove and implement the remaining 6 matrix multiplication properties. You may create your own matrices in which their shapes should not be lower than $(3,3)$. In your methodology, create individual flowcharts for each property and discuss the property you would then present your proofs or validity of your implementation in the results section by comparing your result to present functions from NumPy. ## Conclusion For your conclusion synthesize the concept and application of the laboratory. Briefly discuss what you have learned and achieved in this activity. Also answer the question: "how can matrix operations solve problems in healthcare?". Conclusion in the Lab report: In light of the learnings that the students were able to obtain, it could also be applied to several fields. One of which is that the matrix operation could be used through the healthcare system. In the healthcare system, there is a field that is specialized in treating certain eye illnesses. In this particular field, the use of optics would be prevalent in order to execute a certain diagnosis. With the help of matrices, calculating the reflection and refraction of a certain light would be comparatively easy compared to calculating it through the manual method. Furthermore, it could also be applied when dealing with certain bills that are needed to be paid for healthcare. In here, rectangular arrays of matrices are used by a certain program that would flexibly conduct the calculations quickly and efficiently. With all of this in mind, it is irrefutable that matrix does indeed ease the burden when it comes to solving problems in healthcare. As such, exploring the applications and possibilities of matrices is imperative in order to nurture a better living.
#!/usr/bin/env python """ This file is part of the package FUNtoFEM for coupled aeroelastic simulation and design optimization. Copyright (C) 2015 Georgia Tech Research Corporation. Additional copyright (C) 2015 Kevin Jacobson, Jan Kiviaho and Graeme Kennedy. All rights reserved. FUNtoFEM is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ """ Demonstration of model set up for TOGW minimization """ import numpy as np from pyfuntofem.model import * crm_model = FUNtoFEMmodel('crm wing') # Set up the scenarios # cruise cruise = Scenario(name='cruise', group=0,steady=True,fun3d=True) cruise.set_variable('aerodynamic','AOA',value=3.0,lower=-3.0,upper=10.0,active=True) lift = Function('cl',analysis_type='aerodynamic') cruise.add_function(lift) drag = Function('cd',analysis_type='aerodynamic') cruise.add_function(drag) mass = Function('mass',analysis_type='structural',adjoint=False) cruise.add_function(mass) crm_model.add_scenario(cruise) # maneuver maneuver = Scenario(name='maneuver', group=1,steady=False,fun3d=True, steps =400) maneuver.set_variable('aerodynamic','AOA',value=5.0,lower=-3.0,upper=10.0,active=True) lift = Function('cl',analysis_type='aerodynamic',start = 100, stop =400, averaging = True) maneuver.add_function(lift) options = {'ksweight':50.0} ks = Function('ksFailure',analysis_type='structural',options=options,averaging = False) maneuver.add_function(ks) crm_model.add_scenario(maneuver) # Set up the body wing = Body('wing','aeroelastic',group=1,fun3d=True) # Add the thickness variables thicknesses = np.loadtxt('thicknesses.dat') for i in range(thicknesses.size): thick = Variable('thickness '+str(i), value=thicknesses[i], lower = 0.003, upper = 0.05, coupled = True if i % 2 == 0 else False) wing.add_variable('structural',thick) # Add the shape variables shapes = np.loadtxt('shape_vars.dat') for i in range(shapes.shape[0]): shpe = Variable('shape '+str(i), value=shapes[i,0], lower = shapes[i,1], upper = shapes[i,2]) wing.add_variable('shape',shpe) crm_model.add_body(wing) wing2 = Body('wing 2','aeroelastic',group=1,fun3d=True) for i in range(thicknesses.size): thick = Variable('thickness '+str(i), value=thicknesses[i]*4.0, lower = 0.003, upper = 0.05, coupled = True if i % 2 == 0 else False) wing2.add_variable('structural',thick) crm_model.add_body(wing2) crm_model.print_summary()
(* Title: HOL/Auth/n_germanSymIndex_lemma_on_inv__1.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_germanSymIndex Protocol Case Study*} theory n_germanSymIndex_lemma_on_inv__1 imports n_germanSymIndex_base begin section{*All lemmas on causal relation between inv__1 and some rule r*} lemma n_SendInvAckVsinv__1: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" 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__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv0)" 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__Inv0\<and>i~=p__Inv2)" 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__1: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" 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__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" 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__Inv0)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Cache'') p__Inv2) ''State'')) (Const E)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv0) ''Cmd'')) (Const GntS))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" 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__1: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" 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__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Para (Ident ''Cache'') p__Inv0) ''State'')) (Const I))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const GntE))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Para (Ident ''Cache'') p__Inv2) ''State'')) (Const I))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv0) ''Cmd'')) (Const GntE))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" 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_SendReqE__part__1Vsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__1: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvInvAckVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendGntSVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendGntS i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqEVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE N i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendInv__part__0Vsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqE__part__0Vsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendInv__part__1Vsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendGntEVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendGntE N i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvReqSVsinv__1: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__1 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
rm(list=ls()) library(plyr) library(dplyr) library(ggplot2) library(tidyr) library(ggpubr) library(readxl) library(stats) library(tibble) library(reshape) library(xlsx) setwd("/Users/ChatNoir/Projects/Squam/Graphs/") # Read in data dfmid <- read_excel("/Users/chatnoir/Projects/Squam/Graphs/Tables/CombinedSchmoosh_2021.xlsx") df <- dfmid %>% mutate(Sample = sub('quant', '', Sample)) mdf <- data.frame(Sample=character(0),Hypothesis=character(),corr.eff=numeric(0),pRand=numeric(0)) load("/Users/chatnoir/Projects/Squam/scripts_ch1/Graphing/DataFiles/corsubsample") results <- results %>% filter(Sample != "all") # Remove non subsampled values mid <- df %>% filter(Sample != "all") hyps <- c('TvS','AIvSA', 'AIvSI','SAvSI') subs <- c('80m','60m','80mb','60mb') l1 <- 2000 l2 <- 2000 for (h in hyps) { for (s in subs){ if (h == 'TvS'){ l <- l1 }else{ l <- l2} n <- results %>% filter(Hypothesis == h) %>% filter(Loci == l) m <- mid %>% filter(Hypothesis == h) %>% filter(Sample == s) e <- m$corr.eff p.s <- sum(abs(n$corr.eff) >= abs(e)) / length(n$corr.eff) a <- data.frame(Sample=s,Hypothesis=h,corr.eff=e,pRand=p.s) mdf <- rbind(mdf,a) } } #------------------------------------------------------------------------------------------------------------------------------------------------------ # Save ---------------------------------------------- Save -------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------------------------------------------------ library(xlsx) fname <- paste("/Users/ChatNoir/Projects/Squam/Graphs/Tables/Combined_corr_rand_pvals_mmb_2021.xlsx",sep='') write.xlsx2(as.data.frame(mdf), file=fname, row.names=FALSE)
If two sequences are eventually equal, then they converge or diverge together.
------------------------------------------------------------------------------ -- A Peano arithmetic proof without using a where clause ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module LogicalFramework.CommAddition where open import Common.FOL.Relation.Binary.EqReasoning open import PA.Axiomatic.Standard.Base ------------------------------------------------------------------------------ postulate +-rightIdentity : ∀ n → n + zero ≡ n x+Sy≡S[x+y] : ∀ m n → m + succ n ≡ succ (m + n) succCong : ∀ {m n} → m ≡ n → succ m ≡ succ n +-leftIdentity : ∀ n → zero + n ≡ n +-leftIdentity = PA₃ A : ℕ → Set A m = ∀ n → m + n ≡ n + m A0 : A zero A0 n = zero + n ≡⟨ +-leftIdentity n ⟩ n ≡⟨ sym (+-rightIdentity n) ⟩ n + zero ∎ is : ∀ m → A m → A (succ m) is m ih n = succ m + n ≡⟨ PA₄ m n ⟩ succ (m + n) ≡⟨ succCong (ih n) ⟩ succ (n + m) ≡⟨ sym (x+Sy≡S[x+y] n m) ⟩ n + succ m ∎ +-comm : ∀ m n → m + n ≡ n + m +-comm = ℕ-ind A A0 is
class category (C : Type) := ( hom : C → C → Type ) ( id : (X : C) → hom X X ) ( comp : {X Y Z : C} → hom X Y → hom Y Z → hom X Z ) ( id_comp {X Y : C} (f : hom X Y) : comp (id X) f = f ) ( comp_id {X Y : C} (f : hom X Y) : comp f (id Y) = f ) ( assoc {W X Y Z : C} (f : hom W X) (g : hom X Y) (h : hom Y Z) : comp (comp f g) h = comp f (comp g h) ) notation " 𝟙 " => category.id infixr: 80 " ≫ " => category.comp infixr: 10 " ⟶ " => category.hom variable (C : Type) [category C] inductive prod_coprod : Type | of_cat' : C → prod_coprod | init : prod_coprod | prod : prod_coprod → prod_coprod → prod_coprod | coprod : prod_coprod → prod_coprod → prod_coprod | term : prod_coprod variable {C} namespace prod_coprod @[simp] def size : prod_coprod C → Nat | of_cat' _ => 1 | init => 1 | prod X Y => size X + size Y + 1 | coprod X Y => size X + size Y + 1 | term => 1 inductive syn : (X Y : prod_coprod C) → Type | of_cat {X Y : C} : (X ⟶ Y) → syn (of_cat' X) (of_cat' Y) | prod_mk {X Y Z : prod_coprod C} : syn X Y → syn X Z → syn X (Y.prod Z) | fst {X Y : prod_coprod C} : syn (X.prod Y) X | snd {X Y : prod_coprod C} : syn (X.prod Y) Y | coprod_mk {X Y Z : prod_coprod C} : syn X Z → syn Y Z → syn (X.coprod Y) Z | inl {X Y : prod_coprod C} : syn X (X.coprod Y) | inr {X Y : prod_coprod C} : syn Y (X.coprod Y) | id (X : prod_coprod C) : syn X X | comp {X Y Z : prod_coprod C} : syn X Y → syn Y Z → syn X Z namespace syn inductive rel : {X Y : prod_coprod C} → syn X Y → syn X Y → Prop | refl {X Y : prod_coprod C} (f : syn X Y) : rel f f | symm {X Y : prod_coprod C} {f g : syn X Y} : rel f g → rel g f | trans {X Y : prod_coprod C} {f g h : syn X Y} : rel f g → rel g h → rel f h | comp_congr {X Y Z : prod_coprod C} {f₁ f₂ : syn X Y} {g₁ g₂ : syn Y Z} : rel f₁ f₂ → rel g₁ g₂ → rel (f₁.comp g₁) (f₂.comp g₂) | prod_mk_congr {X Y Z : prod_coprod C} {f₁ f₂ : syn X Y} {g₁ g₂ : syn X Z} : rel f₁ f₂ → rel g₁ g₂ → rel (f₁.prod_mk g₁) (f₂.prod_mk g₂) | coprod_mk_congr {X Y Z : prod_coprod C} {f₁ f₂ : syn X Z} {g₁ g₂ : syn Y Z} : rel f₁ f₂ → rel g₁ g₂ → rel (f₁.coprod_mk g₁) (f₂.coprod_mk g₂) | id_comp {X Y : prod_coprod C} (f : syn X Y) : rel ((syn.id X).comp f) f | comp_id {X Y : prod_coprod C} (f : syn X Y) : rel (f.comp (syn.id Y)) f | assoc {W X Y Z : prod_coprod C} (f : syn W X) (g : syn X Y) (h : syn Y Z) : rel ((f.comp g).comp h) (f.comp (g.comp h)) | of_cat_id {X : C} : rel (syn.of_cat (𝟙 X)) (syn.id (of_cat' X)) | of_cat_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : rel (syn.of_cat (f ≫ g)) (syn.comp (syn.of_cat f) (syn.of_cat g)) | mk_fst_comp {X Y Z : prod_coprod C} (f : syn X Y) (g : syn X Z) : rel (syn.comp (syn.prod_mk f g) syn.fst) f | mk_snd_comp {X Y Z : prod_coprod C} (f : syn X Y) (g : syn X Z) : rel (syn.comp (syn.prod_mk f g) syn.snd) g | prod_eta {X Y Z : prod_coprod C} (f : syn X (Y.prod Z)) : rel (syn.prod_mk (f.comp syn.fst) (f.comp syn.snd)) f | inl_comp_mk {X Y Z : prod_coprod C} (f : syn X Z) (g : syn Y Z) : rel (syn.comp syn.inl (syn.coprod_mk f g)) f | inr_comp_mk {X Y Z : prod_coprod C} (f : syn X Z) (g : syn Y Z) : rel (syn.comp syn.inr (syn.coprod_mk f g)) g | coprod_eta {X Y Z : prod_coprod C} (f : syn (X.coprod Y) Z) : rel (syn.coprod_mk (syn.inl.comp f) (syn.inr.comp f)) f infixl:50 " ♥ " => rel instance : Trans (@rel C _ X Y) (@rel C _ X Y) (@rel C _ X Y) where trans := rel.trans theorem rel_prod {X Y Z : prod_coprod C} {f g : syn X (Y.prod Z)} (h₁ : rel (f.comp syn.fst) (g.comp syn.fst)) (h₂ : rel (f.comp syn.snd) (g.comp syn.snd)) : rel f g := rel.trans (rel.symm (rel.prod_eta f)) (rel.trans (rel.prod_mk_congr h₁ h₂) (rel.prod_eta g)) theorem rel_coprod {X Y Z : prod_coprod C} {f g : syn (X.coprod Y) Z} (h₁ : rel (syn.inl.comp f) (syn.inl.comp g)) (h₂ : rel (syn.inr.comp f) (syn.inr.comp g)) : rel f g := rel.trans (rel.symm (rel.coprod_eta f)) (rel.trans (rel.coprod_mk_congr h₁ h₂) (rel.coprod_eta g)) end syn inductive norm_hom : (X Y : prod_coprod C) → Type | of_cat {X Y : C} (f : X ⟶ Y) : norm_hom (of_cat' X) (of_cat' Y) | coprod_mk {X Y Z : prod_coprod C} (f : norm_hom X Z) (g : norm_hom Y Z) : norm_hom (X.coprod Y) Z | prod_mk {X Y Z : prod_coprod C} (f : norm_hom X Y) (g : norm_hom X Z) : norm_hom X (prod Y Z) | comp_inl {X Y Z : prod_coprod C} (f : norm_hom X Y) : norm_hom X (coprod Y Z) | comp_inr {X Y Z : prod_coprod C} (f : norm_hom X Z) : norm_hom X (coprod Y Z) | fst_comp {X Y Z : prod_coprod C} (f : norm_hom X Z) : norm_hom (prod X Y) Z | snd_comp {X Y Z : prod_coprod C} (f : norm_hom Y Z) : norm_hom (prod X Y) Z | from_init (X : prod_coprod C) : norm_hom init X | to_term (X : prod_coprod C) : norm_hom X term namespace norm_hom inductive rel : {X Y : prod_coprod C} → norm_hom X Y → norm_hom X Y → Prop | refl {X Y : prod_coprod C} (f : norm_hom X Y) : rel f f | symm {X Y : prod_coprod C} {f g : norm_hom X Y} : rel g f → rel f g | trans {X Y : prod_coprod C} {f g h : norm_hom X Y} : rel f g → rel g h → rel f h | coprod_mk_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom X Z} {g₁ g₂ : norm_hom Y Z} : rel f₁ f₂ → rel g₁ g₂ → rel (coprod_mk f₁ g₁) (coprod_mk f₂ g₂) | prod_mk_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom X Y} {g₁ g₂ : norm_hom X Z} : rel f₁ f₂ → rel g₁ g₂ → rel (prod_mk f₁ g₁) (prod_mk f₂ g₂) | comp_inl_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom X Y} : rel f₁ f₂ → rel (comp_inl f₁ : norm_hom X (coprod Y Z)) (comp_inl f₂) | comp_inr_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom X Z} : rel f₁ f₂ → rel (comp_inr f₁ : norm_hom X (coprod Y Z)) (comp_inr f₂) | fst_comp_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom X Z} : rel f₁ f₂ → rel (fst_comp f₁ : norm_hom (prod X Y) Z) (fst_comp f₂) | snd_comp_congr {X Y Z : prod_coprod C} {f₁ f₂ : norm_hom Y Z} : rel f₁ f₂ → rel (snd_comp f₁ : norm_hom (prod X Y) Z) (snd_comp f₂) | fst_comp_prod_mk {W X Y Z : prod_coprod C} (f : norm_hom X Y) (g : norm_hom X Z) : rel (fst_comp (prod_mk f g) : norm_hom (prod X W) (prod Y Z)) (prod_mk f.fst_comp g.fst_comp) | snd_comp_prod_mk {W X Y Z : prod_coprod C} (f : norm_hom X Y) (g : norm_hom X Z) : rel (snd_comp (prod_mk f g) : norm_hom (prod W X) (prod Y Z)) (prod_mk f.snd_comp g.snd_comp) | comp_inl_coprod_mk {W X Y Z : prod_coprod C} (f : norm_hom W Y) (g : norm_hom X Y) : rel (comp_inl (coprod_mk f g) : norm_hom (coprod W X) (coprod Y Z)) (coprod_mk f.comp_inl g.comp_inl) | comp_inr_coprod_mk {W X Y Z : prod_coprod C} (f : norm_hom W Y) (g : norm_hom X Y) : rel (comp_inr (coprod_mk f g) : norm_hom (coprod W X) (coprod Z Y)) (coprod_mk f.comp_inr g.comp_inr) | fst_comp_comp_inl {W X Y Z : prod_coprod C} (f : norm_hom W Y) : rel (f.fst_comp.comp_inl : norm_hom (prod W X) (coprod Y Z)) f.comp_inl.fst_comp | snd_comp_comp_inl {W X Y Z : prod_coprod C} (f : norm_hom X Y) : rel (f.snd_comp.comp_inl : norm_hom (prod W X) (coprod Y Z)) f.comp_inl.snd_comp | fst_comp_comp_inr {W X Y Z : prod_coprod C} (f : norm_hom W Z) : rel (f.fst_comp.comp_inr : norm_hom (prod W X) (coprod Y Z)) f.comp_inr.fst_comp | snd_comp_comp_inr {W X Y Z : prod_coprod C} (f : norm_hom X Z) : rel (f.snd_comp.comp_inr : norm_hom (prod W X) (coprod Y Z)) f.comp_inr.snd_comp def to_inj : {X Y Z : prod_coprod C} → (f : norm_hom X (coprod Y Z)) → Option ((norm_hom X Y) ⊕ (norm_hom X Z)) | _, _, _, comp_inl f => some (Sum.inl f) | _, _, _, comp_inr f => some (Sum.inr f) | _, _, _, fst_comp f => match to_inj f with | none => none | some (Sum.inl f) => some (Sum.inl (fst_comp f)) | some (Sum.inr f) => some (Sum.inr (fst_comp f)) | _, _, _, snd_comp f => match to_inj f with | none => none | some (Sum.inl f) => some (Sum.inl (snd_comp f)) | some (Sum.inr f) => some (Sum.inr (snd_comp f)) | _, _, _, coprod_mk f g => match to_inj f, to_inj g with | some (Sum.inl f), some (Sum.inl g) => some (Sum.inl (coprod_mk f g)) | some (Sum.inr f), some (Sum.inr g) => some (Sum.inr (coprod_mk f g)) | _, _ => none | _, _, _, @from_init _ _ (coprod _ _) => some (Sum.inl (coprod_mk f g)) theorem to_inj_eq_inl : {X Y Z : prod_coprod C} → {f : norm_hom X (coprod Y Z)} → {g : norm_hom X Y} → to_inj f = some (Sum.inl g) → rel f g.comp_inl | _, _, _, comp_inl f, g, h => by simp [to_inj] at h simp [h] exact rel.refl _ | _, _, _, comp_inr f, g, h => by simp [to_inj] at h | _, _, _, snd_comp f, g, h => have hi : ∃ i, to_inj f = some (Sum.inl i) := by { simp [to_inj] at h revert h match to_inj f with | some (Sum.inl i) => intro h; exact ⟨i, rfl⟩ | some (Sum.inr _) => simp | none => simp } match hi with | ⟨i, hi⟩ => by simp [hi, to_inj] at h rw [← h] exact rel.trans (rel.snd_comp_congr (to_inj_eq_inl hi)) (rel.snd_comp_comp_inl i).symm | _, _, _, fst_comp f, g, h => have hi : ∃ i, to_inj f = some (Sum.inl i) := by { simp [to_inj] at h revert h match to_inj f with | some (Sum.inl i) => intro h; exact ⟨i, rfl⟩ | some (Sum.inr _) => simp | none => simp } match hi with | ⟨i, hi⟩ => by simp [hi, to_inj] at h rw [← h] exact rel.trans (rel.fst_comp_congr (to_inj_eq_inl hi)) (rel.fst_comp_comp_inl i).symm | _, _, _, coprod_mk f g, i, h => have hi : ∃ f' g', to_inj f = some (Sum.inl f') ∧ to_inj g = some (Sum.inl g') := by { simp [to_inj] at h revert h match to_inj f, to_inj g with | some (Sum.inl f'), some (Sum.inl g') => intro h; exact ⟨f', g', rfl, rfl⟩ | some (Sum.inr _), some (Sum.inr _) => simp | none, _ => simp | _, none => simp | some (Sum.inl _), some (Sum.inr _) => simp | some (Sum.inr _), some (Sum.inl _) => simp } match hi with | ⟨f', g', hf, hg⟩ => by simp [hf, hg, to_inj] at h rw [← h] exact rel.trans (rel.coprod_mk_congr (to_inj_eq_inl hf) (to_inj_eq_inl hg)) (rel.comp_inl_coprod_mk _ _).symm theorem to_inj_eq_inr : {X Y Z : prod_coprod C} → {f : norm_hom X (coprod Y Z)} → {g : norm_hom X Z} → to_inj f = some (Sum.inr g) → rel f g.comp_inr | _, _, _, comp_inr f, g, h => by simp [to_inj] at h simp [h] exact rel.refl _ | _, _, _, comp_inl f, g, h => by simp [to_inj] at h | _, _, _, snd_comp f, g, h => have hi : ∃ i, to_inj f = some (Sum.inr i) := by { simp [to_inj] at h revert h match to_inj f with | some (Sum.inr i) => intro h; exact ⟨i, rfl⟩ | some (Sum.inl _) => simp | none => simp } match hi with | ⟨i, hi⟩ => by simp [hi, to_inj] at h rw [← h] exact rel.trans (rel.snd_comp_congr (to_inj_eq_inr hi)) (rel.snd_comp_comp_inr i).symm | _, _, _, fst_comp f, g, h => have hi : ∃ i, to_inj f = some (Sum.inr i) := by { simp [to_inj] at h revert h match to_inj f with | some (Sum.inr i) => intro h; exact ⟨i, rfl⟩ | some (Sum.inl _) => simp | none => simp } match hi with | ⟨i, hi⟩ => by simp [hi, to_inj] at h rw [← h] exact rel.trans (rel.fst_comp_congr (to_inj_eq_inr hi)) (rel.fst_comp_comp_inr i).symm | _, _, _, coprod_mk f g, i, h => have hi : ∃ f' g', to_inj f = some (Sum.inr f') ∧ to_inj g = some (Sum.inr g') := by { simp [to_inj] at h revert h match to_inj f, to_inj g with | some (Sum.inr f'), some (Sum.inr g') => intro _; exact ⟨f', g', rfl, rfl⟩ | some (Sum.inl _), some (Sum.inl _) => simp | none, _ => simp | _, none => simp | some (Sum.inr _), some (Sum.inl _) => simp | some (Sum.inl _), some (Sum.inr _) => simp } match hi with | ⟨f', g', hf, hg⟩ => by simp [hf, hg, to_inj] at h rw [← h] exact rel.trans (rel.coprod_mk_congr (to_inj_eq_inr hf) (to_inj_eq_inr hg)) (rel.comp_inr_coprod_mk _ _).symm theorem to_inj_eq_none {X Y Z : prod_coprod C} {f : norm_hom X (coprod Y Z)} (hf : to_inj f = none) {g : norm_hom X Z} : ¬rel f g.comp_inr := by intro h cases h simp at hf end norm_hom
module Verified.Functor %default total class Functor f => VerifiedFunctor (f : Type -> Type) where functorIdentity : {a : Type} -> (x : f a) -> map id x = id x functorComposition : {a : Type} -> {b : Type} -> (x : f a) -> (g1 : a -> b) -> (g2 : b -> c) -> map (g2 . g1) x = (map g2 . map g1) x
#! /usr/bin/env python # -*- coding: utf-8 -*- import warnings import numpy as np from scipy import odr try: from modefit.baseobjects import BaseModel, BaseFitter except: raise ImportError("install modefit (pip install modefit) to be able to access to ADRFitter") from .adr import ADR """ Tools to fit ADR parameters """ __all__ = ["ADRFitter"] class ADRFitter( BaseFitter ): """ """ PROPERTIES = ["adr","lbda", "x", "y", "dx","dy"] DERIVED_PROPERTIES = [] def __init__(self, adr, lbdaref=7000, base_parangle=0, unit=1): """ """ self._properties['adr'] = adr if lbdaref is not None: self.adr.set(lbdaref=lbdaref) self.set_model( ADRModel(self.adr, base_parangle=base_parangle, unit=unit)) def get_fitted_rotation(self): """ dictionary containing the effective rotatio (paramgle=base_parangle+fitted_rotation) + details: Returns ------- dict: {"parangle":self.fitvalues["parangle"]+self.model.base_parangle, "base_parangle":self.model.base_parangle, "fitted_addition_parangle":self.fitvalues["parangle"]} """ return {"parangle":self.fitvalues["parangle"]+self.model.base_parangle, "base_parangle":self.model.base_parangle, "fitted_addition_parangle":self.fitvalues["parangle"] } def set_data(self, lbda, x, y, dx, dy): """ set the fundatemental properties of the object. These that will be used to the fit """ self._properties['x'] = np.asarray(x) self._properties['y'] = np.asarray(y) self._properties['dx'] = np.asarray(dx) self._properties['dy'] = np.asarray(dy) self._properties['lbda'] = np.asarray(lbda) indexref = np.argmin(np.abs(self.lbda-self.adr.lbdaref)) # - Initial Guess self.model.set_reference(self.adr.lbdaref, self.x[indexref], self.y[indexref]) def _get_model_args_(self): """ see model.get_loglikelihood""" return self.x, self.y, self.lbda, self.dx, self.dy # ---------- # # PLOTTER # # ---------- # def show(self, ax=None, savefile=None, show=True, cmap=None, show_colorbar=True, clabel="Wavelength [A]", labelkey=None, guess_airmass=None,**kwargs): """ Plotting method for the ADR fit. Parameters ---------- Returns ------- """ import matplotlib.pyplot as mpl from .tools import figout, insert_ax, colorbar if ax is None: fig = mpl.figure(figsize=[5.5,4]) ax = fig.add_axes([0.14,0.13,0.76,0.75]) ax.set_xlabel("spaxels x-axis", fontsize="medium") ax.set_ylabel("spaxels y-axis", fontsize="medium") else: fig = ax.figure # - Colors if cmap is None: cmap = mpl.cm.viridis vmin, vmax = np.nanmin(self.lbda),np.nanmax(self.lbda) colors = cmap( (self.lbda-vmin)/(vmax-vmin) ) # - data scd = ax.scatter(self.x, self.y, facecolors=colors, edgecolors="None", lw=1., label="data", **kwargs) # - error if self.dx is not None or self.dy is not None: ax.errorscatter(self.x, self.y, dx=self.dx, dy=self.dy, ecolor="0.7", zorder=0) # - model xmodel, ymodel = self.model.get_model(self.lbda) scm = ax.scatter(xmodel, ymodel, edgecolors=colors, facecolors="None", lw=2., label="model", **kwargs) ax.legend(loc="best", frameon=True, ncol=2) if labelkey is None: textlabel = " ; ".join(["%s: %.2f"%(k,self.fitvalues[k]) for k in self.model.FREEPARAMETERS]) + "\n"+" %s: %.1f"%("lbdaref",self.model.adr.lbdaref) + " | unit: %.2f"%self.model._unit else: textlabel = " ; ".join(["%s: %.2f"%(k,self.fitvalues[k]) for k in labelkey]) if guess_airmass is not None: textlabel += " (input airmass: %.2f)"%guess_airmass ax.text(0.5,1.01, textlabel, fontsize="small", transform=ax.transAxes, va="bottom", ha="center") if show_colorbar: axc = ax.insert_ax("right", shrunk=0.89) axc.colorbar(cmap, vmin=vmin, vmax=vmax, label=clabel, fontsize="medium") fig.figout(savefile=savefile, show=show) return {"ax":ax, "fig":fig, "plot":[scd,scm]} # ================= # # Properties # # ================= # @property def adr(self): """ """ return self._properties['adr'] @property def x(self): """ x-positions """ return self._properties['x'] @property def y(self): """ y-positions """ return self._properties['y'] @property def dx(self): """ x-position errors """ return self._properties['dx'] @property def dy(self): """ y-position errors """ return self._properties['dy'] @property def lbda(self): """ wavelength [A] """ return self._properties['lbda'] @property def npoints(self): """ number of data point """ return len(self.x) class ADRModel( BaseModel): """ """ PROPERTIES = ["adr", "lbdaref"] SIDE_PROPERTIES = ["base_parangle"] # could be moved to parameters FREEPARAMETERS = ["parangle", "airmass", "xref", "yref"] parangle_boundaries = [-180, 180] def __init__(self, adr, xref=0, yref=0, base_parangle=0, unit=1.): """ """ self.set_adr(adr) self._side_properties['xref'] = xref self._side_properties['yref'] = yref self._side_properties['base_parangle'] = base_parangle self._unit = unit def setup(self, parameters): """ """ self._properties["parameters"] = np.asarray(parameters) for i,p in enumerate(self.FREEPARAMETERS): if p == "unit": self._unit = parameters[i] elif p== "xref": self._side_properties['xref'] = parameters[i] elif p== "yref": self._side_properties['yref'] = parameters[i] elif p=="parangle": self.adr.set(**{p:(parameters[i]+self.base_parangle)%360}) else: self.adr.set(**{p:parameters[i]}) def set_reference(self, lbdaref, xref=0, yref=0): """ use 'lbdaref=None' to avoid changing lbdaref """ if lbdaref is not None: self.adr.set(lbdaref=lbdaref) self._side_properties['xref'] = xref self._side_properties['yref'] = yref def get_model(self, lbda): """ return the model for the given data. The modelization is based on legendre polynomes that expect x to be between -1 and 1. This will create a reshaped copy of x to scale it between -1 and 1 but if x is already as such, save time by setting reshapex to False Returns ------- array (size of x) """ return self.adr.refract(self.xref, self.yref, lbda, unit=self._unit) def get_loglikelihood(self, x, y, lbda, dx=None, dy=None): """ Measure the likelihood to find the data given the model's parameters. Set pdf to True to have the array prior sum of the logs (array not in log=pdf). In the Fitter define _get_model_args_() that should return the input of this """ if dx is None: dx = 1 if dy is None: dy = 1 xadr, yadr = self.get_model(lbda) point_distance = ((x-xadr)/dx)**2 + ((y-yadr)/dy)**2 return -0.5 * np.sum(point_distance) # ================= # # Properties # # ================= # def set_adr(self, adr): """ """ if self._properties['lbdaref'] is not None: adr.set(lbdaref=lbdaref) self._properties['adr'] = adr @property def adr(self): """ ADR object """ if self._properties['adr'] is None: self.set_adr( ADR() ) return self._properties['adr'] @property def lbdaref(self): """ reference wavelength of the ADR """ return self._properties['lbdaref'] if self._properties['lbdaref'] is not None\ else self.adr.lbdaref # - side properties @property def xref(self): """ x-position at the reference wavelength (lbdaref)""" return self._side_properties['xref'] @property def yref(self): """ y-position at the reference wavelength (lbdaref)""" return self._side_properties['yref'] @property def base_parangle(self): """ the parangle is the additional rotation on top of this """ return self._side_properties["base_parangle"]
! H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ! H0 X ! H0 X libAtoms+QUIP: atomistic simulation library ! H0 X ! H0 X Portions of this code were written by ! H0 X Albert Bartok-Partay, Silvia Cereda, Gabor Csanyi, James Kermode, ! H0 X Ivan Solt, Wojciech Szlachta, Csilla Varnai, Steven Winfield. ! H0 X ! H0 X Copyright 2006-2010. ! H0 X ! H0 X These portions of the source code are released under the GNU General ! H0 X Public License, version 2, http://www.gnu.org/copyleft/gpl.html ! H0 X ! H0 X If you would like to license the source code under different terms, ! H0 X please contact Gabor Csanyi, [email protected] ! H0 X ! H0 X Portions of this code were written by Noam Bernstein as part of ! H0 X his employment for the U.S. Government, and are not subject ! H0 X to copyright in the USA. ! H0 X ! H0 X ! H0 X When using this software, please cite the following reference: ! H0 X ! H0 X http://www.libatoms.org ! H0 X ! H0 X Additional contributions by ! H0 X Alessio Comisso, Chiara Gattinoni, and Gianpietro Moras ! H0 X ! H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX !XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX !X !X cp2k_driver_template program !X !% filepot program for CP2K driver using input file template !X !XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX !XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #include "error.inc" program cp2k_driver_template use libatoms_module use cp2k_driver_module implicit none integer, parameter :: CP2K_LINE_LENGTH = 1024 !Max line length to be printed into the CP2K input files type(Atoms) :: my_atoms real(dp) :: energy real(dp), allocatable :: f0(:,:) real(dp), pointer :: forces_p(:,:) type(CInoutput) :: xyz_io character(len=STRING_LENGTH) :: infile, outfile character(len=STRING_LENGTH) :: args_str character(len=STRING_LENGTH) :: arg integer :: i, index_insert integer :: error = ERROR_NONE call system_initialise(verbosity=PRINT_SILENT,enable_timing=.true.) call verbosity_push(PRINT_NORMAL) call system_timer('cp2k_driver_template') if (cmd_arg_count() < 2) & call system_abort("Usage: cp2k_driver_template infile outfile [ other_cli_arg1=v1 other_cli_arg2=v2 ...]") call get_cmd_arg(1, infile) call get_cmd_arg(2, outfile) args_str = "" if (cmd_arg_count() > 2) then do i=3, cmd_arg_count() call get_cmd_arg(i, arg) !add {} if there is space in the arg if (index(trim(arg)," ").ne.0) then index_insert = index(trim(arg),"=") arg(index_insert+1:len_trim(arg)+2) = "{"//arg(index_insert+1:len_trim(arg))//"}" call print('arg: '//trim(arg),PRINT_SILENT) endif args_str = trim(args_str) // " " // trim(arg) end do endif call read(my_atoms,infile, error=error) if (error == ERROR_NONE) then allocate(f0(3,my_atoms%N)) else ! continue: do_cp2k_calc() should fail, but print first out help message if requested CLEAR_ERROR(error) endif !call CP2K call do_cp2k_calc(at=my_atoms, f=f0, e=energy, args_str=trim(args_str), error=error) HANDLE_ERROR(error) !momentum conservation ! call sum0(f0) !write energy and forces call set_value(my_atoms%params,'energy',energy) call add_property(my_atoms,'force', 0.0_dp, n_cols=3) if (.not. assign_pointer(my_atoms, 'force', forces_p)) then call system_abort("filepot_read_output needed forces, but couldn't find force in my_atoms ") endif forces_p = f0 call initialise(xyz_io,outfile,action=OUTPUT) call write(my_atoms,xyz_io,real_format='%20.13f') call finalise(xyz_io) deallocate(f0) call finalise(my_atoms) call system_timer('cp2k_driver_template') mainlog%prefix="" call verbosity_push(PRINT_SILENT) call system_finalise end program cp2k_driver_template
[STATEMENT] lemma wf_less_bool_rel: "wf less_bool_rel" [PROOF STATE] proof (prove) goal (1 subgoal): 1. wf less_bool_rel [PROOF STEP] by (metis less_bool_rel_iff wfUNIVI)
type $__field_meta__ <struct { @fieldname i32, @offset i32, @declaringclass <* void>, @type <* void>}> var $v1 <* void> public var $v2 <* void> public var $vs <[1] <$__field_meta__>> public = [[1= 0x35ad1b, 2= 0xabcd, 3= addrof ptr $v2, 4= addrof ptr $v1]] var $vvs <[2][1] <$__field_meta__>> public = [[[1= 11, 2= 22, 3= addrof ptr $v1, 4= addrof ptr $v1]], [[1= 33, 2= 44, 3= addrof ptr $v2, 4= addrof ptr $v2]]] # EXEC: %irbuild Main.mpl # EXEC: %irbuild Main.irb.mpl # EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
import os import pdb import sys import traceback import numpy as np import tensorflow as tf from IPython.terminal.embed import embed sys.path.insert(0, os.path.abspath(".")) from capsule import _renorm_r def test1(): """Convolved over image [1, 7, 7, 1] with out_channels=1, kernel_size=3x3, stride=1 Number of upper units convolved lower units: 1 2 3 3 3 2 1 2 4 6 6 6 4 2 3 6 9 9 9 6 3 3 6 9 9 9 6 3 3 6 9 9 9 6 3 2 4 6 6 6 4 2 1 2 3 3 3 2 1 So res[0, 0, 0] should be: 1/1 1/2 1/3 1/2 1/4 1/7 1/3 1/7 1/9 and res[0, 2, 2] should be 1/9 1/9 1/9 1/9 1/9 1/9 1/9 1/9 1/9 """ img_shape = [5, 5, 1, 9, 1] inputs = tf.placeholder(tf.float32, [None] + img_shape) r = _renorm_r(inputs, 1) config = tf.ConfigProto(device_count={'GPU': 0}) with tf.Session(config=config) as sess: res = sess.run(r, feed_dict={inputs: np.ones([1] + img_shape)}) print(res) # ipython interactive terminal embed() def test2(): """Convolved over image [1, 7, 7, 2] with out_channels=2, kernel_size=3x3, stride=1 Number of upper units convolved lower units: 1 2 3 3 3 2 1 2 4 6 6 6 4 2 3 6 9 9 9 6 3 3 6 9 9 9 6 3 3 6 9 9 9 6 3 2 4 6 6 6 4 2 1 2 3 3 3 2 1 So res[0, 0, 0] should be: 1/2 1/4 1/6 1/4 1/8 1/14 1/6 1/14 1/18 1/2 1/4 1/6 1/4 1/8 1/14 1/6 1/14 1/18 and res[0, 2, 2] should be 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 1/18 """ img_shape = [5, 5, 2, 9, 2] inputs = tf.placeholder(tf.float32, [None] + img_shape) r = _renorm_r(inputs, 1) config = tf.ConfigProto(device_count={'GPU': 0}) with tf.Session(config=config) as sess: res = sess.run(r, feed_dict={inputs: np.ones([1] + img_shape)}) print(res) # ipython interactive terminal embed() def test3(): """Convolved over image [1, 7, 7, 2] with out_channels=2, kernel_size=3x3, stride=2 Number of upper units convolved lower units: 1 1 2 1 2 1 1 1 1 2 1 2 1 1 2 2 4 2 4 2 2 1 1 2 1 2 1 1 2 2 4 2 4 2 2 1 1 2 1 2 1 1 1 1 2 1 2 1 1 So res[0, 0, 0] should be: 1/1 1/1 1/2 1/1 1/1 1/2 1/2 1/2 1/4 and res[0, 1, 1] should be 1/4 1/2 1/4 1/2 1/1 1/2 1/4 1/2 1/4 """ img_shape = [3, 3, 1, 9, 1] inputs = tf.placeholder(tf.float32, [None] + img_shape) r = _renorm_r(inputs, 2) config = tf.ConfigProto(device_count={'GPU': 0}) with tf.Session(config=config) as sess: res = sess.run(r, feed_dict={inputs: np.ones([1] + img_shape)}) print(res) # ipython interactive terminal embed() def main(): test1() test2() test3() if __name__ == '__main__': try: main() except: type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
Formal statement is: lemma has_contour_integral_const_linepath: "((\<lambda>x. c) has_contour_integral c*(b - a))(linepath a b)" Informal statement is: The contour integral of a constant function along a line segment is the product of the constant and the length of the line segment.
By comparing manifests from different systems, you can determine if the systems are installed identically or have been upgraded in synch. For example, if you customized your systems to a particular security target, this comparison finds any discrepancies between the manifest that represents your security target, and the manifests from the other systems. For the options, see the bart(1M) man page. On the test system, use the same bart options to create a manifest. To perform the comparison, copy the manifests to a central location. If the test system is not an NFS-mounted system, use sftp or another reliable means to copy the manifests to a central location. Compare the manifests and redirect the output to a file. This example compares the contents of the /usr/bin directory on two systems. Create an identical manifest for each system that you want to compare with the control system. Copy the manifests to the same location. The output indicates that the group ID of the su file in the /usr/bin directory is not the same as that of the control system. This information might indicate that a different version of the software was installed on the test system. Because the GID is changed, the more likely reason is that someone has tampered with the file.
immutable Spec2D{T<:Real,D<:PlaneDomains, G<:PlaneGroups,W<:RedundantWaveletClass} <: AbstractSpec{T,D,G,W} ɛ::Float64 ϕmeta::ΦMeta ψmetas::Array{ΨMeta2D,3} class::W domain::D log2_size::Int max_aspectratio::Float64 max_qualityfactor::Float64 max_scale::Float64 motherfrequency::Float64 n_filters_per_octave::Int n_octaves::Int pointgroup::G signaltype::Type{T} function (::Type{Spec2D}){T,D,W}( ; class::W = Morlet(), signaltype::Type{T} = Float32, domain::D = FourierDomain(2), ɛ = default_ɛ(signaltype), log2_size = 5, max_aspectratio = nothing, max_qualityfactor = nothing, max_scale = Inf, n_filters_per_octave = nothing, n_octaves = nothing, n_orientations = nothing) n_orientations = default_n_orientations(class, n_orientations) """Infer point group from wavelet.""" pointgroup = issteerable(class) ? RotationGroup(n_orientations) : TrivialGroup() """Maximum aspect ratio (length-to-width) of the wavelets.""" max_aspectratio = default_max_aspectratio(class, max_aspectratio) """Maximum quality factor and number of filters per octave are set simultaneously, so that they default to each other if either is present.""" max_qualityfactor, n_filters_per_octave = default_max_qualityfactor(max_qualityfactor, n_filters_per_octave), default_n_filters_per_octave(n_filters_per_octave, max_qualityfactor) """Center frequency of the mother wavelet (`motherfrequency`).""" motherfrequency = default_motherfrequency(class, n_filters_per_octave) """By default, the number of octaves in the filter bank is such that all wavelet scales do not exceed the signal length, nor the user-defined maximum scale `max_scale` if present.""" n_octaves = default_n_octaves(n_octaves, class, log2_size, max_qualityfactor, max_scale, motherfrequency, n_filters_per_octave) """The number of orientations of a one-dimensional filter bank is equal to 1 for non-steerable real wavelets (`pointgroup::TrivialGroup`), equal to n_orientations otherwise (`pointgroup::RotationGroup`).""" nΘs = get_n_orientations(pointgroup) ħ = uncertainty(class) """The meta-information of the wavelets is computed as a 3-d array, whose dimensions respectively correspond to * the orientation variable `θ`, * the chroma variable `χ`, and * the octave variable `j`.""" ψmetas = Array{ΨMeta2D}(nΘs, n_filters_per_octave, n_octaves) for j in 0:(n_octaves-1), χ in 0:(n_filters_per_octave-1) γ = j * n_filters_per_octave + χ resolution = exp2(-γ / n_filters_per_octave) centerfrequency = motherfrequency * resolution unbounded_scale = ħ * max_aspectratio * max_qualityfactor / centerfrequency scale = min(unbounded_scale, max_scale) unbounded_q = scale * centerfrequency / (ħ * max_aspectratio) qualityfactor = clamp(unbounded_q, 1.0, max_qualityfactor) unbounded_scale = ħ * max_aspectratio * qualityfactor / centerfrequency scale = min(unbounded_scale, max_scale) aspectratio = scale * centerfrequency / (ħ * scale) bandwidth = centerfrequency / qualityfactor for θ in 0:(nΘs-1) ψmetas[1+θ, 1+χ, 1+j] = ΨMeta2D(γ, θ, χ, aspectratio, bandwidth, centerfrequency, j, qualityfactor, scale) end end """The bandwidth of the lowpass filter `ϕ` is such that the Fourier transform of `ϕ` will cover the low-frequency part of the spectrum that is not covered by the wavelets `ψs`.""" ϕbandwidth = motherfrequency * exp2(-n_octaves) ϕscale = ħ / ϕbandwidth ϕmeta = ΦMeta(ϕbandwidth, ϕscale) G = typeof(pointgroup) spec = new{T,D,G,W}(ɛ, ϕmeta, ψmetas, class, domain, log2_size, max_aspectratio, max_qualityfactor, max_scale, motherfrequency, n_filters_per_octave, n_octaves, pointgroup, signaltype) """Before returning the `spec`, we call the function `checkspec` which enforces properties of the wavelet filter bank to satisfy null mean, limited spatial support, and Littlewood-Paley inequality.""" checkspec(spec) && return spec end end """Enforces properties of two-dimensional wavelets. * For steerable wavelets, such as `Morlet`, `max_aspectratio` must be `≧1.0` and `n_orientations` must be `≧2`. * For non-steerable wavelets, such as `MexicanHat`, `max_aspectratio` must be equal to `1.0` and `n_orientations` must be equal to `1`.""" function checkspec(spec::Spec2D) if issteerable(spec.class) if spec.max_aspectratio < 1.0 error("`max_aspectratio` must be `≧1.0`", "for steerable wavelets.") end if get_n_orientations(spec.pointgroup) < 2 error("`n_orientations` must be `≧2` for steerable wavelets") end else if spec.max_aspectratio != 1.0 error("`max_aspectratio` must be equal to `1.0`", "for non-steerable wavelets.") end if get_n_orientations(spec.pointgroup) != 1 error("`n_orientations` must be equal to `1`", "for non-steerable wavelets") end end checkspec_super(spec) && return true end """By default, the maximum aspect ratio is set to `2.0` for steerable wavelets, such as `Morlet`. For non-steerable wavelets, such as `MexicanHat`, the maximum aspect ratio must be equal to `1.0`.""" default_max_aspectratio(class::RedundantWaveletClass, max_aspectratio::Void) = issteerable(class) ? 2.0 : 1.0 default_max_aspectratio(class::RedundantWaveletClass, max_aspectratio::Any) = Float64(max_aspectratio) """By default, the number of orientations is set to `4` for steerable wavelets, such as `Morlet`. For non-steerable wavelets, such as `MexicanHat`, the number of orientations must be equal to `1`.""" default_n_orientations(class::RedundantWaveletClass, n_orientations::Void) = issteerable(class) ? 4 : 1 function default_n_orientations(class::RedundantWaveletClass, n_orientations::Any) if issteerable(class) return Int(n_orientations) else error("`n_orientations` must be equal to `1` for steerable wavelets") end end
@theme TangoTheme Dict( :name => "Tango", :description => "A theme inspired by the Tango Icon Theme Guidelines.", :comments => "Based on Tango theme from Pygments.", :style => S"fg: f8f8f8", :tokens => Dict( COMMENT => S"italic; fg: 8f5902", COMMENT_MULTILINE => S"italic; fg: 8f5902", COMMENT_PREPROC => S"italic; fg: 8f5902", COMMENT_SINGLE => S"italic; fg: 8f5902", COMMENT_SPECIAL => S"italic; fg: 8f5902", ERROR => S"fg: a40000; bg: ef2929", GENERIC => S"fg: 000000", GENERIC_DELETED => S"fg: a40000", GENERIC_EMPH => S"italic; fg: 000000", GENERIC_ERROR => S"fg: ef2929", GENERIC_HEADING => S"bold; fg: 000080", GENERIC_INSERTED => S"fg: 00a000", GENERIC_OUTPUT => S"italic; fg: 000000", GENERIC_PROMPT => S"fg: 8f5902", GENERIC_STRONG => S"bold; fg: 000000", GENERIC_SUBHEADING => S"bold; fg: 800080", GENERIC_TRACEBACK => S"bold; fg: a40000", KEYWORD => S"bold; fg: 204a87", KEYWORD_CONSTANT => S"bold; fg: 204a87", KEYWORD_DECLARATION => S"bold; fg: 204a87", KEYWORD_NAMESPACE => S"bold; fg: 204a87", KEYWORD_PSEUDO => S"bold; fg: 204a87", KEYWORD_RESERVED => S"bold; fg: 204a87", KEYWORD_TYPE => S"bold; fg: 204a87", LITERAL => S"fg: 000000", LITERAL_DATE => S"fg: 000000", NAME => S"fg: 000000", NAME_ATTRIBUTE => S"fg: c4a000", NAME_BUILTIN => S"fg: 204a87", NAME_BUILTIN_PSEUDO => S"fg: 3465a4", NAME_CLASS => S"fg: 000000", NAME_CONSTANT => S"fg: 000000", NAME_DECORATOR => S"bold; fg: 5c35cc", NAME_ENTITY => S"fg: ce5c00", NAME_EXCEPTION => S"bold; fg: cc0000", NAME_FUNCTION => S"fg: 000000", NAME_LABEL => S"fg: f57900", NAME_NAMESPACE => S"fg: 000000", NAME_OTHER => S"fg: 000000", NAME_PROPERTY => S"fg: 000000", NAME_TAG => S"bold; fg: 204a87", NAME_VARIABLE => S"fg: 000000", NAME_VARIABLE_CLASS => S"fg: 000000", NAME_VARIABLE_GLOBAL => S"fg: 000000", NAME_VARIABLE_INSTANCE => S"fg: 000000", NUMBER => S"bold; fg: 0000cf", NUMBER_FLOAT => S"bold; fg: 0000cf", NUMBER_HEX => S"bold; fg: 0000cf", NUMBER_INTEGER => S"bold; fg: 0000cf", NUMBER_INTEGER_LONG => S"bold; fg: 0000cf", NUMBER_OCT => S"bold; fg: 0000cf", OPERATOR => S"bold; fg: ce5c00", OPERATOR_WORD => S"bold; fg: 204a87", OTHER => S"fg: 000000", PUNCTUATION => S"bold; fg: 000000", STRING => S"fg: 4e9a06", STRING_BACKTICK => S"fg: 4e9a06", STRING_CHAR => S"fg: 4e9a06", STRING_DOC => S"italic; fg: 8f5902", STRING_DOUBLE => S"fg: 4e9a06", STRING_ESCAPE => S"fg: 4e9a06", STRING_HEREDOC => S"fg: 4e9a06", STRING_INTERPOL => S"fg: 4e9a06", STRING_OTHER => S"fg: 4e9a06", STRING_REGEX => S"fg: 4e9a06", STRING_SINGLE => S"fg: 4e9a06", STRING_SYMBOL => S"fg: 4e9a06", TEXT => S"", WHITESPACE => S"underline; fg: f8f8f8", ) )
r=0.99 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7zc77/media/images/d7zc77-003/svc:tesseract/full/full/0.99/default.jpg Accept:application/hocr+xml
lemma filterlim_split_at: "filterlim f F (at_left x) \<Longrightarrow> filterlim f F (at_right x) \<Longrightarrow> filterlim f F (at x)" for x :: "'a::linorder_topology"
[STATEMENT] lemma eqOn_singl[simp]: "eqOn {p} env \<pi>l env1 \<pi>l1 \<longleftrightarrow> \<pi>l!(env p) = \<pi>l1!(env1 p)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.eqOn {p} env \<pi>l env1 \<pi>l1 = (\<pi>l ! env p = \<pi>l1 ! env1 p) [PROOF STEP] unfolding eqOn_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<forall>pa. pa \<in> {p} \<longrightarrow> \<pi>l ! env pa = \<pi>l1 ! env1 pa) = (\<pi>l ! env p = \<pi>l1 ! env1 p) [PROOF STEP] by auto
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 18 13:41:17 2021 @author: d23 """ import numpy as np import matplotlib.pyplot as plt monoN=np.loadtxt("mini_mono_N.txt") monoT=np.loadtxt("mini_mono_T.txt") staggeredN=np.loadtxt("mini_staggered_N.txt") staggeredT=np.loadtxt("mini_staggered_T.txt") plt.plot(monoN, monoT, 'ro-', staggeredN, staggeredT, 'gx-') plt.yscale('log')
I have a tongue but cannot taste. My servants work hard below me. I am banned in lands where the Crescent Moon reigns. My kin have been made into canon. I can summon an army which doesn’t use weapons. My swinging rounds told time before clocks. What am I?
suppressMessages(library(kazaam, quietly=TRUE)) source("./utils.r") iris = read.iris("./iris.csv")$iris svd = svd(iris) u = svd$u d = diag(svd$d) vt = t(svd$v) tol = sqrt(.Machine$double.eps) test.local = isTRUE(all.equal(iris, u %*% d %*% vt, check.attributes=FALSE, tolerance=tol)) test = comm.all(test.local) comm.print(test) finalize()
[STATEMENT] lemma card_edges_two: "e \<in> E \<Longrightarrow> card e = 2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. e \<in> E \<Longrightarrow> card e = 2 [PROOF STEP] using edge_betw all_bi_edges_alt part_intersect_empty [PROOF STATE] proof (prove) using this: ?e \<in> E \<Longrightarrow> ?e \<in> all_bi_edges X Y ?X \<inter> ?Y = {} \<Longrightarrow> all_bi_edges ?X ?Y = {e. card e = 2 \<and> e \<inter> ?X \<noteq> {} \<and> e \<inter> ?Y \<noteq> {}} X \<inter> Y = {} goal (1 subgoal): 1. e \<in> E \<Longrightarrow> card e = 2 [PROOF STEP] by auto
Require Export Structure.FiniteCompleteClosed. Require Export Structure.Pullback. Module Topos. Structure mixin_of (C: FCClosed) := Mixin { Subobj: C; truth: 1 ~> Subobj; sub {X Y: C} (f: X ~> Y): monic f -> Y ~> Subobj; sub_pullback {X Y: C} (f: X ~> Y) (Hf: monic f): is_pullback truth (sub f Hf) ! f; sub_unique {X Y: C} (f: X ~> Y) (g: Y ~> Subobj) (Hf: monic f): is_pullback truth g ! f -> sub f Hf = g; }. Section ClassDef. Structure class_of (C: Category) := Class { base: FCClosed.class_of C; mixin: mixin_of (FCClosed.Pack C base); }. Local Coercion base: class_of >-> FCClosed.class_of. Local Coercion mixin: class_of >-> mixin_of. Structure type := Pack { sort: Category; _: class_of sort }. Local Coercion sort: type >-> Category. Variable (C: type). Definition class := match C return class_of C with Pack _ c => c end. Let xC := match C with Pack C _ => C end. Notation xclass := (class: class_of xC). Definition TopCategory := TopCategory.Pack C xclass. Definition ProdCategory := ProdCategory.Pack C xclass. Definition CartCategory := CartCategory.Pack C xclass. Definition ExpCategory := ExpCategory.Pack C (ExpCategory.Class _ xclass xclass). Definition CCC := CCC.Pack C xclass. Definition EqCategory := EqCategory.Pack C xclass. Definition FCClosed := FCClosed.Pack C xclass. End ClassDef. Module Exports. Coercion base: class_of >-> FCClosed.class_of. Coercion mixin: class_of >-> mixin_of. Coercion sort: type >-> Category. Coercion TopCategory: type >-> TopCategory.type. Canonical TopCategory. Coercion ProdCategory: type >-> ProdCategory.type. Canonical ProdCategory. Coercion CartCategory: type >-> CartCategory.type. Canonical CartCategory. Coercion ExpCategory: type >-> ExpCategory.type. Canonical ExpCategory. Coercion CCC: type >-> CCC.type. Canonical CCC. Coercion EqCategory: type >-> EqCategory.type. Canonical EqCategory. Coercion FCClosed: type >-> FCClosed.type. Canonical FCClosed. Notation Topos := type. End Exports. End Topos. Export Topos.Exports. Section ToposTheory. Context {T: Topos}. Definition Subobj: T := Topos.Subobj T (Topos.class T). Definition truth: 1 ~> Subobj := Topos.truth T (Topos.class T). Definition sub: forall {X Y: T} (f: X ~> Y), monic f -> Y ~> Subobj := @Topos.sub T (Topos.class T). Notation Ω := Subobj. Notation χ := sub. Lemma sub_pullback: forall {X Y: T} (f: X ~> Y) (Hf: monic f), is_pullback truth (sub f Hf) ! f. Proof. exact (@Topos.sub_pullback T (Topos.class T)). Qed. Lemma sub_unique: forall {X Y: T} (f: X ~> Y) (g: Y ~> Subobj) (Hf: monic f), is_pullback truth g ! f -> sub f Hf = g. Proof. exact (@Topos.sub_unique T (Topos.class T)). Qed. End ToposTheory.
program z2zi real z(9999),zi(0:9999) c c convert z-points to z-cells c c z on stdin c zi on stdout c do k= 1,9999 read(5,*,end=100) z(k) enddo 100 continue kz = k-1 c c assume that cell thickness increases with depth, c and that we would like z to be at the center of the zi's. c zi(0) = 0.0 zi(2) = 0.5*(z(2)+z(3)) zi(1) = max( 0.5*(z(1)+z(2)), & 2.0* z(2)-zi(2) ) do k= 3,kz-1 zi(k) = min( 2.0* z(k)-zi(k-1), & 0.5*(z(k)+z(k+1)) ) enddo zi(kz) = z(kz) + (z(kz) - zi(kz-1)) c write(6,"(f12.4)") zi(0) do k= 1,kz write(6,"(3f12.4)") zi(k),z(k),0.5*(zi(k)+zi(k-1)) enddo end
In 2017, the average number of clients served per month was 979, or 225 clients per week. With the help of many volunteers and donations, over 383,000 pounds of food were distributed in 2017 by the Morrison County Food Shelf. There are more than 300 food shelves in Minnesota, serving every county in the state. LITTLE FALLS, Minn. – August 27, 2018 – Morrison County Food Shelf will host a “Party with a Purpose” event on Tuesday, September 18 at Sprout (609 13th Ave NE, Door 8, Little Falls, MN 55345). The party will raise funds for the the food shelf’s mission to end hunger in Morrison County. The Morrison County Food Shelf exists to provide emergency and supplemental food to people who lack sufficient resources to feed themselves. The public is invited to attend the event to meet the food shelf Board and volunteers and learn about their work, including testimonials from those who have been assisted by the food shelf. “The food shelf is just one piece of the food access puzzle, and right now there’s a lot of opportunity for collaboration, whether it’s Fare for All, Ruby’s Pantry, Share A Meal, or Sprout,” says Kate Bjorge. “We hope community members will attend this event and be inspired by the stories of their neighbors to continue to support these initiatives.” The Morrison County Food Shelf is located at 912 1st Avenue SW, Little Falls, Minnesota and it’s open hours are Tuesdays and Wednesdays from 10am - 12pm and Thursdays from 6pm - 8pm. The food shelf is currently recruiting volunteers to serve, especially those with skills and expertise in electric, plumbing, and building repairs. The food shelf is also hiring for a paid position to clean up to four hours per week. To learn more about these opportunities contact Director Carol Schirmers-Johnson at 320-632-8304. The Parties with a Purpose activities are funded through a grant awarded to Region Five Development Commission by ArtPlace America’s National Creative Placemaking Fund. The ArtPlace funds are providing the Sprout Growers & Makers Marketplace and partners the support needed to host an expansion of economic opportunities, social and cultural experiences, and learning for local growers, artists, makers, producers, chefs, and the public. Sprout and partners will also build out the Marketplace's physical space over the next three years using commissioned functional art from local artists, with priority granted to Latino, East African, Native American, Amish, grower, and youth communities. Sprout strives to connect and strengthen the local food system as a regional asset, operating from their facility centrally located in Little Falls, Minnesota. The Sprout facility hosts the monthly indoor Growers & Makers Marketplace as well as a shared-use commercial kitchen to promote food entrepreneurship and community gatherings around food, art, and culture. Sprout is a federally recognized 501c3 non-profit organization. The community is invited to shop the Sprout Growers & Makers Marketplace vendors selling local food and art on Saturdays from 10 a.m. to 3 p.m. on October 27, November 17, and December 8. Interested growers, artists, chefs, community members, and educators who want to learn more, visit www.SproutMN.com and follow the Sprout Growers & Makers Marketplace on Facebook.
module Calc.Add %default total export add : Int -> Int -> Int add x y = x + y
State Before: R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } ⊢ ↑(collectedBasis h v) = fun a => ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(collectedBasis h v) a = ↑(↑(v a.fst) a.snd) Tactic: funext a State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(collectedBasis h v) a = ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (↑(LinearEquiv.symm (Dfinsupp.mapRange.linearEquiv fun i => (v i).repr)) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) Tactic: simp only [IsInternal.collectedBasis, coeLinearMap, Basis.coe_ofRepr, LinearEquiv.trans_symm, LinearEquiv.symm_symm, LinearEquiv.trans_apply, sigmaFinsuppLequivDfinsupp_apply, sigmaFinsuppEquivDfinsupp_single, LinearEquiv.ofBijective_apply, sigmaFinsuppAddEquivDfinsupp_apply] State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (↑(LinearEquiv.symm (Dfinsupp.mapRange.linearEquiv fun i => (v i).repr)) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (↑(Dfinsupp.mapRange.linearEquiv fun i => LinearEquiv.symm (v i).repr) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) Tactic: rw [Dfinsupp.mapRange.linearEquiv_symm] State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (↑(Dfinsupp.mapRange.linearEquiv fun i => LinearEquiv.symm (v i).repr) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (Dfinsupp.mapRange (fun i x => ↑(LinearEquiv.symm (v i).repr) x) (_ : ∀ (i : ι), ↑(LinearEquiv.symm (v i).repr) 0 = 0) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) Tactic: erw [Dfinsupp.mapRange.linearEquiv_apply] State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(toModule R ι M fun i => Submodule.subtype (A i)) (Dfinsupp.mapRange (fun i x => ↑(LinearEquiv.symm (v i).repr) x) (_ : ∀ (i : ι), ↑(LinearEquiv.symm (v i).repr) 0 = 0) (Dfinsupp.single a.fst (Finsupp.single a.snd 1))) = ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(↑(Dfinsupp.lsum ℕ) fun i => Submodule.subtype (A i)) (Dfinsupp.single a.fst (↑(v a.fst) a.snd)) = ↑(↑(v a.fst) a.snd) Tactic: simp only [Dfinsupp.mapRange_single, Basis.repr_symm_apply, Finsupp.total_single, one_smul, toModule] State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(↑(Dfinsupp.lsum ℕ) fun i => Submodule.subtype (A i)) (Dfinsupp.single a.fst (↑(v a.fst) a.snd)) = ↑(↑(v a.fst) a.snd) State After: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(Submodule.subtype (A a.fst)) (↑(v a.fst) a.snd) = ↑(↑(v a.fst) a.snd) Tactic: erw [Dfinsupp.lsum_single] State Before: case h R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A : ι → Submodule R M h : IsInternal A α : ι → Type u_2 v : (i : ι) → Basis (α i) R { x // x ∈ A i } a : (i : ι) × α i ⊢ ↑(Submodule.subtype (A a.fst)) (↑(v a.fst) a.snd) = ↑(↑(v a.fst) a.snd) State After: no goals Tactic: simp only [Submodule.coeSubtype]
Davis Sunset Rotary is one of three Rotary Clubs in Davis. Rotary International is an international service club whose stated purpose is to bring together business and professional leaders in order to provide humanitarian services, encourage high ethical standards in all vocations, and help build goodwill and peace in the world. In 2011, Davis Sunset Rotary took over Movies in the Park when it was cut from the City budget.
// Copyright 2019-2020 Jan Feitsma (Falcons) // SPDX-License-Identifier: Apache-2.0 /* * mStimulator.cpp * * Created on: Dec 2018 * Author: Jan Feitsma */ // system includes #include <iostream> #include <boost/program_options.hpp> // internal includes #include "cWorldModelStimulator.hpp" // other packages #include "falconsCommon.hpp" // local defines and namespaces namespace po = boost::program_options; bool process_command_line(int argc, char** argv, int& agentId, int& verbosity, std::string& inputFile, std::string& outputFile, int& overruleRobotPos, std::vector<std::string>& overruledKeys, std::vector<std::string>& deletedKeys) { try { po::options_description desc("worldModelStimulator options"); desc.add_options() ("help,h", "produce help message") ("agent,a", po::value<int>(&agentId)->default_value(0), "set agent id") ("input,i", po::value<std::string>(&inputFile)->required(), "set the input file") ("output,o", po::value<std::string>(&outputFile)->default_value("auto"), "set the output file") ("verbosity,v", po::value<int>(&verbosity)->default_value(1), "set verbosity level") ("overrule_robot_pos,p", po::value<int>(&overruleRobotPos)->default_value(0), "overrule robot position with position already on rdl") ("overrule_keys,k", po::value<std::vector<std::string> >()->multitoken()->zero_tokens()->composing(), "overrule keys on the new frame with values from existing frame") ("delete_keys,d", po::value<std::vector<std::string> >()->multitoken()->zero_tokens()->composing(), "keys to be deleted from the existing frame") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return false; } // https://stackoverflow.com/questions/5395503/required-and-optional-arguments-using-boost-library-program-options // There must be an easy way to handle the relationship between options "help" and others // Yes, the magic is putting the po::notify after "help" option check po::notify(vm); if(vm.count("overrule_keys")) { overruledKeys = vm["overrule_keys"].as<std::vector<std::string> >(); } if(vm.count("delete_keys")) { deletedKeys = vm["delete_keys"].as<std::vector<std::string> >(); } } catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return false; } catch(...) { std::cerr << "Unknown error!" << std::endl; return false; } return true; } int main(int argc, char **argv) { // option parsing int agentId = 0; int verbosity = 1; std::string inputFile; std::string outputFile; int overruleRobotPos = 0; std::vector<std::string> overruledKeys; std::vector<std::string> deletedKeys; bool result = process_command_line(argc, argv, agentId, verbosity, inputFile, outputFile, overruleRobotPos, overruledKeys, deletedKeys); if (!result) { return 1; } // initialize and run // TODO: override configuration yaml file? cWorldModelStimulator stim(agentId, inputFile, outputFile); stim.setVerbosity(verbosity); stim.setRobotPosOverrule(overruleRobotPos == 1); for(auto it = overruledKeys.begin(); it != overruledKeys.end(); it++) { stim.add_overruled_key(*it); } for(auto it = deletedKeys.begin(); it != deletedKeys.end(); it++) { stim.add_deleted_key(*it); } stim.run(); return 0; }
[STATEMENT] lemma cp_OclIterate: "(X->iterate\<^sub>S\<^sub>e\<^sub>q(a; x = A | P a x)) \<tau> = ((\<lambda> _. X \<tau>)->iterate\<^sub>S\<^sub>e\<^sub>q(a; x = A | P a x)) \<tau>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. OclIterate X A P \<tau> = OclIterate (\<lambda>_. X \<tau>) A P \<tau> [PROOF STEP] by(simp add: OclIterate_def cp_defined[symmetric])
@testset "239.sliding-window-maximum.jl" begin @test max_sliding_window([1,3,-1,-3,5,3,6,7], 3) == [3,3,5,5,6,7] @test max_sliding_window([1], 1) == [1] @test max_sliding_window([1,-1], 1) == [1,-1] @test max_sliding_window([9,11], 2) == [11] @test max_sliding_window([4,-2], 2) == [4] @test max_sliding_window([32, 61, 68, 8, 87, 7, 20, 8, 16, 32, 20, 85, 21, 90, 89, 7, 1, 27, 22, 10, 19, 93, 44, 22, 9, 62, 55, 58, 16, 9, 20, 40, 49, 69, 91, 85, 56, 98, 64, 2, 1, 60, 75, 100, 56, 63, 47, 79, 20, 94, 78, 58, 69, 39, 7, 75, 52, 65, 36, 3, 73, 11, 73, 26, 78, 20, 45, 71, 53, 63, 74, 61, 29, 38, 2, 20, 75, 56, 96, 94, 74, 20, 21, 59, 81, 2, 9, 60, 52, 85, 98, 86, 97, 6, 94, 76, 70, 21, 50, 4, 32, 87, 18, 6, 100, 100, 9, 13, 71, 44, 83, 67, 59, 13, 74, 44, 20, 16, 81, 51, 74, 1, 60, 86, 60, 40, 99, 10, 44, 74, 61, 86, 39, 34, 75, 34, 86, 49, 43, 57, 43, 43, 14, 79, 65, 10, 95, 7, 65, 4, 71, 9, 61, 88, 26, 50, 68, 5, 50, 37, 56, 38, 3, 63, 93, 16, 73, 26, 41, 36, 96, 48, 99, 79, 43, 16, 3, 24, 93, 29, 87, 81, 51, 5, 52, 30, 70, 17, 23, 75, 53, 70, 29, 24, 93, 77, 38, 51, 55, 71], 15) == [90,90,90,90,90,90,90,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,91,98,98,98,98,98,98,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,94,94,94,94,94,94,78,78,78,78,78,78,78,78,78,78,78,78,78,78,96,96,96,96,96,96,96,96,96,96,96,96,98,98,98,98,98,98,98,98,98,98,98,98,98,98,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,83,83,83,86,86,86,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,86,86,86,86,86,95,95,95,95,95,95,95,95,95,95,95,95,95,95,95,88,88,88,93,93,93,93,93,93,96,96,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,93,93,93,93,93,93,87,93,93,93,93,93,93] @test max_sliding_window([77, 67, 24, 88, 14, 54, 1, 47, 15, 49, 44, 87, 46, 41, 8, 22, 51, 38, 51, 29], 5) == [88,88,88,88,54,54,49,87,87,87,87,87,51,51,51,51] end
%VL_NNNORMALIZE CNN Local Response Normalization (LRN) % Y = VL_NNORMALIZE(X, PARAM) computes the so-called Local Response % Normalization (LRN) operator. This operator performs a % channel-wise sliding window normalization of each column of the % input array X. The normalized output is given by: % % Y(i,j,k) = X(i,j,k) / L(i,j,k)^BETA % % where the normalization factor is given by % % L(i,j,k) = KAPPA + ALPHA * (sum_{q in Q(k)} X(i,j,k)^2, % % PARAM = [N KAPPA ALPHA BETA], and N is the size of the window. The % window Q(k) is defined as: % % Q(k) = [max(1, k-FLOOR((N-1)/2)), min(D, k+CEIL((N-1)/2))]. % % where D is the number of feature channels in X. Note in particular % that, by setting N >= 2D, the function can be used to normalize % all the channels as a single group (useful to achieve L2 % normalization). % % DZDX = VL_NNORMALIZE(X, PARAM, DZDY) computes the derivative of % the block projected onto DZDY. DZDX and DZDY have the same % dimensions as X and Y respectively. % % **Remark:** Some CNN libraries (e.g. Caffe) use a slightly % different convention for the parameters of the LRN. Caffe in % particular uses the convention: % % PARAM_CAFFE = [N KAPPA N*ALPHA BETA] % % i.e. the ALPHA paramter is multiplied by N. % Copyright (C) 2014 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file).
#!/usr/bin/env Rscript # FLYCOP # Author: Beatriz García-Jiménez # April 2018 args = commandArgs(trailingOnly=TRUE) if (length(args)<4) { stop("At least 4 arguments must be supplied: <input_file.txt> <output_file.pdf> <met1_ID> <met2_ID> <strain1> <strain2>.", call.=FALSE) } else { inputFile=args[1] outFile=args[2] met1=args[3] met2=args[4] if(length(args)==6){ strain1=args[5] strain2=args[6] }else{ strain1="strain1" strain2="strain2" } } df=read.csv(inputFile,sep='\t',header=FALSE,col.names=c('hours','biomass1','biomass2','sub1','sub2')) yMax=max(df$biomass1,df$biomass2) yMax=1.5 pdf(outFile,pointsize=20) par(lwd=3) plot(df$hours*0.1,df$biomass1,xlab='time(h)',ylab='biomass (gr/L)',type='l',lwd=4,col="black",ylim=c(0,yMax)) par(new=TRUE) plot(df$hours*0.1,df$biomass2,xlab="",ylab="",type='l',lwd=4,col="black",lty=2,ylim=c(0,yMax)) par(new=TRUE,lwd=2) plot(df$hours*0.1,df$sub1,type='l',lwd=4,col="blue",axes=FALSE,xlab="",ylab="",ylim=c(0, max(df$sub1,df$sub2))) par(new=TRUE) plot(df$hours*0.1,df$sub2,type='l',lwd=4,col="red",axes=FALSE,xlab="",ylab="",ylim=c(0, max(df$sub1,df$sub2))) axis(side=4) mtext('metabolite Conc. (mM)',side=4,cex=par("cex.lab")) par(lty=1) legend("topright", c(strain1,strain2,met1,met2), lty=c(1,2,1,1), lwd=c(4,4,4,4), col=c("black","black","blue","red")) invisible(dev.off())
# https://machinelearningmastery.com/develop-first-xgboost-model-python-scikit-learn/ # https://www.kaggle.com/uciml/pima-indians-diabetes-database import numpy as np from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # Load data dataset = np.loadtxt('C:/q/w64/pima-natives-diabetes.csv', delimiter=",") # Split data into train and test sets, leave 33% of entries aside for testing X = dataset[:,0:8] y = dataset[:,8] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) # Fit model with training data model = XGBClassifier() model.fit(X_train, y_train) # Make predictions for test data y_pred = model.predict(X_test) predictions = [round(value) for value in y_pred] # Evaluate predictions accuracy = accuracy_score(y_test, predictions) print("Accuracy: {:.2f}%".format(accuracy * 100.0))
function set_indices_to!(mutee::AbstractArray{Int,2},indices::AbstractArray{Int,2},set_val::Integer) for y in 1:size(indices,1) mutee[indices[y,1], indices[y,2]] = set_val end end function towards(origin::Integer, destination::Integer) origin > destination && return origin - 1 origin < destination && return origin + 1 return origin end
theory Verifuck imports Main "~~/src/HOL/Word/Word" "~~/src/HOL/Library/Code_Char" begin datatype instr = Incr | Decr | Right | Left | Out | In | Loop | Pool fun parse_instrs :: "string \<Rightarrow> instr list" where "parse_instrs [] = []" | "parse_instrs (x # xs) = ( if x = CHR ''.'' then Out # parse_instrs xs else if x = CHR '','' then In # parse_instrs xs else if x = CHR ''+'' then Incr # parse_instrs xs else if x = CHR ''-'' then Decr # parse_instrs xs else if x = CHR ''<'' then Left # parse_instrs xs else if x = CHR ''>'' then Right # parse_instrs xs else if x = CHR ''['' then Loop # parse_instrs xs else if x = CHR '']'' then Pool # parse_instrs xs else parse_instrs xs)" datatype 'a tape = Tape (left: "'a list") (cur: 'a) (right: "'a list") definition empty_tape :: "'a::zero tape" where "empty_tape = Tape [] 0 []" definition tape_map_cur :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a tape \<Rightarrow> 'a tape" where "tape_map_cur f tape = Tape (left tape) (f (cur tape)) (right tape)" lemma "tape_map_cur f (Tape l c r) = Tape l (f c) r" by(simp add: tape_map_cur_def) fun tape_shift_right :: "'a::zero tape \<Rightarrow> 'a tape" where "tape_shift_right (Tape l c []) = Tape (c # l) 0 []" | "tape_shift_right (Tape l c (r # rs)) = Tape (c # l) r rs" fun tape_shift_left :: "'a::zero tape \<Rightarrow> 'a tape" where "tape_shift_left (Tape [] c r) = Tape [] 0 (c # r)" | "tape_shift_left (Tape (l # ls) c r) = Tape ls l (c # r)" (*state: input buffer read: read from state, produce new state out_buf: output buffer*) datatype ('a, 'b) io = Buffer (state: 'b) (read: "'b \<Rightarrow> ('a \<times> 'b)") ("write": "'a \<Rightarrow> 'b \<Rightarrow> 'b") datatype ('a, 'b) machine = Machine (tape: "'a tape") (io_state: "('a, 'b) io") definition map_tape :: "('a tape \<Rightarrow> 'a tape) \<Rightarrow> ('a, 'b) machine \<Rightarrow> ('a, 'b) machine" where "map_tape f m \<equiv> Machine (f (tape m)) (io_state m)" definition read_io :: "('a, 'b) io \<Rightarrow> ('a \<times> ('a, 'b) io)" where "read_io io = (let (c, state') = read io (state io) in (c, Buffer state' (read io) (write io)))" lemma "read_io (Buffer s r out) = (fst (r s), Buffer (snd (r s)) r out)" by(simp add: read_io_def split: prod.splits) definition write_io :: "'a \<Rightarrow> ('a, 'b) io \<Rightarrow> ('a, 'b) io" where "write_io c io = Buffer (write io c (state io)) (read io) (write io)" (*current program \<times> stack for loop*) type_synonym stacked_instr_list_state = "instr list \<times> instr list list" definition init_stacked_instr_list_state :: "instr list \<Rightarrow> stacked_instr_list_state" where "init_stacked_instr_list_state xs = (xs, [])" fun next_machine :: "instr \<Rightarrow> ('a::{zero,one,minus,plus}, 'b) machine \<Rightarrow> ('a, 'b) machine" where "next_machine Incr = map_tape (tape_map_cur (\<lambda>x. x + 1))" | "next_machine Decr = map_tape (tape_map_cur (\<lambda>x. x - 1))" | "next_machine Left = map_tape tape_shift_left" | "next_machine Right = map_tape tape_shift_right" | "next_machine In = (\<lambda>m. let (c, io') = read_io (io_state m) in Machine (tape_map_cur (\<lambda>_. c) (tape m)) io')" | "next_machine Out = (\<lambda>m. Machine (tape m) (write_io (cur (tape m)) (io_state m)))" fun skip_loop :: "instr list \<Rightarrow> nat \<Rightarrow> (instr list) option" where "skip_loop xs 0 = Some xs" | "skip_loop (Loop # xs) n = skip_loop xs (n + 1)" | "skip_loop (Pool # xs) n = skip_loop xs (n - 1)" | "skip_loop (x # xs) n = skip_loop xs n" | "skip_loop _ _ = None" partial_function (tailrec) interp_bf :: "stacked_instr_list_state \<Rightarrow> ('a::{zero,one,minus,plus}, 'b) machine \<Rightarrow> (instr list list \<times> ('a, 'b) machine) option" where "interp_bf tab m = (case tab of ([], stack) \<Rightarrow> Some (stack, m) | (Loop # is, stack) \<Rightarrow> if cur (tape m) = 0 then (case skip_loop is 1 of None \<Rightarrow> None | Some is' \<Rightarrow> interp_bf (is', stack) m) else interp_bf (is, (Loop # is) # stack) m | (Pool # _, is # stack) \<Rightarrow> interp_bf (is, stack) m | (Pool # _, []) \<Rightarrow> None | (i # is, stack) \<Rightarrow> interp_bf (is, stack) (next_machine i m))" declare interp_bf.simps[code] fun loop_level :: "instr list \<Rightarrow> nat option" where "loop_level [] = Some 0" | "loop_level (Loop # xs) = map_option Suc (loop_level xs)" | "loop_level (Pool # xs) = Option.bind (loop_level xs) (\<lambda>n. case n of 0 \<Rightarrow> None | Suc n \<Rightarrow> Some n)" | "loop_level (_ # xs) = loop_level xs" lemma loop_free_is_fold: "(\<forall>x \<in> set xs. x \<noteq> Pool \<and> x \<noteq> Loop) \<Longrightarrow> interp_bf (xs, stack) m = Some ((stack, fold next_machine xs m))" by (induction xs arbitrary: m stack) (simp add: interp_bf.simps split: instr.splits)+ lemma skip_loop_loop_free: "(\<forall>x \<in> set xs. x \<noteq> Pool \<and> x \<noteq> Loop) \<Longrightarrow> skip_loop (xs @ [Pool]) 1 = Some []" apply (induction xs) apply simp apply simp apply (case_tac a) apply auto done lemma loop_unroll: "(\<forall>x \<in> set xs. x \<noteq> Pool \<and> x \<noteq> Loop) \<Longrightarrow> interp_bf (Loop # xs, stack) m = Some ((stack, fold next_machine xs m))" apply (induction xs arbitrary: m stack) apply (subst interp_bf.simps) apply simp apply safe sorry axiomatization where falseI: "False" (*undefined behavior if reading from undefined input buffer. Pretty unusable since we cannot query from within our bf-code whether there is something to read available.*) (*factory*) definition run_bf_generic :: "instr list \<Rightarrow> 'a::{zero,one,minus,plus} list \<Rightarrow> 'a list" where "run_bf_generic prog input = rev (out_buf (io_state (the (interp_bf (init_stacked_instr_list_state prog) (Machine empty_tape (Buffer input (\<lambda>inp. (hd inp, tl inp)) []))))))" (*https://en.wikipedia.org/wiki/Brainfuck#End-of-file_behavior*) definition EOF :: "8 word" where "EOF \<equiv> 255" fun read_byte :: "8 word list \<Rightarrow> (8 word \<times> 8 word list)" where "read_byte [] = (EOF, [])" | "read_byte (b#bs) = (b, bs)" (*brainfuck byte factory*) definition run_bf :: "instr list \<Rightarrow> 8 word list \<Rightarrow> 8 word list" where "run_bf prog input = rev (out_buf (io_state (the (interp_bf (init_stacked_instr_list_state prog) (Machine empty_tape (Buffer input read_byte []))))))" export_code run_bf in SML module_name Verifuck file "code/verifuck.ML" (*SML_file "code/verifuck.ML"*) (*source: http://de.wikipedia.org/wiki/Brainfuck#Hello_World.21 retrieved Feb 7 2015*) definition "hello_world = ''++++++++++ [ >+++++++>++++++++++>+++>+<<<<- ] Schleife zur Vorbereitung der Textausgabe >++. Ausgabe von 'H' >+. Ausgabe von 'e' +++++++. 'l' . 'l' +++. 'o' >++. Leerzeichen <<+++++++++++++++. 'W' >. 'o' +++. 'r' ------. 'l' --------. 'd' >+. '!' >. Zeilenvorschub +++. Wagenruecklauf''" definition byte_to_char :: "8 word \<Rightarrow> char" where "byte_to_char b \<equiv> char_of_nat (unat b)" definition char_to_byte :: "char \<Rightarrow> 8 word" where "char_to_byte c \<equiv> of_nat (nat_of_char c)" lemma "let result = run_bf (parse_instrs hello_world) ([]::8 word list) in map byte_to_char result = ''Hello World!'' @ [CHR ''\<newline>'', CHR 0x0D]" by eval export_code run_bf in Haskell fun tape_shift_left' :: "'a tape \<Rightarrow> (string + 'a tape)" where "tape_shift_left' (Tape [] c r) = Inl ''cannot shift tape left: end of tape''" | "tape_shift_left' (Tape (l # ls) c r) = Inr (Tape ls l (c # r))" fun skip_loop_forward :: "instr list \<Rightarrow> instr list \<Rightarrow> nat \<Rightarrow> string + (instr list \<times> instr list)" where "skip_loop_forward [] rs _ = Inl ''unbalanced [] expected ]''" | "skip_loop_forward (Pool # cs) rs 0 = Inr (cs, Pool#rs)" | "skip_loop_forward (Pool # cs) rs (Suc n) = skip_loop_forward cs (Pool#rs) n" | "skip_loop_forward (Loop # cs) rs n = skip_loop_forward cs (Loop#rs) (n + 1)" | "skip_loop_forward (c # cs) rs n = skip_loop_forward cs (c#rs) n" fun skip_loop_backward :: "instr list \<Rightarrow> instr list \<Rightarrow> nat \<Rightarrow> string + (instr list \<times> instr list)" where "skip_loop_backward cs [] _ = Inl ''unbalanced [] expected [''" | "skip_loop_backward cs (Loop # rs) 0 = Inr (Loop#cs, rs)" | "skip_loop_backward cs (Loop # rs) (Suc n) = skip_loop_backward (Loop#cs) rs n" | "skip_loop_backward cs (Pool # rs) n = skip_loop_backward (Pool#cs) rs (n + 1)" | "skip_loop_backward cs (c#rs) n = skip_loop_backward (c#cs) rs n" lemma skip_loop_forward_Result_Pool: "skip_loop_forward cs rs n = Inr (cs', rs') \<Longrightarrow> hd rs' = Pool" by(induction cs rs n arbitrary: cs' rs' rule: skip_loop_forward.induct) auto lemma "skip_loop_backward cs rs n = Inr (cs', rs') \<Longrightarrow> hd cs' = Loop" by(induction cs rs n arbitrary: cs' rs' rule: skip_loop_backward.induct) auto lemma skip_loop_forward_Result: "skip_loop_forward cs rs n = Inr (cs', rs') \<Longrightarrow> rev rs @ cs = rev rs' @ cs'" by(induction cs rs n arbitrary: cs' rs' rule: skip_loop_forward.induct) auto <<<<<<< Updated upstream lemma skip_loop_forward_Result_cs: "skip_loop_forward cs rs n = Inr (cs', rs') \<Longrightarrow> ======= lemma skip_loop_forward_Reuslt_cs: "skip_loop_forward cs rs n = Result (cs', rs') \<Longrightarrow> >>>>>>> Stashed changes cs = (drop (length rs) (rev rs')) @ cs'" (* apply(induction cs rs n arbitrary: cs' rs' rule: skip_loop_forward.induct) apply auto (*This proof is yolo*) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) apply (smt append.assoc append_Nil append_eq_append_conv_if append_eq_conv_conj append_is_Nil_conv append_same_eq append_take_drop_id drop_all drop_append length_rev rev.simps(2) rev_append rev_rev_ident skip_loop_forward_Reuslt) *) <<<<<<< Updated upstream oops lemma "skip_loop_backward cs rs n = Inr (cs', rs') \<Longrightarrow> ======= done lemma "skip_loop_backward cs rs n = Result (cs', rs') \<Longrightarrow> >>>>>>> Stashed changes rev rs @ cs = rev rs' @ cs'" by(induction cs rs n arbitrary: cs' rs' rule: skip_loop_backward.induct) auto value "skip_loop_forward [Incr, Incr, Pool, Incr] [Loop, Decr] 0" value "skip_loop_backward [Pool, Decr] [Incr, Incr, Loop, Incr] 0" <<<<<<< Updated upstream (*steps left \<Rightarrow> current program \<Rightarrow> executed instructions \<Rightarrow> machine state \<Rightarrow> result*) fun bounded_machine :: "nat \<Rightarrow> instr list \<Rightarrow> instr list \<Rightarrow> ======= (*steps left \<Rightarrow> current program \<Rightarrow> executed instructions \<Rightarrow> skip because we are in a loop? \<Rightarrow> ...*) fun bounded_machine :: "nat \<Rightarrow> instr list \<Rightarrow> instr list \<Rightarrow> >>>>>>> Stashed changes ('a::{zero,one,minus,plus}, 'b) machine \<Rightarrow> (string \<times> instr list \<times> instr list \<times> ('a, 'b) machine) + ('a, 'b) machine " where "bounded_machine 0 cs rs m = Inl (''Out of Instructions'', rev rs, cs, m)" | (*TODO: error out-of-instructions*) "bounded_machine _ [] _ m = Inr m" | "bounded_machine (Suc n) (Incr#cs) rs (Machine tpe io) = bounded_machine n cs (Incr#rs) (Machine (tape_map_cur (\<lambda>x. x + 1) tpe) io)" | "bounded_machine (Suc n) (Decr#cs) rs (Machine tpe io) = bounded_machine n cs (Decr#rs) (Machine (tape_map_cur (\<lambda>x. x - 1) tpe) io)" | "bounded_machine (Suc n) (Left#cs) rs (Machine tpe io) = (case tape_shift_left' tpe of Inr tape' \<Rightarrow> bounded_machine n cs (Left#rs) (Machine tape' io) | Inl err \<Rightarrow> Inl (err, rev rs, cs, (Machine tpe io)) )" | <<<<<<< Updated upstream "bounded_machine (Suc n) (Right#cs) rs (Machine tpe io) = bounded_machine n cs (Right#rs) (Machine (tape_shift_right tpe) io)" | "bounded_machine (Suc n) (In#cs) rs (Machine tpe io) = bounded_machine n cs (In#rs) (let (c, io') = read_io io in (Machine (tape_map_cur (\<lambda>_. c) tpe) io'))" | "bounded_machine (Suc n) (Out#cs) rs (Machine tpe io) = bounded_machine n cs (Out#rs) (Machine tpe (write_io (cur tpe) io))" | "bounded_machine (Suc n) (Loop#cs) rs m = (if cur (tape m) = 0 then ======= "bounded_machine (Suc n) (Right#cs) rs (tape, io) = bounded_machine n cs (Right#rs) (tape_shift_right tape, io)" | "bounded_machine (Suc n) (In#cs) rs (tape, io) = bounded_machine n cs (In#rs) (let (c, io') = read_io io in (tape_map_cur (\<lambda>_. c) tape, io'))" | "bounded_machine (Suc n) (Out#cs) rs (tape, io) = bounded_machine n cs (Out#rs) (tape, write_io (cur tape) io)" | "bounded_machine (Suc n) (Loop#cs) rs m = (if cur (fst m) = 0 then >>>>>>> Stashed changes (case skip_loop_forward cs (Loop#rs) 0 of Inr (cs', rs') \<Rightarrow> bounded_machine n cs' rs' m | Inl err \<Rightarrow> Inl (err, rev rs, cs, m)) else bounded_machine n cs (Loop#rs) m)" | "bounded_machine (Suc n) (Pool#cs) rs m = (case skip_loop_backward (Pool#cs) rs 0 of Inr (cs', rs') \<Rightarrow> bounded_machine n cs' rs' m | Inl err \<Rightarrow> Inl (err, rev rs, cs, m))" value "bounded_machine 10 [Incr, Loop, Incr, Pool] [] (Machine empty_tape (Buffer [] read_byte []))" value "bounded_machine 4000 [Incr, Loop, Incr, Out, Pool] [] (Machine empty_tape (Buffer [] read_byte []))" value "bounded_machine 400000 [Decr, Loop, Loop, Decr, Right, Incr, Left, Pool, Out, Decr, Pool] [] (Machine empty_tape (Buffer [] read_byte []))" value "bounded_machine limit prog [] (Machine empty_tape (Buffer input read_byte []))" definition run_bf_bounded :: "nat \<Rightarrow> instr list \<Rightarrow> 8 word list \<Rightarrow> (string \<times> instr list \<times> instr list \<times> (8 word, 8 word list) machine) + (8 word list)" where "run_bf_bounded limit prog input \<equiv> case bounded_machine limit prog [] (Machine empty_tape (Buffer input read_byte [])) of Inr (Machine tpe buf) \<Rightarrow> Inr (rev (out_buf buf)) | Inl err \<Rightarrow> Inl err" lemma "case run_bf_bounded 1024 (parse_instrs hello_world) [] of Inr result \<Rightarrow> map byte_to_char result = ''Hello World!'' @ [CHR ''\<newline>'', CHR 0x0D]" by eval lemma "bounded_machine n prog rs m = Inr m' \<Longrightarrow> interp_bf (init_stacked_instr_list_state prog) m = Some m'" apply(induction n prog rs m rule: bounded_machine.induct) apply(simp_all add: init_stacked_instr_list_state_def interp_bf.simps map_tape_def split: list.splits) oops theorem "bounded_machine n prog [] m = Inr m' \<Longrightarrow> interp_bf (init_stacked_instr_list_state prog) m = Some m'" oops (*todo lars*) end
[STATEMENT] lemma rel_comp_empty_trancl_simp: "R O R = {} \<Longrightarrow> R\<^sup>+ = R" [PROOF STATE] proof (prove) goal (1 subgoal): 1. R O R = {} \<Longrightarrow> R\<^sup>+ = R [PROOF STEP] by (metis O_assoc relcomp_empty2 sup_bot_right trancl_unfold trancl_unfold_right)
import os from astropy.io import ascii from astropy.io.ascii.ipac import Ipac HERE = os.path.abspath(os.path.dirname(__file__)) class IPACSuite: def setup(self): self.vals = [str(i + 1) for i in range(1000)] self.widths = [i + 1 for i in range(1000)] f = open(os.path.join(HERE, 'files', 'ipac', 'string.txt')) self.lines = f.read().split('\n') f.close() self.table = ascii.read(os.path.join(HERE, 'files', 'ipac', 'string.txt'), format='ipac', guess=False) self.reader = Ipac() self.header = self.reader.header self.data = self.reader.data self.splitter = self.reader.data.splitter self.header.cols = list(self.table.columns.values()) self.data.cols = list(self.table.columns.values()) self.data._set_fill_values(self.data.cols) def time_splitter(self): self.splitter.join(self.vals, self.widths) def time_get_cols(self): self.header.get_cols(self.lines) def time_header_str_vals(self): self.header.str_vals() def time_data_str_vals(self): self.data.str_vals()
The palm tree is so iconic that we can lose sight of the varied uses of palms for making lovely gardens and landscapes. Jason Dewees, author of Designing with Palms and longtime friend of the UC Botanical Garden, will give a presentation with photos by Caitlin Atkison on the power of palms in garden design. In his book, he discusses palms' appeal to the senses and their use in creating garden styles, as well as basic information gardeners and designers need to know about the diverse palm family, including a portfolio of useful hardy palms and tropical staple species illustrated with photographer Caitlin Atkinson's gorgeous photos. Come see why palms' beauty and diversity -- from from delicate understory plants and hardy shrubs, to graceful trees and even bamboo-like clusters -- earn them a place in well-designed gardens throughout the warmer parts of the world -- including California. Lecture is followed by a walk through the collection. Jason Dewees is the horticulturist and palm expert on staff at Flora Grubb Gardens, in San Francisco, who has consulted on palm collections of the Conservatory of Flowers, UC Botanical Garden, and San Francisco Botanical Garden, trained volunteers and docents on the palm family, grown thousands of palms from seed, planted palms in gardens, consulted with gardeners, landscape architects and designers on using palms in the landscape, and lectured on palms. Jason joined the Northern California Chapter of the International Palm Society as their youngest member in 1986 and offers a very local point of view on palms for Bay Area climates. Copies of his book will be available for sale.
(* Based on https://github.com/xuanruiqi/categories/blob/master/category.v by Xuanruiqi. *) From sgdt Require Import preamble. Declare Scope category_scope. Delimit Scope category_scope with cat. Set Universe Polymorphism. Set Primitive Projections. Reserved Infix "~>" (at level 90, right associativity). Reserved Infix "\\o" (at level 40, left associativity). Reserved Notation "C '^op'" (at level 20, left associativity). Module Hom. Structure mixin_of (obj : Type) := Mixin {hom : obj -> obj -> Type}. Structure type : Type := Pack {sort; class : mixin_of sort}. Module Exports. Coercion sort : type >-> Sortclass. Global Bind Scope category_scope with sort. End Exports. End Hom. Export Hom.Exports. Definition hom {C} := Hom.hom _ (Hom.class C). Notation "U ~> V" := (hom U V) : category_scope. Module Precategory. Local Open Scope category_scope. Section Ops. Context (C : Hom.type). Definition op_seq := forall (X Y Z : C), X ~> Y -> Y ~> Z -> X ~> Z. Definition op_idn := forall X : C, X ~> X. End Ops. Structure mixin_of (C : Hom.type) := Mixin {seq : op_seq C; idn : op_idn C}. Structure type : Type := Pack {sort; class : mixin_of sort}. Module Exports. Coercion sort : type >-> Hom.type. Global Hint Unfold op_idn op_seq : core. End Exports. End Precategory. Export Precategory.Exports. Definition seq {C} {x y z} := @Precategory.seq _ (Precategory.class C) x y z. Definition idn {C} := Precategory.idn _ (Precategory.class C). Infix ">>" := seq (at level 60) : category_scope. Module Category. Local Open Scope category_scope. Section Laws. Context (C : Precategory.type). Definition law_seqA := forall (X Y Z W : C) (f : X ~> Y) (g : Y ~> Z) (h : Z ~> W), seq f (seq g h) = seq (seq f g) h. Definition law_seqL := forall (X Y : C) (f : X ~> Y), seq (idn X) f = f. Definition law_seqR := forall (X Y : C) (f : X ~> Y), seq f (idn Y) = f. End Laws. Structure mixin_of (C : Precategory.type) : Prop := Mixin {seqA : law_seqA C; seqL : law_seqL C; seqR : law_seqR C}. Structure type : Type := Pack {sort; class : mixin_of sort}. Module Exports. Coercion sort : type >-> Precategory.type. Global Hint Unfold law_seqA law_seqL law_seqR : core. End Exports. End Category. Export Category.Exports. Section Facts. Context {C : Category.type}. Fact seqA : Category.law_seqA C. Proof. by case: (Category.class C). Qed. Fact seqL : Category.law_seqL C. Proof. by case: (Category.class C). Qed. Fact seqR : Category.law_seqR C. Proof. by case: (Category.class C). Qed. End Facts. Local Open Scope category_scope. Module Opposite. Section Opposite. Context (C : Category.type). Definition hom_mixin : Hom.mixin_of C. Proof. build=> x y; exact: (y ~> x). Defined. Canonical hom : Hom.type. Proof. esplit; apply: hom_mixin. Defined. Definition precat_mixin : Precategory.mixin_of hom. Proof. build. - move=> x y z xy yz. exact: (yz >> xy). - move=> x; apply: idn. Defined. Canonical precat : Precategory.type. Proof. esplit; apply: precat_mixin. Defined. Definition cat_mixin : Category.mixin_of precat. Proof. build. - move=> u v w x uv vw wx. by rewrite /seq//=seqA. - move=> u v uv. by rewrite /seq//=seqR. - move=> u v uv. by rewrite/seq//=seqL. Qed. Canonical cat : Category.type. Proof. esplit; apply: cat_mixin. Defined. End Opposite. End Opposite. Canonical Opposite.hom. Canonical Opposite.precat. Canonical Opposite.cat. Notation "C '^op' " := (Opposite.cat C) : category_scope. Module FullSubcategory. Section Defs. Context (C : Category.type) (P : C -> Prop). Definition hom_mixin : Hom.mixin_of {x : C | P x}. Proof. by build=> x y; exact: (pi1 x ~> pi1 y). Defined. Canonical hom : Hom.type. Proof. by esplit; apply: hom_mixin. Defined. Definition precat_mixin : Precategory.mixin_of hom. Proof. build. - by move=> x y z; apply: seq. - by move=> x; apply: idn. Defined. Canonical precat : Precategory.type. Proof. by esplit; apply: precat_mixin. Defined. Definition cat_mixin : Category.mixin_of precat. Proof. build. - by move=>*; apply: seqA. - by move=>*; apply: seqL. - by move=>*; apply: seqR. Defined. Canonical cat : Category.type. Proof. by esplit; apply: cat_mixin. Defined. End Defs. End FullSubcategory. Canonical FullSubcategory.hom. Canonical FullSubcategory.precat. Canonical FullSubcategory.cat. Module TYPE. Definition hom_mixin : Hom.mixin_of Type. Proof. constructor=> A B; exact: (A -> B). Defined. Canonical hom : Hom.type. Proof. by esplit; apply: hom_mixin. Defined. Definition precat_mixin : Precategory.mixin_of hom. Proof. build. - by move=> A B C f g; exact: (g \o f). - by move=> A; exact: id. Defined. Canonical precat : Precategory.type. Proof. by esplit; apply: precat_mixin. Defined. Definition cat_mixin : Category.mixin_of precat. Proof. by []. Defined. Canonical cat : Category.type. Proof. by esplit; apply: cat_mixin. Defined. End TYPE. Module SET. Definition cat := TYPE.cat@{_ Set}. End SET. Module Product. Section Defs. Context (𝒞 𝒟 : Category.type). Definition hom_mixin : Hom.mixin_of (𝒞 × 𝒟). Proof. build; case=> c1 d1; case=> c2 d2. exact ((c1 ~> c2) × (d1 ~> d2)). Defined. Canonical hom : Hom.type. Proof. esplit; apply: hom_mixin. Defined. Definition precat_mixin : Precategory.mixin_of hom. Proof. build. - move=> u v w f g; split. + by exact: (pi1 f >> pi1 g). + by exact: (pi2 f >> pi2 g). - move=> u; split; by exact: idn. Defined. Canonical precat : Precategory.type. Proof. esplit; apply: precat_mixin. Defined. Definition cat_mixin : Category.mixin_of precat. Proof. by build; move=>*; apply: prodE=> //=; apply: seqA + apply: seqL + apply: seqR. Qed. Definition cat : Category.type. Proof. esplit; apply: cat_mixin. Defined. End Defs. End Product. Module Discrete. Section Defs. Context (I : Type). Definition hom_mixin : Hom.mixin_of I. Proof. by constructor=> i j; exact (i = j). Defined. Canonical hom : Hom.type. Proof. by esplit; apply: hom_mixin. Defined. Definition precat_mixin : Precategory.mixin_of hom. Proof. build. by move=> i j k -> ->. Defined. Canonical precat : Precategory.type. Proof. by esplit; apply: precat_mixin. Defined. Definition cat_mixin : Category.mixin_of precat. Proof. build. - move=> //= i j k l ij jk kl. move: j ij jk; apply: eq_ind. move: l kl; apply: eq_ind. by move: k; apply: eq_ind. - by move=> //= i; apply: eq_ind. - by move=> //= i; apply: eq_ind. Qed. Canonical cat : Category.type. Proof. by esplit; apply: cat_mixin. Defined. End Defs. End Discrete.
module ContriverText.Util import Data.SortedMap dic0 : Ord k => SortedMap k v dic0 = fromList [] dic1 : Ord k => k -> v -> SortedMap k v dic1 k0 v0 = fromList [(k0, v0)] dic2 : Ord k => k -> v -> k -> v -> SortedMap k v dic2 k0 v0 k1 v1 = fromList [(k0, v0), (k1, v1)] dic3 : Ord k => k -> v -> k -> v -> k -> v -> SortedMap k v dic3 k0 v0 k1 v1 k2 v2 = fromList [(k0, v0), (k1, v1), (k2, v2)] dic4 : Ord k => k -> v -> k -> v -> k -> v -> k -> v -> SortedMap k v dic4 k0 v0 k1 v1 k2 v2 k3 v3 = fromList [(k0, v0), (k1, v1), (k2, v2), (k3, v3)]
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .monoid import .loop set_option default_priority 0 namespace algebra signature group (α : Type*) := (op : α → α → α) (inv : α → α) (id : α) namespace group_sig variables {α : Type*} (s : group_sig α) abbreviation ldiv (x y : α) := s.op (s.inv x) y -- (λ x y, x⁻¹ ∙ y) abbreviation rdiv (x y : α) := s.op x (s.inv y) -- (λ x y, x ∙ y⁻¹) @[signature_instance] definition to_monoid : monoid_sig α := { op := s.op , id := s.id } @[signature_instance] definition to_loop : loop_sig α := { op := s.op , ldiv := s.ldiv , rdiv := s.rdiv , id := s.id } end group_sig variables {α : Type*} (s : group_sig α) local infix ∙ := s.op local postfix ⁻¹ := s.inv local notation `e` := s.id @[theory] class group : Prop := intro :: (associative : identity.op_associative s.op) (right_identity : identity.op_right_identity s.op s.id) (right_inverse : identity.op_right_inverse s.op s.inv s.id) namespace group variable [i : group s] include i @[identity_instance] theorem right_cancellative : identity.op_right_cancellative s.op := λ x y z, assume h : x ∙ y = z ∙ y, show x = z, from calc x = x ∙ e : by rw op_right_identity s.op ... = x ∙ (y ∙ y⁻¹) : by rw op_right_inverse s.op s.inv ... = (x ∙ y) ∙ y⁻¹ : by rw op_associative s.op ... = (z ∙ y) ∙ y⁻¹ : by rw h ... = z ∙ (y ∙ y⁻¹) : by rw op_associative s.op ... = z ∙ e : by rw op_right_inverse s.op s.inv ... = z : by rw op_right_identity s.op @[identity_instance] theorem left_identity : identity.op_left_identity s.op s.id := λ x, have (e ∙ x) ∙ x⁻¹ = x ∙ x⁻¹, from calc (e ∙ x) ∙ x⁻¹ = e ∙ (x ∙ x⁻¹) : by rw op_associative s.op ... = e ∙ e : by rw op_right_inverse s.op ... = e : by rw op_right_identity s.op ... = x ∙ x⁻¹ : by rw op_right_inverse s.op, op_right_cancellative s.op this @[identity_instance] theorem left_inverse : identity.op_left_inverse s.op s.inv s.id := λ x, have (x⁻¹ ∙ x) ∙ x⁻¹ = e ∙ x⁻¹, from calc (x⁻¹ ∙ x) ∙ x⁻¹ = x⁻¹ ∙ (x ∙ x⁻¹) : by rw op_associative s.op ... = x⁻¹ ∙ e : by rw op_right_inverse s.op s.inv ... = x⁻¹ : by rw op_right_identity s.op ... = e ∙ x⁻¹ : by rw op_left_identity s.op, op_right_cancellative s.op this @[identity_instance] theorem left_cancellative : identity.op_left_cancellative s.op := λ x y z, assume h : x ∙ y = x ∙ z, show y = z, from calc y = e ∙ y : by rw op_left_identity s.op ... = (x⁻¹ ∙ x) ∙ y : by rw op_left_inverse s.op ... = x⁻¹ ∙ (x ∙ y) : by rw op_associative s.op ... = x⁻¹ ∙ (x ∙ z) : by rw h ... = (x⁻¹ ∙ x) ∙ z : by rw op_associative s.op ... = e ∙ z : by rw op_left_inverse s.op ... = z : by rw op_left_identity s.op @[identity_instance] theorem inv_fixpoint : identity.fn_fixpoint s.inv s.id := show e⁻¹ = e, from calc e⁻¹ = e⁻¹ ∙ e : by rw op_right_identity s.op ... = e : by rw op_left_inverse s.op @[identity_instance] theorem inv_involutive : identity.fn_involutive s.inv := λ x, have x⁻¹⁻¹ ∙ x⁻¹ = x ∙ x⁻¹, from calc x⁻¹⁻¹ ∙ x⁻¹ = e : by rw op_left_inverse s.op ... = x ∙ x⁻¹ : by rw op_right_inverse s.op, op_right_cancellative s.op this @[identity_instance] theorem inv_antimorphism : identity.fn_op_antimorphism s.inv s.op s.op := λ x y, have (x ∙ y)⁻¹ ∙ (x ∙ y) = (y⁻¹ ∙ x⁻¹) ∙ (x ∙ y), from calc (x ∙ y)⁻¹ ∙ (x ∙ y) = e : by rw op_left_inverse s.op ... = y⁻¹ ∙ y : by rw op_left_inverse s.op ... = (y⁻¹ ∙ e) ∙ y : by rw op_right_identity s.op s.id ... = (y⁻¹ ∙ (x⁻¹ ∙ x)) ∙ y : by rw op_left_inverse s.op ... = ((y⁻¹ ∙ x⁻¹) ∙ x) ∙ y : by rw op_associative s.op y⁻¹ x⁻¹ x ... = (y⁻¹ ∙ x⁻¹) ∙ (x ∙ y) : by rw op_associative s.op, op_right_cancellative s.op this @[identity_instance] theorem left_division : identity.op_left_division s.op s.ldiv := λ x y, show x ∙ (x⁻¹ ∙ y) = y, from calc x ∙ (x⁻¹ ∙ y) = (x ∙ x⁻¹) ∙ y : by rw op_associative s.op ... = e ∙ y : by rw op_right_inverse s.op ... = y : by rw op_left_identity s.op @[identity_instance] theorem right_division : identity.op_right_division s.op s.rdiv := λ x y, show (y ∙ x⁻¹) ∙ x = y, from calc (y ∙ x⁻¹) ∙ x = y ∙ (x⁻¹ ∙ x) : by rw op_associative s.op ... = y ∙ e : by rw op_left_inverse s.op ... = y : by rw op_right_identity s.op instance to_monoid : monoid s.to_monoid := monoid.infer _ instance to_loop : loop s.to_loop := loop.infer _ end group @[theory] class comm_group : Prop := intro :: (associative : identity.op_associative s.op) (commutative : identity.op_commutative s.op) (right_identity : identity.op_right_identity s.op s.id) (right_inverse : identity.op_right_inverse s.op s.inv s.id) namespace comm_group variable [i : comm_group s] include i instance to_group : group s := group.infer _ @[identity_instance] theorem inv_homomorphism : identity.fn_op_homomorphism s.inv s.op s.op := λ x y, show (x ∙ y)⁻¹ = x⁻¹ ∙ y⁻¹, from calc (x ∙ y)⁻¹ = (y ∙ x)⁻¹ : by rw op_commutative s.op ... = x⁻¹ ∙ y⁻¹ : by rw fn_op_antimorphism s.inv s.op s.op instance to_comm_monoid : comm_monoid s.to_monoid := comm_monoid.infer _ end comm_group end algebra
module Main import Data.List data Token : Type where TokenString : Token TokenNumber : Token TerminalWord : String -> Token TerminalChar : Char -> Token tokenize : (xs : List Char) -> List Token tokenize [] = [] tokenize ('%' :: 'd' :: chars) = TokenNumber :: tokenize(chars) tokenize ('%' :: 's' :: chars) = TokenString :: tokenize(chars) tokenize (c :: chars) = (TerminalChar c) :: tokenize(chars) stringToTokens : String -> List Token stringToTokens s = tokenize . unpack $ s Formatter : (List Token) -> Type Formatter [] = String Formatter (x :: xs) = case x of TokenNumber => (i : Int) -> Formatter xs TokenString => (s : String) -> Formatter xs _ => Formatter xs printFmt : (tokens : List Token) -> (acc : String) -> Formatter tokens printFmt [] acc = acc printFmt (x :: xs) acc = case x of TokenNumber => (\i => printFmt xs (acc ++ show i)) TokenString => \s => printFmt xs (acc ++ s) (TerminalWord w) => printFmt xs (acc ++ w) (TerminalChar c) => printFmt xs (acc ++ (strCons c "")) ||| поддерживает следующие шаблоны: ||| ||| - %d - целое число ||| - %s - строка ||| - %v - структура поддерживающая интерфейс Show ||| ||| Пример использования: ||| ||| printf "Привет мир от %s" "Ивана" ||| ||| printf "Я получил %d монет от %s" 100 "Михаила" ||| ||| printf "Структура Nat: %v" (S (S (S N))) ||| printf : (template : String) -> Formatter (stringToTokens template) printf template = printFmt (stringToTokens template) "" main : IO () main = do putStrLn (printf "Hello, %s !" "UserName") putStrLn (printf "I have %d%s" 100 "$") putStrLn (printf "%s %d %s %d" "a" 10 "b" 10) -- Ошибочные случаи, когда мы не пройдем Type Checker: -- Type mistmatch beetween String -> String and String -- putStrLn (printf "%s %s" "hello") -- Type mistmatch between String and Int (expected type) -- putStrLn (printf "%d %s" "arg" 1)
```python from sympy.physics.mechanics import * from sympy import symbols, atan, cos, Matrix ``` ```python q = dynamicsymbols('q:3') qd = dynamicsymbols('q:3', level=1) l = symbols('l:3') m = symbols('m:3') g, t = symbols('g, t') ``` ```python # Compose World Frame N = ReferenceFrame('N') A = N.orientnew('A', 'axis', [q[0], N.z]) B = N.orientnew('B', 'axis', [q[1], N.z]) C = N.orientnew('C', 'axis', [q[2], N.z]) A.set_ang_vel(N, qd[0] * N.z) B.set_ang_vel(N, qd[1] * N.z) C.set_ang_vel(N, qd[2] * N.z) ``` ```python O = Point('O') P = O.locatenew('P', l[0] * A.x) R = P.locatenew('R', l[1] * B.x) S = R.locatenew('S', l[2] * C.x) ``` ```python O.set_vel(N, 0) P.v2pt_theory(O, N, A) R.v2pt_theory(P, N, B) S.v2pt_theory(R, N, C) ``` $\displaystyle l_{0} \dot{q}_{0}\mathbf{\hat{a}_y} + l_{1} \dot{q}_{1}\mathbf{\hat{b}_y} + l_{2} \dot{q}_{2}\mathbf{\hat{c}_y}$ ```python ParP = Particle('ParP', P, m[0]) ParR = Particle('ParR', R, m[1]) ParS = Particle('ParS', S, m[2]) ``` ```python FL = [(P, m[0] * g * N.x), (R, m[1] * g * N.x), (S, m[2] * g * N.x)] ``` ```python # Calculate the lagrangian, and form the equations of motion Lag = Lagrangian(N, ParP, ParR, ParS) LM = LagrangesMethod(Lag, q, forcelist=FL, frame=N) lag_eqs = LM.form_lagranges_equations() ``` ```python lag_eqs.simplify() lag_eqs ``` $\displaystyle \left[\begin{matrix}l_{0} \left(g m_{0} \sin{\left(\operatorname{q_{0}}{\left(t \right)} \right)} + g m_{1} \sin{\left(\operatorname{q_{0}}{\left(t \right)} \right)} + g m_{2} \sin{\left(\operatorname{q_{0}}{\left(t \right)} \right)} + l_{0} m_{0} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} + l_{0} m_{1} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} + l_{0} m_{2} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} + l_{1} m_{1} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{1}}{\left(t \right)}\right)^{2} + l_{1} m_{1} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{1}}{\left(t \right)} + l_{1} m_{2} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{1}}{\left(t \right)}\right)^{2} + l_{1} m_{2} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{1}}{\left(t \right)} + l_{2} m_{2} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{2}}{\left(t \right)}\right)^{2} + l_{2} m_{2} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{2}}{\left(t \right)}\right)\\l_{1} \left(g m_{1} \sin{\left(\operatorname{q_{1}}{\left(t \right)} \right)} + g m_{2} \sin{\left(\operatorname{q_{1}}{\left(t \right)} \right)} - l_{0} m_{1} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{0}}{\left(t \right)}\right)^{2} + l_{0} m_{1} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} - l_{0} m_{2} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{0}}{\left(t \right)}\right)^{2} + l_{0} m_{2} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{1}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} + l_{1} m_{1} \frac{d^{2}}{d t^{2}} \operatorname{q_{1}}{\left(t \right)} + l_{1} m_{2} \frac{d^{2}}{d t^{2}} \operatorname{q_{1}}{\left(t \right)} + l_{2} m_{2} \sin{\left(\operatorname{q_{1}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{2}}{\left(t \right)}\right)^{2} + l_{2} m_{2} \cos{\left(\operatorname{q_{1}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{2}}{\left(t \right)}\right)\\l_{2} m_{2} \left(g \sin{\left(\operatorname{q_{2}}{\left(t \right)} \right)} - l_{0} \sin{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{0}}{\left(t \right)}\right)^{2} + l_{0} \cos{\left(\operatorname{q_{0}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{0}}{\left(t \right)} - l_{1} \sin{\left(\operatorname{q_{1}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \left(\frac{d}{d t} \operatorname{q_{1}}{\left(t \right)}\right)^{2} + l_{1} \cos{\left(\operatorname{q_{1}}{\left(t \right)} - \operatorname{q_{2}}{\left(t \right)} \right)} \frac{d^{2}}{d t^{2}} \operatorname{q_{1}}{\left(t \right)} + l_{2} \frac{d^{2}}{d t^{2}} \operatorname{q_{2}}{\left(t \right)}\right)\end{matrix}\right]$ ```python ```
[STATEMENT] lemma mask_power_eq: "(x AND mask n) ^ k AND mask n = x ^ k AND mask n" for x :: \<open>'a::len word\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x AND mask n) ^ k AND mask n = x ^ k AND mask n [PROOF STEP] using word_of_int_Ex [where x=x] [PROOF STATE] proof (prove) using this: \<exists>y. x = word_of_int y goal (1 subgoal): 1. (x AND mask n) ^ k AND mask n = x ^ k AND mask n [PROOF STEP] unfolding take_bit_eq_mask [symmetric] [PROOF STATE] proof (prove) using this: \<exists>y. x = word_of_int y goal (1 subgoal): 1. take_bit n (take_bit n x ^ k) = take_bit n (x ^ k) [PROOF STEP] by (transfer; simp add: take_bit_eq_mod mod_simps)+
// Copyright 2008-2010 Gordon Woodhull // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/msm/mpl_graph/breadth_first_search.hpp> #include <boost/msm/mpl_graph/adjacency_list_graph.hpp> #include <boost/msm/mpl_graph/incidence_list_graph.hpp> #include <iostream> namespace mpl_graph = boost::msm::mpl_graph; namespace mpl = boost::mpl; // vertices struct A{}; struct B{}; struct C{}; struct D{}; struct E{}; struct F{}; struct G{}; // edges struct A_B{}; struct B_C{}; struct C_D{}; struct C_E{}; struct C_F{}; struct B_F{}; /* incidence list test graph: A -> B -> C -\--> D \ |--> E \ \--> F \-----/ */ typedef mpl::vector<mpl::vector<A_B,A,B>, mpl::vector<B_C,B,C>, mpl::vector<C_D,C,D>, mpl::vector<C_E,C,E>, mpl::vector<C_F,C,F>, mpl::vector<B_F,B,F> > some_incidence_list; typedef mpl_graph::incidence_list_graph<some_incidence_list> some_incidence_list_graph; /* adjacency list test graph: A -> B -> C -\--> D \ |--> E \ \--> F \-----/ G */ typedef mpl::vector< mpl::pair<A, mpl::vector<mpl::pair<A_B, B> > >, mpl::pair<B, mpl::vector<mpl::pair<B_C, C>, mpl::pair<B_F, F> > >, mpl::pair<C, mpl::vector<mpl::pair<C_D, D>, mpl::pair<C_E, E>, mpl::pair<C_F, F> > >, mpl::pair<G, mpl::vector<> > > some_adjacency_list; typedef mpl_graph::adjacency_list_graph<some_adjacency_list> some_adjacency_list_graph; struct preordering_visitor : mpl_graph::bfs_default_visitor_operations { template<typename Vertex, typename Graph, typename State> struct discover_vertex : mpl::push_back<State, Vertex> {}; }; struct postordering_visitor : mpl_graph::bfs_default_visitor_operations { template<typename Vertex, typename Graph, typename State> struct finish_vertex : mpl::push_back<State, Vertex> {}; }; struct examine_edge_visitor : mpl_graph::bfs_default_visitor_operations { template<typename Edge, typename Graph, typename State> struct examine_edge : mpl::push_back<State, Edge> {}; }; struct tree_edge_visitor : mpl_graph::bfs_default_visitor_operations { template<typename Edge, typename Graph, typename State> struct tree_edge : mpl::push_back<State, Edge> {}; }; // adjacency list tests // preordering, start from A typedef mpl::first<mpl_graph:: breadth_first_search<some_adjacency_list_graph, preordering_visitor, mpl::vector<>, A>::type>::type preorder_adj_a; BOOST_MPL_ASSERT(( mpl::equal<preorder_adj_a::type, mpl::vector<A,B,C,F,D,E> > )); // examine edges, start from A typedef mpl::first<mpl_graph:: breadth_first_search<some_adjacency_list_graph, examine_edge_visitor, mpl::vector<>, A>::type>::type ex_edges_adj_a; BOOST_MPL_ASSERT(( mpl::equal<ex_edges_adj_a::type, mpl::vector<A_B,B_C,B_F,C_D,C_E,C_F> > )); // tree edges, start from A typedef mpl::first<mpl_graph:: breadth_first_search<some_adjacency_list_graph, tree_edge_visitor, mpl::vector<>, A>::type>::type tree_edges_adj_a; BOOST_MPL_ASSERT(( mpl::equal<tree_edges_adj_a::type, mpl::vector<A_B,B_C,B_F,C_D,C_E> > )); // preordering, search all, default start node (first) typedef mpl::first<mpl_graph:: breadth_first_search_all<some_adjacency_list_graph, preordering_visitor, mpl::vector<> >::type>::type preorder_adj; BOOST_MPL_ASSERT(( mpl::equal<preorder_adj::type, mpl::vector<A,B,C,F,D,E,G> > )); // postordering, starting at A (same as preordering because BFS fully processes one vertex b4 moving to next) typedef mpl::first<mpl_graph:: breadth_first_search<some_adjacency_list_graph, postordering_visitor, mpl::vector<>, A>::type>::type postorder_adj_a; BOOST_MPL_ASSERT(( mpl::equal<postorder_adj_a::type, mpl::vector<A,B,C,F,D,E> > )); // postordering, default start node (same as preordering because BFS fully processes one vertex b4 moving to next) typedef mpl::first<mpl_graph:: breadth_first_search_all<some_adjacency_list_graph, postordering_visitor, mpl::vector<> >::type>::type postorder_adj; BOOST_MPL_ASSERT(( mpl::equal<postorder_adj::type, mpl::vector<A,B,C,F,D,E,G> > )); // preordering starting at C typedef mpl::first<mpl_graph:: breadth_first_search<some_adjacency_list_graph, preordering_visitor, mpl::vector<>, C>::type>::type preorder_adj_from_c; BOOST_MPL_ASSERT(( mpl::equal<preorder_adj_from_c::type, mpl::vector<C,D,E,F> > )); // preordering, search all, starting at C typedef mpl::first<mpl_graph:: breadth_first_search_all<some_adjacency_list_graph, preordering_visitor, mpl::vector<>, C>::type>::type preorder_adj_from_c_all; BOOST_MPL_ASSERT(( mpl::equal<preorder_adj_from_c_all::type, mpl::vector<C,D,E,F,A,B,G> > )); // incidence list tests // preordering, start from A typedef mpl::first<mpl_graph:: breadth_first_search<some_incidence_list_graph, preordering_visitor, mpl::vector<>, A>::type>::type preorder_inc_a; BOOST_MPL_ASSERT(( mpl::equal<preorder_inc_a::type, mpl::vector<A,B,C,F,D,E> > )); // preordering, start from C typedef mpl::first<mpl_graph:: breadth_first_search<some_incidence_list_graph, preordering_visitor, mpl::vector<>, C>::type>::type preorder_inc_c; BOOST_MPL_ASSERT(( mpl::equal<preorder_inc_c::type, mpl::vector<C,D,E,F> > )); // preordering, default start node (first) typedef mpl::first<mpl_graph:: breadth_first_search_all<some_incidence_list_graph, preordering_visitor, mpl::vector<> >::type>::type preorder_inc; BOOST_MPL_ASSERT(( mpl::equal<preorder_inc::type, mpl::vector<A,B,C,F,D,E> > )); // postordering, default start node typedef mpl::first<mpl_graph:: breadth_first_search_all<some_incidence_list_graph, postordering_visitor, mpl::vector<> >::type>::type postorder_inc; BOOST_MPL_ASSERT(( mpl::equal<postorder_inc::type, mpl::vector<A,B,C,F,D,E> > )); // preordering, search all, starting at C typedef mpl::first<mpl_graph:: breadth_first_search_all<some_incidence_list_graph, preordering_visitor, mpl::vector<>, C>::type>::type preorder_inc_from_c; BOOST_MPL_ASSERT(( mpl::equal<preorder_inc_from_c::type, mpl::vector<C,D,E,F,A,B> > )); int main() { return 0; }
library(tidyverse) library(igraph) partes_tesis <- tibble::tribble( ~codigo, ~x, ~y, ~nodo_desc, ~tarea, ~origen, ~detalle, "h1", 1, 5, "La red agregada total (desde 1996 a 2016) es de mundo pequeño puesto que es una característica presente en la mayoría de las redes de coautorías científicas.", "hipotesis", "Plan tesis", "mundo pequenio y libre escala", "h2", 1, 10, "La cantidad de autores aumenta en el tiempo debido al crecimiento de la disciplina en el país, lo que se refleja en un aumento en la cantidad de nodos en la red.", "hipotesis", "Plan tesis", "cuidado con crecimiento de disciplina", "h3", 1, 15, "Los autores fundadores se refuerzan en el tiempo, lo cual se verá reflejado en mayores medidas de grado, intermediación y fuerza de colaboración.", "hipotesis", "Plan tesis", "verificar en diferentes T las metricas.", "h4", 1, 20, "Los componentes más grandes absorben a los más pequeños a lo largo del tiempo, dado que autores periféricos pasan a trabajar en conjunto con autores principales.", "hipotesis", "Plan tesis", "si se abosrben componentes en tiempo, los links que se generan.", "t1", 3, 1, "Desambiguación de nombres de autor, se considera un proceso necesario para el armado de la base de datos. Esto puede verse reflejado en el trabajo de Morel et al. (2009) [ 9 ] y una fundamentación más extensa de por qué realizar esta tarea se observa en el trabajo de Tang (2010) [ 10 ]", "tarea", "kumar", "--", "t2", 3, 3, "Visualización de la red. Se plantea tener diferentes puntos de vista que pueden ayudar con el análisis de la red complementario a las métricas.", "tarea", "kumar", "--", "t3", 3, 5, "Análisis de mundo pequeño y red de libre escala (Small World & scale free) para la red agregada total y para cada instante temporal, para poder comparar la red obtenida con simulaciones basadas en sus particularidades.", NA, "kumar", "--", "t4", 3, 7, "El tamaño del componente gigante y su evolución en el tiempo. Este análisis brinda la posibilidad de ver qué tan cohesiva o fragmentada es la red.", "tarea", "kumar", "--", "t5", 3, 9, "El componente gigante podría significar la principal actividad de investigación; mientras que los otros componentes pueden ser agrupamientos especializados o sub-comunidades. (Fatt et al., 2010) [ 8 ]", "tarea", "kumar", "--", "t6", 3, 11, "Búsqueda de Comunidades. Este análisis permite evaluar la ubicación e interacciones entre los distintos grupos de investigación dentro de la red y buscarles un sentido a las comunidades dentro del contexto de la disciplina.", "tarea", "koseglu", "--", "t7", 3, 13, "Métricas generales a fin de analizar por períodos de agregación y la red completa. De las métricas que se tendrán en cuenta se destacan: (a) artículos con más de un autor, (b) autores que participan en artículos con más de un autor, (c) índice de colaboración, siendo este último una relación entre las medidas (b) / (c)", "tarea", "koseglu", "--", "t8", 3, 15, "Patrones de autoría, es decir, cuántos artículos por cantidad de autores existen en los diferentes periodos, dejando expuesto cuantos participan individualmente, en colaboración de a 2 autores, o más. Este análisis es útil para evaluar si existen tendencias de mayor trabajo en equipo a lo largo del tiempo.", "tarea", "koseglu", "--", "t9", 3, 17, "Comparación con otras redes de coautoría realizadas en otros trabajos utilizando métricas que están presentes en todos ellos por ejemplo: (a) artículos por autor, (b) coeficiente de clustering (transitividad), (c) tamaño del componente principal, (d) componente principal representado en porcentaje, y (e) distancia media.", "tarea", "koseglu", "--", "s1", 5, 1, "Capitulo 1: introduccion", "seccion tesis", "Escritura – tesis", "Establecer contexto, plantear problema, plantear plan de solucion, pie a capitulo 2", "s2", 5, 3, "Capitulo 2: generacion Datos", "seccion tesis", "Escritura – tesis", "intro de capitulo, materiales y metodos, resultados de procesos, resumen, pie al 3", "s3", 5, 5, "Capitulo 3: generacion herramienta", "seccion tesis", "Escritura – tesis", "intro del capitulo, materiales y metodos, resumen del capitulo, pie al 4", "s4", 5, 7, "Capitulo 4: analisis de red de coautoria", "seccion tesis", "Escritura – tesis", "intro del capitulo contestar hipotesis. Contestar objetivos. Resumen capitulo pie al 5", "s5", 5, 9, "Capitulo 5: discucion & cierre", "seccion tesis", "Escritura – tesis", "Intro, discucion, cierre, trabajos futuros. Agradecimientos.", "s6", 5, 11, "ANEXO: software y librerías utilizadas", "seccion tesis", "Escritura – tesis", "creditos al software", "s7", 5, 13, "ANEXO: Detalle estandarización autores", "seccion tesis", "Escritura – tesis", "detalle de como se realizo la estandarizacion de autores", "s8", 5, 15, "ANEXO: Detalle consideraciones PDF", "seccion tesis", "Escritura – tesis", "detalle de los pdf\\", "s9", 5, 17, "ANEXO: Detalle procesamiento bibTEX", "seccion tesis", "Escritura – tesis", "detalle de los bibtex", "s10", 5, 19, "ANEXO: Detalle de algoritmos para búsqueda de comunidades", "seccion tesis", "Escritura – tesis", "detalle de algoritmos para la busqueda de comunidades", "a1", 7, 1, "cosideraciones: generales", "seccion app", "desarrollo app", "consideraciones", "a2", 7, 3, "consideraciones: EDA", "seccion app", "desarrollo app", "analisis exploratorio", "a3", 7, 5, "analisis estatico: visualizacion", "seccion app", "desarrollo app", "visualizacion", "a4", 7, 7, "analisis estatico: articulos asociados", "seccion app", "desarrollo app", "datos crudos", "a5", 7, 9, "analisis estatico: estructura red", "seccion app", "desarrollo app", "estructura grafo", "a6", 7, 11, "analisis estatico: comparacion modelos", "seccion app", "desarrollo app", "modelos", "a7", 7, 13, "analisis estatico: comunidades", "seccion app", "desarrollo app", "comunidades", "a8", 7, 15, "analisis temporal: visualizacion dinamica", "seccion app", "desarrollo app", "temporal evolucion", "a9", 7, 17, "analisis temporal: metricas red por anio", "seccion app", "desarrollo app", "metricas anuales", "a10", 7, 19, "analisis temporal: metricas red acumuladas", "seccion app", "desarrollo app", "metricas acumuladas", "a11", 7, 21, "analisis temporal: metricas nodos top N tiempo", "seccion app", "desarrollo app", "metricas top n", "a12", 7, 23, "analisis temporal: metricas nodos top N tiempo acumuladas", "seccion app", "desarrollo app", "metricas top n totales" ) grafo_vacio <- make_empty_graph(n = 0, directed = FALSE) hipotesis <- partes_tesis %>% filter(str_detect(codigo,pattern = 'h')) %>% pull(codigo) tareas <- partes_tesis %>% filter(str_detect(codigo,pattern = 't')) %>% pull(codigo) secciones <- partes_tesis %>% filter(str_detect(codigo,pattern = 's')) %>% pull(codigo) grafo_resultado <- grafo_vacio + igraph::vertices(hipotesis,color='red') + igraph::vertices(tareas,color='blue') + igraph::vertices(secciones,color='green') degree(grafo_resultado) visNetwork::visIgraph(grafo_resultado)
SplitString("Hello,How,Are,You,Today", ","); # [ "Hello", "How", "Are", "You", "Today" ] JoinStringsWithSeparator(last, "."); # "Hello.How.Are.You.Today"
We are delighted to offer the Café No.8 experience at the nearby York Art Gallery in partnership with the York Museums Trust. Enjoy a fabulous al fresco experience in our outdoor seating area, overlooking the beautiful fountain to the front of the Gallery on Exhibition Square. Glance up to see York Theatre Royal, Petergate and the adjoining City Walls, and, of course, the magnificent York Minster. We are a family friendly café and are able to provide high chairs on request. As well as a child-friendly menu at low prices, we also offer our younger visitors colouring pads and crayons so they can take inspiration from their surroundings and explore their creative side. We run drawing and colouring competitions throughout the year with prizes on offer! Just ask our staff for more information or look out for posters during your visit.
program IfstTC; {sample25t} var ch:char;int:integer;boolx,booly:boolean; begin boolx:=true;booly:=false;ch:='a';int:=66; write(integer(ch));write(integer(int));write(integer(boolx),integer(booly)); writeln; writeln(char(ch),char(int));writeln(boolean(ch),integer(int),integer(boolx), integer(booly));end.
Before the turkey has been in the fridge long enough to be called a leftover, many families will hit their favorite retailer ready to strike a deal on Black Friday. For the experienced Black Friday shopper, this official start to the holiday shopping season is a welcome challenge full of its own tradition. In fact, the National Retail Federation reported in its 2015 Thanksgiving weekend survey that tradition was the second-most-popular reason consumers braved the Black Friday crowds to shop in a brick-and-mortar store. But there is one motivator that surpassed tradition to bring out shoppers on the day after Thanksgiving: The deals were too good to pass up. About half of Black Friday shoppers showed up for the deals, and April Gilman — a Philadelphia, Pa. resident with a penchant for deals — has been one of them for the last 15 to 20 years. The fact that there are shoppers looking for deals on Black Friday is hardly a surprise; however, the survey showed that the way they are finding these deals is changing. Whether consumers are shopping in-store or online, technology is influencing the process. If you’re looking for tips to master Black Friday Shopping, you can learn from the tech-savvy habits of these experienced deal-finders. Based on the habits of those surveyed, here are some suggestions for using your smartphone or tablet to improve your in-person shopping experience. While sale circulars were the most popular research tool, almost a third of those surveyed last year planned their trip by doing an online search. Retailers keep a close eye on their competition during Thanksgiving weekend, so you never know when a last-minute deal will be introduced. The highest level of smartphone activity on Black Friday — even higher than online purchasing — was researching products and comparing prices. When you’re in a crowd of competitive shoppers, it’s not very convenient to stop and read every detail on the box. But it might be worth an extra minute to do a quick search from the store to make sure you’re truly getting the lowest price. Coupon redemption was also a common use of smartphones in 2015. Several digital coupon apps with built-in GPS technology are available for iPhones and Android devices. If you’re near a store with a coupon or special sale, most of these apps will send you a push notification. Some even let you set the app to check your favorite stores. Sometimes retailers limit their inventory of deeply discounted products and a great deal will go fast. Many store websites allow you to enter your zip code to check in-store availability of an item before you go. This way, you don’t waste time looking for a product that was advertised nationally but wasn’t stocked at your local store. These practical tips, combined with the advantages of technology, can help you master Black Friday shopping like a pro.
I have had a similar experience with precut strips. I no longer assume they are accurate or straight! I think your outcome is really nice though! I've had at least one jelly roll that did that to me. I like to cut my own now. :) You did a marvelous job of not only finishing the flimsy, but turning it into something equally as interesting as the original pattern. If it were me, I'd use the leftover blocks somehow in the backing, just to get rid of them. I know how good it feels to finish up something I am very tired of looking at. Great job, and very creative! I remember that debacle! It had me afraid to buy strip sets for years, but I've passed that. I was also thinking "lemonade." I think keeping those frustrating pieces was good, because those ombre colors look so good up there! Great quilt! Love what you finally arrived at, very creative play. I haven't been happy with a couple of layer cakes too not being true squares and not cut on the true grain. You made a great job of rescuing the blocks. Your new flimsy looks fantastic!! Great job!! Sandy, You are amazing. That was an eye grabbing finish to that less than perfect cut of a jellyroll. It really looks great. I'm getting back on line so stop by sometime. Looking forward to being with you at retreat ....really soon. Will send out info soon.
-- A DSL example in the language Agda: "polynomial types" module TypeDSL where open import Data.Empty open import Data.Unit open import Data.Sum open import Data.Product open import Data.Nat data E : Set1 where Add : E -> E -> E Mul : E -> E -> E Zero : E One : E eval : E -> Set eval (Add x y) = (eval x) ⊎ (eval y) eval (Mul x y) = (eval x) × (eval y) eval Zero = ⊥ eval One = ⊤ two = Add One One three = Add One two test1 : eval One test1 = tt false : eval two false = inj₁ tt true : eval two true = inj₂ tt test3 : eval three test3 = inj₁ tt card : E -> ℕ card (Add x y) = card x + card y card (Mul x y) = card x * card y card Zero = 0 card One = 1 open import Data.Vec as V variable m n : ℕ A B : Set enumAdd : Vec A m -> Vec B n -> Vec (A ⊎ B) (m + n) enumAdd xs ys = V.map inj₁ xs ++ V.map inj₂ ys -- cartesianProduct enumMul : Vec A m → Vec B n → Vec (A × B) (m * n) enumMul xs ys = concat (V.map (\a -> V.map ((a ,_)) ys) xs) enumerate : (t : E) -> Vec (eval t) (card t) enumerate (Add x y) = enumAdd (enumerate x) (enumerate y) enumerate (Mul x y) = enumMul (enumerate x) (enumerate y) enumerate Zero = [] enumerate One = [ tt ] test : Vec (eval three) 3 test = enumerate three -- inj₁ tt ∷ inj₂ (inj₁ tt) ∷ inj₂ (inj₂ tt) ∷ [] -- Exercise: add a constructor for function types to the syntax E
%% AMPL Install for OPTI Toolbox % Supplied binaries are built from Netlib's AMPL Solver Library Interface % Copyright (C) 2011 Jonathan Currie (I2C2) % This file will help you compile AMPL Solver Library (ASL) for use with % MATLAB. % My build platform: % - Windows 8 x64 % - Visual Studio 2012 % 1) Get AMPL Solver Library % The generic NL reader for AMPL is available free from Netlib % (http://www.netlib.org/ampl/solvers/). You will need to download all .c % and .h as well as .hd files. Note this is not the AMPL engine % (www.ampl.com) which is a commerical product, but code to allow people to % connect their solvers to AMPL. Alternatively send a blank email to % "[email protected]" with "send all from ampl/solvers" as the subject to % retrieve all files. % 2) Compile ASL % The easiest way to compile ASL is to use the Visual Studio Project % Builder included with OPTI. Use the following commands, substituting the % required path on your computer: % %% Visual Studio Builder Commands % path = 'full path to ASL here'; %e.g. 'C:\Solvers\ASL' % sdir = path; % name = 'libasl'; % opts = []; % opts.exPP = {'Arith_Kind_ASL=1','Sscanf=sscanf','Printf=printf','Sprintf=sprintf',... % 'Fprintf=fprintf','snprintf=_snprintf','NO_STDIO1','_CRT_SECURE_NO_WARNINGS','_CRT_NONSTDC_NO_DEPRECATE'}; % opts.exclude = {'arithchk.c','atof.c','b_search.c','dtoa.c','fpinit.c','funcadd.c',... % 'funcadd0.c','funcaddk.c','funcaddr.c','obj_adj0.c','sjac0dim.c',... % 'sprintf.c','sscanf.c','printf.c','mpec_adj0.c'}; % opts.charset = 'MultiByte'; % VS_WriteProj(sdir,name,[],opts) % %% % Once complete, you will have a directory called ASL\libasl. Open the % Visual Studio 2012 project file, then complete the following steps: % a) Rename arith.h0 to arith.h, and uncomment the define "IEEE_8087" % b) Rename stdio1.h0 to stdio1.h % c) Under project properties change the character set to "Use % Multi-Byte Character Set" (both Win32 and x64 as required). % d) Comment out the line "exit(n)" in mainexit.c (this stops MATLAB % crashing on an ASL error) [line 62] % e) To prevent Matlab crashing on a bad NL file comment all code under % the if(n_con < 0 || ...) statement on line 260 in jac0dim.c. Add return % NULL; so instead of exiting, our MEX file can determine this as a bad file. % f) Comment line 900 in asl.h (extern int Sprintf(char*, ....) % g) Comment line 36 in jac0dim.c (extern int Sscanf(char*, ...) % h) Comment line 56 in stderr.c (AllocConsole();) % i) Build a Win32 or x64 Release to compile the code. % j) Copy the generated .lib file to the following folder: % % OPTI/Utilities/File IO/Source/lib/win32 or win64 % % Also copy all header files to the include directory as per the above % path. % 3) MEX Interface % The Read MEX Interface is a simple MEX interface I wrote to use the AMPL % File IO and Eval routines. % 4) Compile the MEX File % The code below will automatically include all required libraries and % directories to build the MEX file. Once you have completed all % the above steps, simply run this file to compile! You MUST BE in % the base directory of OPTI! clear asl % Get Arch Dependent Library Path libdir = opti_GetLibPath(); fprintf('\n------------------------------------------------\n'); fprintf('AMPL MEX FILE INSTALL\n\n'); post = [' -IInclude -L' libdir ' -llibasl -DNO_STDIO1 -output asl']; %CD to Source Directory cdir = cd; cd 'Utilities/File IO/Source'; %Compile & Move pre = 'mex -v -largeArrayDims amplmex.c'; try eval([pre post]) movefile(['asl.' mexext],'../','f') fprintf('Done!\n'); catch ME cd(cdir); error('opti:ampl','Error Compiling AMPL!\n%s',ME.message); end cd(cdir); fprintf('------------------------------------------------\n');
Require Import Omega. Require Import Coq.Lists.List. Import ListNotations. From q3_2001 Require Export misc. (* TODO Retire in favour of largest_elt? *) Definition nat_list_max (l : list nat) : nat := fold_right max 0 l. Lemma nat_list_max_spec_0 : forall m l, m <= nat_list_max (m::l). Proof. intros. simpl. apply Nat.le_max_l. Qed. Lemma nat_list_max_spec_1 : forall m l, nat_list_max l <= nat_list_max (m::l). Proof. intros. simpl. fold nat_list_max. apply Nat.le_max_r. Qed. Lemma nat_list_max_spec_2 : forall (l : list nat), l <> [] -> In (nat_list_max l) l. Proof. intros l Hl. generalize dependent l. induction l as [| x l IHl]; try contradiction. destruct (Nat.max_spec_le x (nat_list_max l)) as [[Hmax Hmax'] | [Hmax Hmax']]; intros H; simpl; rewrite Hmax'. + destruct (list_empty_dec l) as [Hl' | Hl']. * left. subst. simpl. simpl in Hmax. omega. * right. apply IHl in Hl'. apply Hl'. + left. reflexivity. Qed. Lemma nat_list_max_spec_3 : forall (l : list nat) (m : nat), In m l -> m <= nat_list_max l. Proof. intros l m Hm. induction l as [| x l IHl]; try contradiction. destruct Hm as [H | H]. - subst. apply nat_list_max_spec_0. - apply IHl in H. pose (H' := (nat_list_max_spec_1 x l)). omega. Qed. Lemma nat_list_max_spec_4 : forall (l : list nat), nat_list_max l = 0 <-> (forall x, In x l -> x = 0). Proof. intros l. split. - intros H x Hx. apply nat_list_max_spec_3 in Hx. rewrite H in Hx. omega. - intros H. destruct (list_empty_dec l) as [Hl | Hl]. + rewrite Hl. auto. + apply nat_list_max_spec_2 in Hl. apply H in Hl. assumption. Qed.
theory Searching_In_Lists imports Main begin fun first_pos :: "('a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> nat" where "first_pos _ Nil = 0" | \<open>first_pos f (Cons x xs) = (if f x then 0 else 1 + first_pos f xs)\<close> value "first_pos (\<lambda>x. x = (3 :: nat)) [1::nat, 3, 5, 3, 1]" value "first_pos (\<lambda>x. x \<ge> 4) [1::nat, 3, 5, 7]" value "first_pos (\<lambda>x. size x > 1) [[], [1::nat, 2], [3]]" lemma "(first_pos P xs = size xs) = (\<forall> x \<in> set xs. \<not>(P x))" by(induct xs, auto) lemma "list_all (\<lambda>x. \<not>P x) (take (first_pos P xs) xs)" by(induct xs, auto) lemma "first_pos (\<lambda>x. P x \<or> Q x) xs = min (first_pos P xs) (first_pos Q xs)" by(induction xs, auto) lemma "first_pos (\<lambda>x. P x \<and> Q x) xs \<ge> max (first_pos P xs) (first_pos Q xs)" by(induction xs, auto) lemma assumes "\<forall>x. (P x \<longrightarrow> Q x)" shows "first_pos P xs < length xs \<longrightarrow> first_pos Q xs < length xs" using assms by (induction xs, auto) fun count :: "('a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> nat" where "count _ Nil = 0" | "count f (Cons x xs) = (if f x then 1 else 0) + count f xs" print_theorems lemma count_concat_split: "count f (xs @ ys) = count f xs + count f ys" by(induct xs, auto) lemma "count f xs = count f (rev xs)" by(induct xs, auto simp add: count_concat_split) lemma "length (filter f xs) = count f xs" by(induct xs, auto) end
#Snippets and Programs from Chapter 5: Playing with Sets and Probability ```python %matplotlib inline ``` ```python #P125: Finding the power set of a set >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2, 3) >>> ps = s.powerset() >>> ps ``` {EmptySet(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}} ```python #P126: Union of two Sets >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2, 3) >>> t = FiniteSet(2, 4, 6) >>> s.union(t) {1, 2, 3, 4, 6} ``` {1, 2, 3, 4, 6} ```python #P127: Intersection of two Sets >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2) >>> t = FiniteSet(2, 3) >>> s.intersect(t) ``` {2} ```python #P127/128: Cartesian product of two Sets >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2) >>> t = FiniteSet(3, 4) >>> p = s*t >>> for elem in p: print(elem) ``` (1, 3) (1, 4) (2, 3) (2, 4) ```python #P130: Different gravity, different results from sympy import FiniteSet, pi def time_period(length, g): T = 2*pi*(length/g)**0.5 return T if __name__ == '__main__': L = FiniteSet(15, 18, 21, 22.5, 25) g_values = FiniteSet(9.8, 9.78, 9.83) print('{0:^15}{1:^15}{2:^15}'.format('Length(cm)', 'Gravity(m/s^2)', 'Time Period(s)')) for elem in L*g_values: l = elem[0] g = elem[1] t = time_period(l/100, g) print('{0:^15}{1:^15}{2:^15.3f}'.format(float(l), float(g), float(t))) ``` Length(cm) Gravity(m/s^2) Time Period(s) 15.0 9.78 0.778 15.0 9.8 0.777 15.0 9.83 0.776 18.0 9.78 0.852 18.0 9.8 0.852 18.0 9.83 0.850 21.0 9.78 0.921 21.0 9.8 0.920 21.0 9.83 0.918 22.5 9.78 0.953 22.5 9.8 0.952 22.5 9.83 0.951 25.0 9.78 1.005 25.0 9.8 1.004 25.0 9.83 1.002 ```python #P132: Probability of a Prime number appearing when a 20-sided dice is rolled def probability(space, event): return len(event)/len(space) def check_prime(number): if number != 1: for factor in range(2, number): if number % factor == 0: return False else: return False return True if __name__ == '__main__': space = FiniteSet(*range(1, 21)) primes = [] for num in space: if check_prime(num): primes.append(num) event= FiniteSet(*primes) p = probability(space, event) print('Sample space: {0}'.format(space)) print('Event: {0}'.format(event)) print('Probability of rolling a prime: {0:.5f}'.format(p)) ``` Sample space: {1, 2, 3, ..., 18, 19, 20} Event: {2, 3, 5, 7, 11, 13, 17, 19} Probability of rolling a prime: 0.40000 ```python #P134: Probability of event A or event B >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2, 3, 4, 5, 6) >>> a = FiniteSet(2, 3, 5) >>> b = FiniteSet(1, 3, 5) >>> e = a.union(b) >>> len(e)/len(s) ``` 0.6666666666666666 ```python #P134: Probability of event A and event B >>> from sympy import FiniteSet >>> s = FiniteSet(1, 2, 3, 4, 5, 6) >>> a = FiniteSet(2, 3, 5) >>> b = FiniteSet(1, 3, 5) >>> e = a.intersect(b) >>> len(e)/len(s) ``` 0.3333333333333333 ```python #P135: Can you Roll that score? ''' Roll a die until the total score is 20 ''' import matplotlib.pyplot as plt import random target_score = 20 def roll(): return random.randint(1, 6) if __name__ == '__main__': score = 0 num_rolls = 0 while score < target_score: die_roll = roll() num_rolls += 1 print('Rolled: {0}'.format(die_roll)) score += die_roll print('Score of {0} reached in {1} rolls'.format(score, num_rolls)) ``` Rolled: 5 Rolled: 4 Rolled: 2 Rolled: 5 Rolled: 2 Rolled: 6 Score of 24 reached in 6 rolls ```python #P136: Is the target score possible? from sympy import FiniteSet import random def find_prob(target_score, max_rolls): die_sides = FiniteSet(1, 2, 3, 4, 5, 6) # sample space s = die_sides**max_rolls # Find the event set if max_rolls > 1: success_rolls = [] for elem in s: if sum(elem) >= target_score: success_rolls.append(elem) else: if target_score > 6: success_rolls = [] else: success_rolls = [] for roll in die_sides: if roll >= target_score: success_rolls.append(roll) e = FiniteSet(*success_rolls) # calculate the probability of reaching target score return len(e)/len(s) if __name__ == '__main__': target_score = int(input('Enter the target score: ')) max_rolls = int(input('Enter the maximum number of rolls allowed: ')) p = find_prob(target_score, max_rolls) print('Probability: {0:.5f}'.format(p)) ``` Enter the target score: 25 Enter the maximum number of rolls allowed: 5 Probability: 0.03241 ```python #P139: Simulate a fictional ATM ''' Simulate a fictional ATM that dispenses dollar bills of various denominations with varying probability ''' import random import matplotlib.pyplot as plt def get_index(probability): c_probability = 0 sum_probability = [] for p in probability: c_probability += p sum_probability.append(c_probability) r = random.random() for index, sp in enumerate(sum_probability): if r <= sp: return index return len(probability)-1 def dispense(): dollar_bills = [5, 10, 20, 50] probability = [1/6, 1/6, 1/3, 1/3] bill_index = get_index(probability) return dollar_bills[bill_index] # Simulate a large number of bill withdrawls if __name__ == '__main__': bill_dispensed = [] for i in range(10000): bill_dispensed.append(dispense()) # plot a histogram plt.hist(bill_dispensed) plt.show() ``` ```python #P140: Draw a Venn diagram for two sets ''' Draw a Venn diagram for two sets ''' from matplotlib_venn import venn2 import matplotlib.pyplot as plt from sympy import FiniteSet def draw_venn(sets): venn2(subsets=sets) plt.show() if __name__ == '__main__': s1 = FiniteSet(1, 3, 5, 7, 9, 11, 13, 15, 17, 19) s2 = FiniteSet(2, 3, 5, 7, 11, 13, 17, 19) draw_venn([s1, s2]) ```
Require Import List. Import ListNotations. Require Import LC.Util.Fin. Require Import LC.Util.Vec. Require Import LC.Util.Star. Inductive Term : nat -> Type := | Var : forall {n}, Fin n -> Term n | App : forall {n}, Term n -> Term n -> Term n | Lam : forall {n}, Term (S n) -> Term n. Infix "#" := App (left associativity, at level 40). Definition var {n} (i : nat) : Term (i + S n) := Var (Fin_of_nat i). Fixpoint weaken {n} (t : Term n) : Fin (S n) -> Term (S n) := match t with | Var j => fun i => Var (shift i j) | t1 # t2 => fun i => weaken t1 i # (weaken t2 i) | Lam t' => fun i => Lam (weaken t' (inr i)) end. Fixpoint subst {n} (t : Term (S n)) : Fin (S n) -> Term n -> Term n := match t in Term m return S n = m -> Fin (S n) -> Term n -> Term n with | Var j => fun pf i u => match pf with | eq_refl => fun j' => match avoid i j' with | Some k => Var k | None => u end end j | t1 # t2 => fun pf i u => match pf with | eq_refl => fun s1 s2 => subst s1 i u # subst s2 i u end t1 t2 | Lam t' => fun pf i u => match pf with | eq_refl => fun s => Lam (@subst (S n) s (inr i) (weaken u i)) end t' end eq_refl. Lemma subst_weaken {n} : forall (M N : Term n) (i : Fin (S n)), subst (weaken M i) i N = M. Proof. induction M; intros; simpl. - now rewrite avoid_shift. - now rewrite IHM1, IHM2. - now rewrite IHM. Qed. Inductive red : forall {n}, Term n -> Term n -> Prop := | beta_red : forall {n} (t : Term (S n)) (u : Term n), red (Lam t # u) (subst t (inl tt) u) | app_red_l : forall {n} (t t' u : Term n), red t t' -> red (t # u) (t' # u) | app_red_r : forall {n} (t u u' : Term n), red u u' -> red (t # u) (t # u') | lam_red : forall {n} (t t' : Term (S n)), red t t' -> red (Lam t) (Lam t'). Definition reds {n} : Term n -> Term n -> Prop := star red. Lemma app_reds_l : forall {n} (t t' u : Term n), reds t t' -> reds (t # u) (t' # u). Proof. intros n t t' u r. induction r. { apply star_refl. } { eapply R_star. { apply app_red_l; eauto. } { auto. } } Qed. Lemma app_reds_r : forall {n} (t u u' : Term n), reds u u' -> reds (t # u) (t # u'). Proof. intros n t t' u r. induction r. { apply star_refl. } { eapply R_star. { apply app_red_r; eauto. } { auto. } } Qed. Lemma lam_reds : forall {n} (t t' : Term (S n)), reds t t' -> reds (Lam t) (Lam t'). Proof. intros n t t' r. induction r. { apply star_refl. } { eapply R_star. { apply lam_red; eauto. } { auto. } } Qed. Definition not_lam {n} (t : Term n) : Prop := match t with | Lam _ => False | _ => True end. Fixpoint normal {n} (t : Term n) : Prop := match t with | Var _ => True | App t1 t2 => not_lam t1 /\ normal t1 /\ normal t2 | Lam t' => normal t' end. Lemma normal_no_red : forall {n} (t t' : Term n), normal t -> ~ red t t'. Proof. intros n t t' norm_t red_tt'. induction red_tt'; simpl in norm_t; tauto. Qed. Lemma no_red_normal : forall {n} (t : Term n), (forall t', ~ red t t') -> normal t. Proof. intros n t. induction t; intros. - exact I. - simpl; repeat split. + destruct t1; [exact I|exact I|]. eapply H. apply beta_red. + apply IHt1. intros t' Hr. eapply H. apply app_red_l; eauto. + apply IHt2. intros t' Hr. eapply H. apply app_red_r; eauto. - apply IHt. intros t' Hr. eapply H. apply lam_red; eauto. Qed. Class Const (T : forall n, Term n) : Prop := { weaken_const : forall n i, weaken (T n) i = T (S n) }. Lemma subst_const {T} `{Const T} : forall n i U, subst (T (S n)) i U = T n. Proof. intros. rewrite <- (weaken_const _ i). now rewrite subst_weaken. Qed. Ltac beta := match goal with | [ |- red (Lam _ # _) _ ] => apply beta_red; simpl | [ |- red (Lam _) _ ] => apply lam_red; beta | [ |- red (_ # _) _ ] => first [ apply app_red_l; beta | apply app_red_r; beta ] | _ => fail end. Ltac normal_order := match goal with | [ |- reds _ _ ] => unfold reds; normal_order | [ |- star red _ _ ] => apply star_refl | [ |- context [ avoid ?t ?t ] ] => rewrite avoid_refl; normal_order | [ |- star red _ _ ] => eapply R_star; [ beta | simpl; repeat rewrite subst_const; repeat rewrite weaken_const; repeat rewrite subst_weaken ]; normal_order | _ => idtac end.
If $S$ is a complete metric space and $t$ is a closed subset of $S$, then $S \cap t$ is a complete metric space.
{-# OPTIONS --safe #-} module JVM.Compiler where open import JVM.Types open import JVM.Syntax.Instructions module _ 𝑭 where open import JVM.Compiler.Monad StackTy ⟨ 𝑭 ∣_↝_⟩ noop using (Compiler) public module _ {𝑭} where open import JVM.Compiler.Monad StackTy ⟨ 𝑭 ∣_↝_⟩ noop hiding (Compiler) public
f := function(x,y) local z, helper; z := 1 - y; helper := function(bla) return x + y*z - bla; end; return helper; end; x -> x + 1; {x,y} -> x + y + 1; Print("This is a string\n"); for n in [1..100] do for i in [1..NrSmallGroups(n)] do G := SmallGroup(n,i); Print("SmallGroup(", n, ",", i, ") is abelian? ", IsAbelian(G), "\n"); if IsPerfectGroup(G) = true then break; fi; od; od; BindGlobal("foo", 1); BIND_GLOBAL("bar", 2); r := rec( a := [1,2,3], b := true, c := fail, ); InstallImmediateMethod( IsFinitelyGeneratedGroup, IsGroup and HasGeneratorsOfGroup, function( G ) if IsFinite( GeneratorsOfGroup( G ) ) then return true; fi; TryNextMethod(); end );
Veronica is all what you want in a pug! Fun, lovable, wrinkles and more. She is very unique and has white on just the front tips of her feet. She is an angel from heaven who dipped her feet in the clouds. :) She will come home up to date on vaccinations and worming. Make her yours today! My Little Puppy is defined as a family-direct site. We work with families all over the country to help list and sell their puppies for them, so they can really focus on raising them. All of our puppies are backed by a 5 year health guarantee, and pet safe air transportation is already included in the list prices!
proposition homotopic_paths_eq: "\<lbrakk>path p; path_image p \<subseteq> s; \<And>t. t \<in> {0..1} \<Longrightarrow> p t = q t\<rbrakk> \<Longrightarrow> homotopic_paths s p q"