Datasets:
AI4M
/

text
stringlengths
0
3.34M
from __future__ import absolute_import import numpy as np import random from brainfuck.core import Instruction from . import brainfuck_common as common print_interval = 5 def preset_flags(FLAGS): FLAGS.max_length = 1 FLAGS.test_max_length = 1 FLAGS.input_dim = 8 + 1 + 3 + 1 + 2 # 13 + 2 code 8 nonzero 1 skip 3 direction 1 FLAGS.output_dim = 3 * (3 + 3 + 3 + 1 + 3) + 2 # 13 + 2 head 3 value 3 skip 3 direction 1 interaction 3 def run(ntm, seq_length, sess, idx=None, print_=True): return common.meta_run(ntm, seq_length, sess, generate_training_sequence=generate_training_sequence, idx=idx, seq_to_inst=seq_to_inst, print_=print_) def train(ntm, config, sess): return common.meta_train(ntm, config, sess, generate_training_sequence=generate_training_sequence) tf_set = [False, True] order = '><+-.,[]' def generate_training_sequence(length, config, idx=None): if not idx: idx = random.randint(0, 2 ** 30) context, instruction = common.context_products[idx % len(common.context_products)] token = context[0] if token is None: token = random.choice(order) token_id = order.index(token) nonzero = context[1] if nonzero is None: nonzero = random.choice(tf_set) skip = context[2] if skip is None: skip = random.choice((0, 1, 2)) direction = context[3] direction_id = direction > 0 seq_in = np.zeros([1, config.input_dim], dtype=np.float32) # marker 2 bits seq_in[0][2 + token_id] = 1 # token 8 bits -> 10 seq_in[0][10] = nonzero # nonzero 1 bit -> 11 seq_in[0][11 + skip] = 1 # skip 3 bits -> 14 seq_in[0][14] = direction_id direction_id = instruction.direction > 0 interaction_id = [None, 'i', 'o'].index(instruction.interaction) seq_out = np.zeros([1, config.output_dim], dtype=np.float32) idx = 2 subidx = (instruction.head_diff + 1) * 3 seq_out[0][idx + subidx:idx + subidx + 3] = 1 idx += 9 subidx = (instruction.value_diff + 1) * 3 seq_out[0][idx + subidx:idx + subidx + 3] = 1 idx += 9 subidx = (instruction.skip_diff + 1) * 3 seq_out[0][idx + subidx:idx + subidx + 3] = 1 idx += 9 seq_out[0][idx:idx + 3] = direction_id idx += 3 subidx = (interaction_id * 3) seq_out[0][idx + subidx:idx + subidx + 3] = 1 return (token, nonzero, skip, direction), instruction, list(seq_in), list(seq_out) def seq_to_inst(seq): bits = seq[0] def get_diff(base): diff = sorted([ (bits[base + 0:base + 3].sum(), -1), (bits[base + 3:base + 6].sum(), 2), (bits[base + 6:base + 9].sum(), 1), ], reverse=True)[0][1] if diff == 2: diff = 0 return diff head_diff = get_diff(2) value_diff = get_diff(11) skip_diff = get_diff(20) direction = 1 if bits[29:32].sum() > 1.5 else -1 interaction_id = get_diff(32) interaction = (interaction_id == 0 and 'i') or (interaction_id == 1 and 'o') or None instruction = Instruction(head_diff, value_diff, skip_diff, direction, interaction) return instruction
## LiDAR Basics with VLP-16 LIDAR—Light Detection and Ranging—is used to find the precise distance of objects in relation to us. Velodyne LiDAR sensors use time-of-flight methodology for doing this. When a laser pulse is emited, its time-of-shooting and direction are registered. The laser pulse travels through air until it hits an obstacle which reflects some of the energy. The time-of-acquisition and power received are registered by sensor after recieving the portion of energy. The spherical coordinates of the obstacle is calculated using time-of-acquisition which is returned along with power received(as relectance) after each scan. As LiDAR sensor returns reading in spherical coordinates, let's brush up with the spherical coordinate system. ___ To know more on LiDAR's history and how it works this [blog](https://news.voyage.auto/an-introduction-to-lidar-the-key-self-driving-car-sensor-a7e405590cff) by Oliver Cameron is helpful. ### Spherical Coordinate System In a spherical coordinate system, a point is defined by a distance and two angles. To represent the two angles we use azimuth($\theta$) and polar angle($\phi$) convention. Thus a point is defined by $(\text{r}, \theta, \phi)$. As you can see from above diagram, the azimuth angle is in X-Y plane measured from X-axis and polar angle is in Z-Y plane measured from Z axis. From above diagram, we can get the following equations for converting a cartesian coordinate to spherical coordinates. <math>\begin{align} r&=\sqrt{x^2 + y^2 + z^2} \\ \theta &= \arccos\frac{z}{\sqrt{x^2 + y^2 + z^2}} = \arccos\frac{z}{r} \\ \varphi &= \arctan \frac{y}{x} \end{align}</math> We can derive cartesian coordinates from spherical coordinates using below equations. <math>\begin{align} x&=r \, \sin\theta \, \cos\varphi \\ y&=r \, \sin\theta \, \sin\varphi \\ z&=r \, \cos\theta\end{align}</math> ___ Read [more](https://en.wikipedia.org/wiki/Spherical_coordinate_system) about Spherical coordinate system at Wikipedia. ## VLP-16 coordinate system Velodyne VLP-16 returns reading in spherical coordinates. But there is a slight difference from the above discussed convention. In sensor coordinate system, a point is defined by (radius $\text{r}$, elevation $\omega$, azimuth $\alpha$). Elevation angle, $\omega$ is in Z-Y plane measured from Y-axis. Azimuth angle, $\alpha$ is in X-Y plane measured from Y-axis. Below is the diagram. Cartesian coordinates can be derived by following equations. <math>\begin{align} x&=r \, \cos\omega \, \sin\alpha \\ y&=r \, \cos\omega \, \cos\alpha \\ z&=r \, \sin\omega\end{align}</math> A computation is necessary to convert the spherical data from the sensor to Cartesian coordinates using above equations. This can be done using a ros package. Above diagram shows the coordinate system of sensor mounted on a car. ___ This [manual](https://velodynelidar.com/docs/manuals/63-9243%20REV%20D%20MANUAL,USERS,VLP-16.pdf) is a good start to know more about Velodyne VLP-16. ## Data format An unstructured point cloud is returned after each scan by sensor. Even though LiDAR returns reading in spherical coordinates, widely used coordinate system is Cartesian. A point in point cloud is defined by it's coordinates and reflectance. Reflectance tells us the reflectivity of the surface. A zero value in reflectance denotes that the laser pulse didn't result in a measurement. There are many formats to store and process point clouds like PCD, PCL but we can treat point cloud as a `Numpy` array. Each element of the array will have `(x,y,z,r)`. For processing point cloud we can use `Numpy`.
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.basic import category_theory.pi.basic import category_theory.shift /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We put the "pointwise" category structure on these, as the non-dependent specialization of `category_theory.pi`. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.pi open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [category.{v} C] instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) := category_theory.pi (λ _, C) /-- The projection of a graded object to its `i`-th component. -/ @[simps] def eval {β : Type w} (b : β) : graded_object β C ⥤ C := { obj := λ X, X b, map := λ X Y f, f b, } section variable (C) /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap (λ _, C) f ≅ comap (λ _, C) g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end @[simp] lemma eq_to_hom_apply {β : Type w} {X Y : Π b : β, C} (h : X = Y) (b : β) : (eq_to_hom h : X ⟶ Y) b = eq_to_hom (by subst h) := by { subst h, refl } /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap (λ _, C) (e.symm : γ → β), inverse := comap (λ _, C) (e : β → γ), counit_iso := (comap_comp (λ _, C) _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp } )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, by { ext b, dsimp, simp, }, } -- See note [dsimp, simp]. end local attribute [reducible, instance] endofunctor_monoidal_category discrete.add_monoidal instance has_shift {β : Type*} [add_comm_group β] (s : β) : has_shift (graded_object_with_shift s C) ℤ := has_shift_mk _ _ { F := λ n, comap (λ _, C) $ λ (b : β), b + n • s, ε := (comap_id β (λ _, C)).symm ≪≫ (comap_eq C (by { ext, simp })), μ := λ m n, comap_comp _ _ _ ≪≫ comap_eq C (by { ext, simp [add_zsmul, add_comm] }), left_unitality := by { introv, ext, dsimp, simpa }, right_unitality := by { introv, ext, dsimp, simpa }, associativity := by { introv, ext, dsimp, simp } } @[simp] lemma shift_functor_obj_apply {β : Type*} [add_comm_group β] (s : β) (X : β → C) (t : β) (n : ℤ) : (shift_functor (graded_object_with_shift s C) n).obj X t = X (t + n • s) := rfl @[simp] lemma shift_functor_map_apply {β : Type*} [add_comm_group β] (s : β) {X Y : graded_object_with_shift s C} (f : X ⟶ Y) (t : β) (n : ℤ) : (shift_functor (graded_object_with_shift s C) n).map f t = f (t + n • s) := rfl instance has_zero_morphisms [has_zero_morphisms C] (β : Type w) : has_zero_morphisms.{(max w v)} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } } @[simp] lemma zero_apply [has_zero_morphisms C] (β : Type w) (X Y : graded_object β C) (b : β) : (0 : X ⟶ Y) b = 0 := rfl section open_locale zero_object instance has_zero_object [has_zero_object C] [has_zero_morphisms C] (β : Type w) : has_zero_object.{(max w v)} (graded_object β C) := { zero := λ b, (0 : C), unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [category.{v} C] variables [has_coproducts C] /-- The total object of a graded object is the coproduct of the graded components. -/ noncomputable def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : ulift.{v} β, X i.down), map := λ X Y f, limits.sigma.map (λ i, f i.down) }. variables [has_zero_morphisms C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful (total β C) := { map_injective' := λ X Y f g w, begin classical, ext i, replace w := sigma.ι (λ i : ulift.{v} β, X i.down) ⟨i⟩ ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object noncomputable theory variables (β : Type) variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_coproducts C] [has_zero_morphisms C] instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
module MainPaths using Graphs using SparseArrays export mainpath export SPCEdge, SPCVertex, GKP export ForwardLocal, BackwardLocal, ForwardBackwardLocal include("utils.jl") include("weights_spc.jl") include("weights_gkp.jl") include("traversal.jl") include("mainpath.jl") include("segments.jl") end
Require Import Coq.Logic.ProofIrrelevance. Require Import Coq.omega.Omega. Require Import Logic.lib.Bijection. Require Import Logic.lib.Countable. Require Import Logic.GeneralLogic.Base. Require Import Logic.MinimumLogic.Syntax. Require Import Logic.PropositionalLogic.Syntax. Require Import Logic.SeparationLogic.Syntax. Local Open Scope logic_base. Local Open Scope syntax. Import PropositionalLanguageNotation. Import SeparationLogicNotation. Class PropositionalVariables: Type := { Var: Type }. Inductive expr {Sigma: PropositionalVariables}: Type := | andp : expr -> expr -> expr | orp : expr -> expr -> expr | impp : expr -> expr -> expr | falsep : expr | sepcon : expr -> expr -> expr | wand : expr -> expr -> expr | varp : Var -> expr. Arguments expr: clear implicits. Instance L {Sigma: PropositionalVariables}: Language := Build_Language (expr Sigma). Instance minL {Sigma: PropositionalVariables}: MinimumLanguage L := Build_MinimumLanguage L impp. Instance pL {Sigma: PropositionalVariables}: PropositionalLanguage L := Build_PropositionalLanguage L andp orp falsep. Instance sepconL {Sigma: PropositionalVariables}: SepconLanguage L := Build_SepconLanguage L sepcon. Instance wandL {Sigma: PropositionalVariables}: WandLanguage L := Build_WandLanguage L wand.
#include <boost/algorithm/string/concept.hpp>
SUBROUTINE ST_SORT ( itype, nstr, inpstr, nout, outstr, iret ) C************************************************************************ C* ST_SORT * C* * C* This subroutine sorts a list of strings. The output list may be * C* sorted forward or backward, and may contain only the unique entries. * C* The input and output arrays may be the same. * C* * C* ST_SORT ( ITYPE, NSTR, INPSTR, NOUT, OUTSTR, IRET ) * C* * C* Input parameters: * C* ITYPE INTEGER Type of sort * C* 1 = Forward * C* -1 = Backward * C* 2 = Forward, unique only * C* -2 = Backward, unique only * C* NSTR INTEGER Number of input strings * C* INPSTR (NSTR) CHAR* Input strings * C* * C* Output parameters: * C* NOUT INTEGER Number of output strings * C* OUTSTR (NOUT) CHAR* Sorted strings * C* IRET INTEGER Return code * C* 0 = normal return * C** * C* Log: * C* S. Jacobs/NCEP 3/01 Copied from TI_SORT * C************************************************************************ CHARACTER*(*) inpstr (*), outstr (*) C* CHARACTER swpbuf*160 C------------------------------------------------------------------------ iret = 0 istop = nstr - 1 C C* Load output array. C DO ii = 1, nstr outstr (ii) = inpstr (ii) END DO C C* Perform bubble sort. C iswflg = 1 DO WHILE ( ( iswflg .ne. 0 ) .and. ( istop .ge. 1 ) ) iswflg = 0 C DO i = 1, istop IF ( outstr (i) .gt. outstr (i+1) ) THEN iswflg = 1 swpbuf = outstr (i) outstr (i) = outstr (i+1) outstr (i+1) = swpbuf ENDIF END DO istop = istop-1 END DO C C* If the sort order is backward, reverse the array. C IF ( itype .lt. 0 ) THEN jj = nstr DO ii = 1, nstr/2 swpbuf = outstr (ii) outstr (ii) = outstr (jj) outstr (jj) = swpbuf jj = jj - 1 END DO END IF C C* If the user has requested, return only unique entries. C IF ( ABS(itype) .eq. 2 ) THEN jj = 1 DO ii = 2, nstr IF ( outstr (ii) .ne. outstr (jj) ) THEN jj = jj + 1 outstr (jj) = outstr (ii) END IF END DO nout = jj DO ii = nout+1, nstr outstr (ii) = ' ' END DO ELSE nout = nstr END IF C* RETURN END
lemma holomorphic_on_compose_gen: "f holomorphic_on s \<Longrightarrow> g holomorphic_on t \<Longrightarrow> f ` s \<subseteq> t \<Longrightarrow> (g o f) holomorphic_on s"
(* Title: FOLP/IFOLP.thy Author: Martin D Coen, Cambridge University Computer Laboratory Copyright 1992 University of Cambridge *) section \<open>Intuitionistic First-Order Logic with Proofs\<close> theory IFOLP imports Pure begin ML_file \<open>~~/src/Tools/misc_legacy.ML\<close> setup Pure_Thy.old_appl_syntax_setup setup \<open>Proofterm.set_preproc (Proof_Rewrite_Rules.standard_preproc [])\<close> class "term" default_sort "term" typedecl p typedecl o consts (*** Judgements ***) Proof :: "[o,p]=>prop" EqProof :: "[p,p,o]=>prop" ("(3_ /= _ :/ _)" [10,10,10] 5) (*** Logical Connectives -- Type Formers ***) eq :: "['a,'a] => o" (infixl "=" 50) True :: "o" False :: "o" conj :: "[o,o] => o" (infixr "&" 35) disj :: "[o,o] => o" (infixr "|" 30) imp :: "[o,o] => o" (infixr "-->" 25) (*Quantifiers*) All :: "('a => o) => o" (binder "ALL " 10) Ex :: "('a => o) => o" (binder "EX " 10) (*Rewriting gadgets*) NORM :: "o => o" norm :: "'a => 'a" (*** Proof Term Formers: precedence must exceed 50 ***) tt :: "p" contr :: "p=>p" fst :: "p=>p" snd :: "p=>p" pair :: "[p,p]=>p" ("(1<_,/_>)") split :: "[p, [p,p]=>p] =>p" inl :: "p=>p" inr :: "p=>p" "when" :: "[p, p=>p, p=>p]=>p" lambda :: "(p => p) => p" (binder "lam " 55) App :: "[p,p]=>p" (infixl "`" 60) alll :: "['a=>p]=>p" (binder "all " 55) app :: "[p,'a]=>p" (infixl "^" 55) exists :: "['a,p]=>p" ("(1[_,/_])") xsplit :: "[p,['a,p]=>p]=>p" ideq :: "'a=>p" idpeel :: "[p,'a=>p]=>p" nrm :: p NRM :: p syntax "_Proof" :: "[p,o]=>prop" ("(_ /: _)" [51, 10] 5) parse_translation \<open> let fun proof_tr [p, P] = Syntax.const \<^const_syntax>\<open>Proof\<close> $ P $ p in [(\<^syntax_const>\<open>_Proof\<close>, K proof_tr)] end \<close> (*show_proofs = true displays the proof terms -- they are ENORMOUS*) ML \<open>val show_proofs = Attrib.setup_config_bool \<^binding>\<open>show_proofs\<close> (K false)\<close> print_translation \<open> let fun proof_tr' ctxt [P, p] = if Config.get ctxt show_proofs then Syntax.const \<^syntax_const>\<open>_Proof\<close> $ p $ P else P in [(\<^const_syntax>\<open>Proof\<close>, proof_tr')] end \<close> (**** Propositional logic ****) (*Equality*) (* Like Intensional Equality in MLTT - but proofs distinct from terms *) axiomatization where ieqI: "ideq(a) : a=a" and ieqE: "[| p : a=b; !!x. f(x) : P(x,x) |] ==> idpeel(p,f) : P(a,b)" (* Truth and Falsity *) axiomatization where TrueI: "tt : True" and FalseE: "a:False ==> contr(a):P" (* Conjunction *) axiomatization where conjI: "[| a:P; b:Q |] ==> <a,b> : P&Q" and conjunct1: "p:P&Q ==> fst(p):P" and conjunct2: "p:P&Q ==> snd(p):Q" (* Disjunction *) axiomatization where disjI1: "a:P ==> inl(a):P|Q" and disjI2: "b:Q ==> inr(b):P|Q" and disjE: "[| a:P|Q; !!x. x:P ==> f(x):R; !!x. x:Q ==> g(x):R |] ==> when(a,f,g):R" (* Implication *) axiomatization where impI: "\<And>P Q f. (!!x. x:P ==> f(x):Q) ==> lam x. f(x):P-->Q" and mp: "\<And>P Q f. [| f:P-->Q; a:P |] ==> f`a:Q" (*Quantifiers*) axiomatization where allI: "\<And>P. (!!x. f(x) : P(x)) ==> all x. f(x) : ALL x. P(x)" and spec: "\<And>P f. (f:ALL x. P(x)) ==> f^x : P(x)" axiomatization where exI: "p : P(x) ==> [x,p] : EX x. P(x)" and exE: "[| p: EX x. P(x); !!x u. u:P(x) ==> f(x,u) : R |] ==> xsplit(p,f):R" (**** Equality between proofs ****) axiomatization where prefl: "a : P ==> a = a : P" and psym: "a = b : P ==> b = a : P" and ptrans: "[| a = b : P; b = c : P |] ==> a = c : P" axiomatization where idpeelB: "[| !!x. f(x) : P(x,x) |] ==> idpeel(ideq(a),f) = f(a) : P(a,a)" axiomatization where fstB: "a:P ==> fst(<a,b>) = a : P" and sndB: "b:Q ==> snd(<a,b>) = b : Q" and pairEC: "p:P&Q ==> p = <fst(p),snd(p)> : P&Q" axiomatization where whenBinl: "[| a:P; !!x. x:P ==> f(x) : Q |] ==> when(inl(a),f,g) = f(a) : Q" and whenBinr: "[| b:P; !!x. x:P ==> g(x) : Q |] ==> when(inr(b),f,g) = g(b) : Q" and plusEC: "a:P|Q ==> when(a,%x. inl(x),%y. inr(y)) = a : P|Q" axiomatization where applyB: "[| a:P; !!x. x:P ==> b(x) : Q |] ==> (lam x. b(x)) ` a = b(a) : Q" and funEC: "f:P ==> f = lam x. f`x : P" axiomatization where specB: "[| !!x. f(x) : P(x) |] ==> (all x. f(x)) ^ a = f(a) : P(a)" (**** Definitions ****) definition Not :: "o => o" ("~ _" [40] 40) where not_def: "~P == P-->False" definition iff :: "[o,o] => o" (infixr "<->" 25) where "P<->Q == (P-->Q) & (Q-->P)" (*Unique existence*) definition Ex1 :: "('a => o) => o" (binder "EX! " 10) where ex1_def: "EX! x. P(x) == EX x. P(x) & (ALL y. P(y) --> y=x)" (*Rewriting -- special constants to flag normalized terms and formulae*) axiomatization where norm_eq: "nrm : norm(x) = x" and NORM_iff: "NRM : NORM(P) <-> P" (*** Sequent-style elimination rules for & --> and ALL ***) schematic_goal conjE: assumes "p:P&Q" and "!!x y.[| x:P; y:Q |] ==> f(x,y):R" shows "?a:R" apply (rule assms(2)) apply (rule conjunct1 [OF assms(1)]) apply (rule conjunct2 [OF assms(1)]) done schematic_goal impE: assumes "p:P-->Q" and "q:P" and "!!x. x:Q ==> r(x):R" shows "?p:R" apply (rule assms mp)+ done schematic_goal allE: assumes "p:ALL x. P(x)" and "!!y. y:P(x) ==> q(y):R" shows "?p:R" apply (rule assms spec)+ done (*Duplicates the quantifier; for use with eresolve_tac*) schematic_goal all_dupE: assumes "p:ALL x. P(x)" and "!!y z.[| y:P(x); z:ALL x. P(x) |] ==> q(y,z):R" shows "?p:R" apply (rule assms spec)+ done (*** Negation rules, which translate between ~P and P-->False ***) schematic_goal notI: assumes "!!x. x:P ==> q(x):False" shows "?p:~P" unfolding not_def apply (assumption | rule assms impI)+ done schematic_goal notE: "p:~P \<Longrightarrow> q:P \<Longrightarrow> ?p:R" unfolding not_def apply (drule (1) mp) apply (erule FalseE) done (*This is useful with the special implication rules for each kind of P. *) schematic_goal not_to_imp: assumes "p:~P" and "!!x. x:(P-->False) ==> q(x):Q" shows "?p:Q" apply (assumption | rule assms impI notE)+ done (* For substitution int an assumption P, reduce Q to P-->Q, substitute into this implication, then apply impI to move P back into the assumptions.*) schematic_goal rev_mp: "[| p:P; q:P --> Q |] ==> ?p:Q" apply (assumption | rule mp)+ done (*Contrapositive of an inference rule*) schematic_goal contrapos: assumes major: "p:~Q" and minor: "!!y. y:P==>q(y):Q" shows "?a:~P" apply (rule major [THEN notE, THEN notI]) apply (erule minor) done (** Unique assumption tactic. Ignores proof objects. Fails unless one assumption is equal and exactly one is unifiable **) ML \<open> local fun discard_proof \<^Const_>\<open>Proof for P _\<close> = P; in fun uniq_assume_tac ctxt = SUBGOAL (fn (prem,i) => let val hyps = map discard_proof (Logic.strip_assums_hyp prem) and concl = discard_proof (Logic.strip_assums_concl prem) in if exists (fn hyp => hyp aconv concl) hyps then case distinct (op =) (filter (fn hyp => Term.could_unify (hyp, concl)) hyps) of [_] => assume_tac ctxt i | _ => no_tac else no_tac end); end; \<close> (*** Modus Ponens Tactics ***) (*Finds P-->Q and P in the assumptions, replaces implication by Q *) ML \<open> fun mp_tac ctxt i = eresolve_tac ctxt [@{thm notE}, make_elim @{thm mp}] i THEN assume_tac ctxt i \<close> method_setup mp = \<open>Scan.succeed (SIMPLE_METHOD' o mp_tac)\<close> (*Like mp_tac but instantiates no variables*) ML \<open> fun int_uniq_mp_tac ctxt i = eresolve_tac ctxt [@{thm notE}, @{thm impE}] i THEN uniq_assume_tac ctxt i \<close> (*** If-and-only-if ***) schematic_goal iffI: assumes "!!x. x:P ==> q(x):Q" and "!!x. x:Q ==> r(x):P" shows "?p:P<->Q" unfolding iff_def apply (assumption | rule assms conjI impI)+ done schematic_goal iffE: assumes "p:P <-> Q" and "!!x y.[| x:P-->Q; y:Q-->P |] ==> q(x,y):R" shows "?p:R" apply (rule conjE) apply (rule assms(1) [unfolded iff_def]) apply (rule assms(2)) apply assumption+ done (* Destruct rules for <-> similar to Modus Ponens *) schematic_goal iffD1: "[| p:P <-> Q; q:P |] ==> ?p:Q" unfolding iff_def apply (rule conjunct1 [THEN mp], assumption+) done schematic_goal iffD2: "[| p:P <-> Q; q:Q |] ==> ?p:P" unfolding iff_def apply (rule conjunct2 [THEN mp], assumption+) done schematic_goal iff_refl: "?p:P <-> P" apply (rule iffI) apply assumption+ done schematic_goal iff_sym: "p:Q <-> P ==> ?p:P <-> Q" apply (erule iffE) apply (rule iffI) apply (erule (1) mp)+ done schematic_goal iff_trans: "[| p:P <-> Q; q:Q<-> R |] ==> ?p:P <-> R" apply (rule iffI) apply (assumption | erule iffE | erule (1) impE)+ done (*** Unique existence. NOTE THAT the following 2 quantifications EX!x such that [EX!y such that P(x,y)] (sequential) EX!x,y such that P(x,y) (simultaneous) do NOT mean the same thing. The parser treats EX!x y.P(x,y) as sequential. ***) schematic_goal ex1I: assumes "p:P(a)" and "!!x u. u:P(x) ==> f(u) : x=a" shows "?p:EX! x. P(x)" unfolding ex1_def apply (assumption | rule assms exI conjI allI impI)+ done schematic_goal ex1E: assumes "p:EX! x. P(x)" and "!!x u v. [| u:P(x); v:ALL y. P(y) --> y=x |] ==> f(x,u,v):R" shows "?a : R" apply (insert assms(1) [unfolded ex1_def]) apply (erule exE conjE | assumption | rule assms(1))+ apply (erule assms(2), assumption) done (*** <-> congruence rules for simplification ***) (*Use iffE on a premise. For conj_cong, imp_cong, all_cong, ex_cong*) ML \<open> fun iff_tac ctxt prems i = resolve_tac ctxt (prems RL [@{thm iffE}]) i THEN REPEAT1 (eresolve_tac ctxt [asm_rl, @{thm mp}] i) \<close> method_setup iff = \<open>Attrib.thms >> (fn prems => fn ctxt => SIMPLE_METHOD' (iff_tac ctxt prems))\<close> schematic_goal conj_cong: assumes "p:P <-> P'" and "!!x. x:P' ==> q(x):Q <-> Q'" shows "?p:(P&Q) <-> (P'&Q')" apply (insert assms(1)) apply (assumption | rule iffI conjI | erule iffE conjE mp | iff assms)+ done schematic_goal disj_cong: "[| p:P <-> P'; q:Q <-> Q' |] ==> ?p:(P|Q) <-> (P'|Q')" apply (erule iffE disjE disjI1 disjI2 | assumption | rule iffI | mp)+ done schematic_goal imp_cong: assumes "p:P <-> P'" and "!!x. x:P' ==> q(x):Q <-> Q'" shows "?p:(P-->Q) <-> (P'-->Q')" apply (insert assms(1)) apply (assumption | rule iffI impI | erule iffE | mp | iff assms)+ done schematic_goal iff_cong: "[| p:P <-> P'; q:Q <-> Q' |] ==> ?p:(P<->Q) <-> (P'<->Q')" apply (erule iffE | assumption | rule iffI | mp)+ done schematic_goal not_cong: "p:P <-> P' ==> ?p:~P <-> ~P'" apply (assumption | rule iffI notI | mp | erule iffE notE)+ done schematic_goal all_cong: assumes "!!x. f(x):P(x) <-> Q(x)" shows "?p:(ALL x. P(x)) <-> (ALL x. Q(x))" apply (assumption | rule iffI allI | mp | erule allE | iff assms)+ done schematic_goal ex_cong: assumes "!!x. f(x):P(x) <-> Q(x)" shows "?p:(EX x. P(x)) <-> (EX x. Q(x))" apply (erule exE | assumption | rule iffI exI | mp | iff assms)+ done (*NOT PROVED ML_Thms.bind_thm ("ex1_cong", prove_goal (the_context ()) "(!!x.f(x):P(x) <-> Q(x)) ==> ?p:(EX! x.P(x)) <-> (EX! x.Q(x))" (fn prems => [ (REPEAT (eresolve_tac [ex1E, spec RS mp] 1 ORELSE ares_tac [iffI,ex1I] 1 ORELSE mp_tac 1 ORELSE iff_tac prems 1)) ])) *) (*** Equality rules ***) lemmas refl = ieqI schematic_goal subst: assumes prem1: "p:a=b" and prem2: "q:P(a)" shows "?p : P(b)" apply (rule prem2 [THEN rev_mp]) apply (rule prem1 [THEN ieqE]) apply (rule impI) apply assumption done schematic_goal sym: "q:a=b ==> ?c:b=a" apply (erule subst) apply (rule refl) done schematic_goal trans: "[| p:a=b; q:b=c |] ==> ?d:a=c" apply (erule (1) subst) done (** ~ b=a ==> ~ a=b **) schematic_goal not_sym: "p:~ b=a ==> ?q:~ a=b" apply (erule contrapos) apply (erule sym) done schematic_goal ssubst: "p:b=a \<Longrightarrow> q:P(a) \<Longrightarrow> ?p:P(b)" apply (drule sym) apply (erule subst) apply assumption done (*A special case of ex1E that would otherwise need quantifier expansion*) schematic_goal ex1_equalsE: "[| p:EX! x. P(x); q:P(a); r:P(b) |] ==> ?d:a=b" apply (erule ex1E) apply (rule trans) apply (rule_tac [2] sym) apply (assumption | erule spec [THEN mp])+ done (** Polymorphic congruence rules **) schematic_goal subst_context: "[| p:a=b |] ==> ?d:t(a)=t(b)" apply (erule ssubst) apply (rule refl) done schematic_goal subst_context2: "[| p:a=b; q:c=d |] ==> ?p:t(a,c)=t(b,d)" apply (erule ssubst)+ apply (rule refl) done schematic_goal subst_context3: "[| p:a=b; q:c=d; r:e=f |] ==> ?p:t(a,c,e)=t(b,d,f)" apply (erule ssubst)+ apply (rule refl) done (*Useful with eresolve_tac for proving equalties from known equalities. a = b | | c = d *) schematic_goal box_equals: "[| p:a=b; q:a=c; r:b=d |] ==> ?p:c=d" apply (rule trans) apply (rule trans) apply (rule sym) apply assumption+ done (*Dual of box_equals: for proving equalities backwards*) schematic_goal simp_equals: "[| p:a=c; q:b=d; r:c=d |] ==> ?p:a=b" apply (rule trans) apply (rule trans) apply (assumption | rule sym)+ done (** Congruence rules for predicate letters **) schematic_goal pred1_cong: "p:a=a' ==> ?p:P(a) <-> P(a')" apply (rule iffI) apply (tactic \<open> DEPTH_SOLVE (assume_tac \<^context> 1 ORELSE eresolve_tac \<^context> [@{thm subst}, @{thm ssubst}] 1)\<close>) done schematic_goal pred2_cong: "[| p:a=a'; q:b=b' |] ==> ?p:P(a,b) <-> P(a',b')" apply (rule iffI) apply (tactic \<open> DEPTH_SOLVE (assume_tac \<^context> 1 ORELSE eresolve_tac \<^context> [@{thm subst}, @{thm ssubst}] 1)\<close>) done schematic_goal pred3_cong: "[| p:a=a'; q:b=b'; r:c=c' |] ==> ?p:P(a,b,c) <-> P(a',b',c')" apply (rule iffI) apply (tactic \<open> DEPTH_SOLVE (assume_tac \<^context> 1 ORELSE eresolve_tac \<^context> [@{thm subst}, @{thm ssubst}] 1)\<close>) done lemmas pred_congs = pred1_cong pred2_cong pred3_cong (*special case for the equality predicate!*) lemmas eq_cong = pred2_cong [where P = "(=)"] (*** Simplifications of assumed implications. Roy Dyckhoff has proved that conj_impE, disj_impE, and imp_impE used with mp_tac (restricted to atomic formulae) is COMPLETE for intuitionistic propositional logic. See R. Dyckhoff, Contraction-free sequent calculi for intuitionistic logic (preprint, University of St Andrews, 1991) ***) schematic_goal conj_impE: assumes major: "p:(P&Q)-->S" and minor: "!!x. x:P-->(Q-->S) ==> q(x):R" shows "?p:R" apply (assumption | rule conjI impI major [THEN mp] minor)+ done schematic_goal disj_impE: assumes major: "p:(P|Q)-->S" and minor: "!!x y.[| x:P-->S; y:Q-->S |] ==> q(x,y):R" shows "?p:R" apply (tactic \<open>DEPTH_SOLVE (assume_tac \<^context> 1 ORELSE resolve_tac \<^context> [@{thm disjI1}, @{thm disjI2}, @{thm impI}, @{thm major} RS @{thm mp}, @{thm minor}] 1)\<close>) done (*Simplifies the implication. Classical version is stronger. Still UNSAFE since Q must be provable -- backtracking needed. *) schematic_goal imp_impE: assumes major: "p:(P-->Q)-->S" and r1: "!!x y.[| x:P; y:Q-->S |] ==> q(x,y):Q" and r2: "!!x. x:S ==> r(x):R" shows "?p:R" apply (assumption | rule impI major [THEN mp] r1 r2)+ done (*Simplifies the implication. Classical version is stronger. Still UNSAFE since ~P must be provable -- backtracking needed. *) schematic_goal not_impE: assumes major: "p:~P --> S" and r1: "!!y. y:P ==> q(y):False" and r2: "!!y. y:S ==> r(y):R" shows "?p:R" apply (assumption | rule notI impI major [THEN mp] r1 r2)+ done (*Simplifies the implication. UNSAFE. *) schematic_goal iff_impE: assumes major: "p:(P<->Q)-->S" and r1: "!!x y.[| x:P; y:Q-->S |] ==> q(x,y):Q" and r2: "!!x y.[| x:Q; y:P-->S |] ==> r(x,y):P" and r3: "!!x. x:S ==> s(x):R" shows "?p:R" apply (assumption | rule iffI impI major [THEN mp] r1 r2 r3)+ done (*What if (ALL x.~~P(x)) --> ~~(ALL x.P(x)) is an assumption? UNSAFE*) schematic_goal all_impE: assumes major: "p:(ALL x. P(x))-->S" and r1: "!!x. q:P(x)" and r2: "!!y. y:S ==> r(y):R" shows "?p:R" apply (assumption | rule allI impI major [THEN mp] r1 r2)+ done (*Unsafe: (EX x.P(x))-->S is equivalent to ALL x.P(x)-->S. *) schematic_goal ex_impE: assumes major: "p:(EX x. P(x))-->S" and r: "!!y. y:P(a)-->S ==> q(y):R" shows "?p:R" apply (assumption | rule exI impI major [THEN mp] r)+ done schematic_goal rev_cut_eq: assumes "p:a=b" and "!!x. x:a=b ==> f(x):R" shows "?p:R" apply (rule assms)+ done lemma thin_refl: "!!X. [|p:x=x; PROP W|] ==> PROP W" . ML_file \<open>hypsubst.ML\<close> ML \<open> structure Hypsubst = Hypsubst ( (*Take apart an equality judgement; otherwise raise Match!*) fun dest_eq \<^Const_>\<open>Proof for \<^Const_>\<open>eq _ for t u\<close> _\<close> = (t, u); val imp_intr = @{thm impI} (*etac rev_cut_eq moves an equality to be the last premise. *) val rev_cut_eq = @{thm rev_cut_eq} val rev_mp = @{thm rev_mp} val subst = @{thm subst} val sym = @{thm sym} val thin_refl = @{thm thin_refl} ); open Hypsubst; \<close> ML_file \<open>intprover.ML\<close> (*** Rewrite rules ***) schematic_goal conj_rews: "?p1 : P & True <-> P" "?p2 : True & P <-> P" "?p3 : P & False <-> False" "?p4 : False & P <-> False" "?p5 : P & P <-> P" "?p6 : P & ~P <-> False" "?p7 : ~P & P <-> False" "?p8 : (P & Q) & R <-> P & (Q & R)" apply (tactic \<open>fn st => IntPr.fast_tac \<^context> 1 st\<close>)+ done schematic_goal disj_rews: "?p1 : P | True <-> True" "?p2 : True | P <-> True" "?p3 : P | False <-> P" "?p4 : False | P <-> P" "?p5 : P | P <-> P" "?p6 : (P | Q) | R <-> P | (Q | R)" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done schematic_goal not_rews: "?p1 : ~ False <-> True" "?p2 : ~ True <-> False" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done schematic_goal imp_rews: "?p1 : (P --> False) <-> ~P" "?p2 : (P --> True) <-> True" "?p3 : (False --> P) <-> True" "?p4 : (True --> P) <-> P" "?p5 : (P --> P) <-> True" "?p6 : (P --> ~P) <-> ~P" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done schematic_goal iff_rews: "?p1 : (True <-> P) <-> P" "?p2 : (P <-> True) <-> P" "?p3 : (P <-> P) <-> True" "?p4 : (False <-> P) <-> ~P" "?p5 : (P <-> False) <-> ~P" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done schematic_goal quant_rews: "?p1 : (ALL x. P) <-> P" "?p2 : (EX x. P) <-> P" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done (*These are NOT supplied by default!*) schematic_goal distrib_rews1: "?p1 : ~(P|Q) <-> ~P & ~Q" "?p2 : P & (Q | R) <-> P&Q | P&R" "?p3 : (Q | R) & P <-> Q&P | R&P" "?p4 : (P | Q --> R) <-> (P --> R) & (Q --> R)" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done schematic_goal distrib_rews2: "?p1 : ~(EX x. NORM(P(x))) <-> (ALL x. ~NORM(P(x)))" "?p2 : ((EX x. NORM(P(x))) --> Q) <-> (ALL x. NORM(P(x)) --> Q)" "?p3 : (EX x. NORM(P(x))) & NORM(Q) <-> (EX x. NORM(P(x)) & NORM(Q))" "?p4 : NORM(Q) & (EX x. NORM(P(x))) <-> (EX x. NORM(Q) & NORM(P(x)))" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>)+ done lemmas distrib_rews = distrib_rews1 distrib_rews2 schematic_goal P_Imp_P_iff_T: "p:P ==> ?p:(P <-> True)" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>) done schematic_goal not_P_imp_P_iff_F: "p:~P ==> ?p:(P <-> False)" apply (tactic \<open>IntPr.fast_tac \<^context> 1\<close>) done end
abstract type AbstractOperationModel end struct DefaultOpModel<:AbstractOperationModel end mutable struct ModelReference transmission::Type{<:PM.AbstractPowerModel} devices::Dict{Symbol, DeviceModel} branches::Dict{Symbol, DeviceModel} services::Dict{Symbol, ServiceModel} end """ ModelReference(::Type{T}) where {T<:PM.AbstractPowerFormulation} Creates a model reference of the Power Formulation, devices, branches, and services. # Arguments -`model::Type{T} where {T<:PM.AbstractPowerFormulation} = CopperPlatePowerModel`: -`devices::Dict{Symbol, DeviceModel} = devices`: device dictionary -`branches::Dict{Symbol, BranchModel} = branches`: branch dictionary -`services::Dict{Symbol, ServiceModel} = services`: service dictionary # Example ```julia model_ref= ModelReference(CopperPlatePowerModel, devices, branches, services) ``` """ function ModelReference(::Type{T}) where {T<:PM.AbstractPowerModel} return ModelReference(T, Dict{Symbol, DeviceModel}(), Dict{Symbol, DeviceModel}(), Dict{Symbol, ServiceModel}()) end mutable struct OperationModel{M<:AbstractOperationModel} model_ref::ModelReference sys::PSY.System canonical::CanonicalModel end """ OperationModel(::Type{M}, model_ref::ModelReference, sys::PSY.System; optimizer::Union{Nothing, JuMP.OptimizerFactory}=nothing, kwargs...) where {M<:AbstractOperationModel, T<:PM.AbstractPowerFormulation} This builds the optimization model and populates the operation model # Arguments -`::Type{M} where {M<:AbstractOperationModel, T<:PM.AbstractPowerFormulation} = TestOptModel`: The abstract operation model type -`model_ref::ModelReference = model_ref`: The model reference made up of transmission, devices, branches, and services. -`sys::PSY.System = c_sys5`: the system created using Power Systems # Output -`op_model::OperationModel`: The operation model contains the model type, model, Power Systems system, and optimization model. # Example ```julia model_ref= ModelReference(CopperPlatePowerModel, devices, branches, services) OpModel = OperationModel(TestOptModel, model_ref, c_sys5_re; PTDF = PTDF5, optimizer = GLPK_optimizer) ``` # Accepted Key Words -`verbose::Bool = true`: verbose default is true -`PTDF::PTDF = PTDF`: Passes the PTDF matrix into the optimization model -`optimizer::union{Nothing,JuMP.OptimizerFactory} = GLPK_optimizer`: The optimizer gets passed into the optimization model the default is nothing. -`sequential_runs::Bool = false`: tells the model to do sequential runs -`initial_conditions::DICKDA = DICKDA()`: default of Dict{ICKey, Array{InitialCondition}} -`parameters::Bool = false`: enable JuMP parameters -`forecast::Bool = true`: if true, forecast collects the time steps in Power Systems, if false it runs for one time step -`initial_time::Dates.DateTime = PSY.get_forecasts_initial_time(sys)`: initial time of forecast """ function OperationModel(::Type{M}, model_ref::ModelReference, sys::PSY.System; optimizer::Union{Nothing, JuMP.OptimizerFactory}=nothing, kwargs...) where {M<:AbstractOperationModel} op_model = OperationModel{M}(model_ref, sys, CanonicalModel(model_ref.transmission, sys, optimizer; kwargs...)) build_op_model!(op_model; kwargs...) return op_model end """ OperationModel(op_model::Type{M}, ::Type{T}, sys::PSY.System; kwargs...) where {M<:AbstractOperationModel, T<:PM.AbstractPowerFormulation} This uses the Abstract Power Formulation to build the model reference and the optimization model and populates the operation model struct. # Arguments -`op_model::Type{M} = where {M<:AbstractOperationModel`: Defines the type of the operation model -`::Type{T} where T<:PM.AbstractPowerFormulation`: The power formulation used for model ref & optimization model -`sys::PSY.System = c_sys5`: the system created in Power Systems # Output -`op_model::OperationModel`: The operation model contains the model type, model, Power Systems system, and optimization model. # Example ```julia model_ref= ModelReference(CopperPlatePowerModel, devices, branches, services) OpModel = OperationModel(TestOptModel, model_ref, c_sys5_re; PTDF = PTDF5, optimizer = GLPK_optimizer) ``` # Accepted Key Words -`verbose::Bool = true`: verbose default is true -`PTDF::PTDF = PTDF`: Passes the PTDF matrix into the optimization model -`optimizer::union{Nothing,JuMP.OptimizerFactory} = GLPK_optimizer`: The optimizer gets passed into the optimization model the default is nothing. -`sequential_runs::Bool = false`: tells the model to do sequential runs -`initial_conditions::DICKDA = DICKDA()`: default of Dict{ICKey, Array{InitialCondition}} -`parameters::Bool = false`: enable JuMP parameters -`forecast::Bool = true`: if true, forecast collects the time steps in Power Systems, if false it runs for one time step -`initial_time::Dates.DateTime = PSY.get_forecasts_initial_time(sys)`: initial time of forecast """ function OperationModel(::Type{M}, ::Type{T}, sys::PSY.System; kwargs...) where {M<:AbstractOperationModel, T<:PM.AbstractPowerModel} optimizer = get(kwargs, :optimizer, nothing) return OperationModel{M}(ModelReference(T), sys, CanonicalModel(T, sys, optimizer; kwargs...)) end """ OperationModel(::Type{T}, sys::PSY.System; kwargs...) where {M<:AbstractOperationModel, T<:PM.AbstractPowerFormulation} This uses the Abstract Power Formulation to build the model reference and the optimization model and populates the operation model struct. ***Note:*** the abstract operation model is set to the default operation model # Arguments -`op_model::Type{M} = where {M<:AbstractOperationModel`: Defines the type of the operation model -`::Type{T} where T<:PM.AbstractPowerFormulation`: The power formulation used for model ref & optimization model -`sys::PSY.System = c_sys5`: the system created in Power Systems # Output -`op_model::OperationModel`: The operation model contains the model type, model, Power Systems system, and optimization model. # Example ```julia model_ref= ModelReference(CopperPlatePowerModel, devices, branches, services) OpModel = OperationModel(TestOptModel, model_ref, c_sys5_re; PTDF = PTDF5, optimizer = GLPK_optimizer) ``` # Accepted Key Words -`verbose::Bool = true`: verbose default is true -`PTDF::PTDF = PTDF`: Passes the PTDF matrix into the optimization model -`optimizer::union{Nothing,JuMP.OptimizerFactory} = GLPK_optimizer`: The optimizer gets passed into the optimization model the default is nothing. -`sequential_runs::Bool = false`: tells the model to do sequential runs -`initial_conditions::DICKDA = DICKDA()`: default of Dict{ICKey, Array{InitialCondition}} -`parameters::Bool = false`: enable JuMP parameters -`forecast::Bool = true`: if true, forecast collects the time steps in Power Systems, if false it runs for one time step -`initial_time::Dates.DateTime = PSY.get_forecasts_initial_time(sys)`: initial time of forecast """ function OperationModel(::Type{T}, sys::PSY.System; kwargs...) where {T<:PM.AbstractPowerModel} return OperationModel(DefaultOpModel, T, sys; kwargs...) end get_transmission_ref(op_model::OperationModel) = op_model.model_ref.transmission get_devices_ref(op_model::OperationModel) = op_model.model_ref.devices get_branches_ref(op_model::OperationModel) = op_model.model_ref.branches get_services_ref(op_model::OperationModel) = op_model.model_ref.services get_system(op_model::OperationModel) = op_model.sys function set_transmission_ref!(op_model::OperationModel{M}, transmission::Type{T}; kwargs...) where {T<:PM.AbstractPowerModel, M<:AbstractOperationModel} # Reset the canonical op_model.model_ref.transmission = transmission op_model.canonical = CanonicalModel(transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) return end function set_devices_ref!(op_model::OperationModel{M}, devices::Dict{Symbol, DeviceModel}; kwargs...) where M<:AbstractOperationModel # Reset the canonical op_model.model_ref.devices = devices op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) return end function set_branches_ref!(op_model::OperationModel{M}, branches::Dict{Symbol, DeviceModel}; kwargs...) where M<:AbstractOperationModel # Reset the canonical op_model.model_ref.branches = branches op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) return end function set_services_ref!(op_model::OperationModel{M}, services::Dict{Symbol, DeviceModel}; kwargs...) where M<:AbstractOperationModel # Reset the canonical op_model.model_ref.services = services op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) return end function set_device_model!(op_model::OperationModel{M}, name::Symbol, device::DeviceModel{D, B}; kwargs...) where {D<:PSY.Injection, B<:AbstractDeviceFormulation, M<:AbstractOperationModel} if haskey(op_model.model_ref.devices, name) op_model.model_ref.devices[name] = device op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) else error("Device Model with name $(name) doesn't exist in the model") end return end function set_branch_model!(op_model::OperationModel{M}, name::Symbol, branch::DeviceModel{D, B}; kwargs...) where {D<:PSY.Branch, B<:AbstractDeviceFormulation, M<:AbstractOperationModel} if haskey(op_model.model_ref.branches, name) op_model.model_ref.branches[name] = branch op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) else error("Branch Model with name $(name) doesn't exist in the model") end return end function set_services_model!(op_model::OperationModel{M}, name::Symbol, service::DeviceModel; kwargs...) where M<:AbstractOperationModel if haskey(op_model.model_ref.devices, name) op_model.model_ref.services[name] = service op_model.canonical = CanonicalModel(op_model.model_ref.transmission, op_model.sys, op_model.canonical.optimizer_factory; kwargs...) build_op_model!(op_model; kwargs...) else error("Branch Model with name $(name) doesn't exist in the model") end return end function construct_device!(op_model::OperationModel, name::Symbol, device_model::DeviceModel; kwargs...) if haskey(op_model.model_ref.devices, name) error("Device with model name $(name) already exists in the Opertaion Model") end op_model.model_ref.devices[name] = device_model construct_device!(op_model.canonical, get_system(op_model), device_model, get_transmission_ref(op_model); kwargs...) JuMP.@objective(op_model.canonical.JuMPmodel, MOI.MIN_SENSE, op_model.canonical.cost_function) return end function construct_network!(op_model::OperationModel, system_formulation::Type{T}; kwargs...) where {T<:PM.AbstractPowerModel} construct_network!(op_model.canonical, get_system(op_model), T; kwargs...) return end function get_initial_conditions(op_model::OperationModel) return op_model.canonical.initial_conditions end function get_initial_conditions(op_model::OperationModel, ic::InitialConditionQuantity, device::PSY.Device) canonical = op_model.canonical key = ICKey(ic, device) return get_ini_cond(canonical, key) end
collapse.unlabelled.singleton <- function(tree){ if(!is.rooted(tree)) stop("tree must be rooted") if(!is.null(tree$edge.length)) stop("tree must not have edge length") # Solve bug reading newick in phytools 0.6 if(tree$Nnode > length(tree$node.label)) tree$node.label <- c(tree$node.label, rep('', tree$Nnode - length(tree$node.label))) # number of tips not <- length(tree$tip.label) edge <- tree$edge # unlabelled nodes un <- which(tree$node.label %in% '') + not # descendants number of unlabelled node dnoun <- sapply(un, function(x,y){length(y[y[ ,1] %in% x,1])}, y = edge) if(sum(dnoun == 1) > 0){ # node to drop ntd <- un[dnoun == 1] # node to tip ntt <- edge[edge[ ,2] %in% (1:not),1] # common node to tip cntt <- edge[edge[ ,2] %in% ntt,1] newedge <- edge # relink nodes for(i in ntd){ nn <- newedge[newedge[ ,1] %in% i,2] newedge <- newedge[!(newedge[ ,1] %in% i), ] newedge[newedge[ ,2] %in% i,2] <- nn } # relink root node root <- not + 1 rd <- newedge[newedge[ ,1] == root,2] if(length(rd) == 1){ if(rd %in% un){ newedge <- newedge[newedge[ ,1] != root, ] newedge[newedge[ ,1] %in% rd,1] <- root } } # New nodes positions newn <- matrix(NA, nrow = tree$Nnode, ncol = 2, dimnames = list(1:tree$Nnode, c('nodes', 'new'))) newn [ ,1] <- 1:tree$Nnode + not newn <- newn[!(newn[ ,1] %in% ntd), ] newn [ ,2] <- rank(newn[ ,1]) + not # Reference table to new nodes positions refedge <- rbind(newn, matrix(rep(1:not, each = 2), ncol = 2, byrow = TRUE)) newedge[ ,1] <- refedge[match(newedge[ ,1], refedge[ ,1]) ,2] newedge[ ,2] <- refedge[match(newedge[ ,2], refedge[ ,1]) ,2] # update tree tree$edge <- newedge tree$node.label <- tree$node.label[-(ntd - not)] tree$Nnode <- tree$Nnode - length(ntd) } return(tree) }
-- deletion tactics for G&G prover import meta.expr open tactic expr universes u v w def list.mchoose {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := pure (λ (h : option β) (t : list β), option.rec_on h t (λ h, h :: t)) <*> f h <*> list.mchoose t def list.some {α : Type u} (p : α -> bool) : list α -> bool | [] := false | (h :: t) := p h || list.some t namespace exprset meta def exprset := rbmap expr unit expr.lt_prop meta def from_list (l : list expr) : exprset := rbmap.from_list $ list.map (λ x, ⟨x,unit.star⟩) l meta def to_list (d : exprset) : list expr := list.map prod.fst $ rbmap.to_list d meta def empty : exprset := mk_rbmap expr unit expr.lt_prop meta def union : exprset -> exprset -> exprset := rbmap.fold(λ x u a, rbmap.insert a x u) meta def contains : exprset -> expr -> bool := rbmap.contains end exprset open exprset meta def get_local_consts (e : expr) : exprset := from_list $ expr.list_local_const $ e meta structure formula := (term : expr) (type : expr) (deps : exprset) meta def as_prop (h : expr) : tactic $ option formula := do y <- infer_type h, p <- is_prop y, let deps := get_local_consts y in return $ if p then some ⟨h, y, deps⟩ else none /--Get all of the context entries which are propositions along with their types.-/ meta def local_hypotheses : tactic $ list formula := local_context >>= list.mchoose as_prop /--Get the goals which are propositions along with their types -/ meta def local_targets : tactic $ list formula := get_goals >>= list.mchoose as_prop meta def find_dangling : exprset -> list formula -> list formula -> list formula | d acc [] := acc | d acc (h :: hs) := find_dangling (union d h.deps) ( if list.some (λ h, (not $ contains d h) && list.all hs (λ h', not $ contains h'.deps h)) $ to_list h.deps then h :: acc else acc ) (hs) meta def deleteDangling : tactic unit := do hyps <- local_hypotheses, targets <- local_targets, target_deps <- return $ list.foldl union empty $ list.map (λ t : formula, t.deps) targets, list.mmap' (λ (h : formula), clear h.term) $ find_dangling target_deps [] hyps variables a b c : Prop example : a -> (a -> b) -> c -> b := begin intros, deleteDangling, sorry end
{-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -Wall #-} import qualified Numeric.Sundials.ARKode.ODE as ARK import qualified Numeric.Sundials.CVode.ODE as CV import Numeric.LinearAlgebra import Numeric.Sundials.ODEOpts (ODEOpts(..)) import Plots as P import qualified Diagrams.Prelude as D import Diagrams.Backend.Rasterific import Control.Lens import Data.Functor.Compose import Test.Hspec lorenz :: Double -> [Double] -> [Double] lorenz _t u = [ sigma * (y - x) , x * (rho - z) - y , x * y - beta * z ] where rho = 28.0 sigma = 10.0 beta = 8.0 / 3.0 x = u !! 0 y = u !! 1 z = u !! 2 _lorenzJac :: Double -> Vector Double -> Matrix Double _lorenzJac _t u = (3><3) [ (-sigma), rho - z, y , sigma , -1.0 , x , 0.0 , (-x) , (-beta) ] where rho = 28.0 sigma = 10.0 beta = 8.0 / 3.0 x = u ! 0 y = u ! 1 z = u ! 2 brusselator :: Double -> [Double] -> [Double] brusselator _t x = [ a - (w + 1) * u + v * u * u , w * u - v * u * u , (b - w) / eps - w * u ] where a = 1.0 b = 3.5 eps = 5.0e-6 u = x !! 0 v = x !! 1 w = x !! 2 brussJac :: Double -> Vector Double -> Matrix Double brussJac _t x = tr $ (3><3) [ (-(w + 1.0)) + 2.0 * u * v, w - 2.0 * u * v, (-w) , u * u , (-(u * u)) , 0.0 , (-u) , u , (-1.0) / eps - u ] where y = toList x u = y !! 0 v = y !! 1 w = y !! 2 eps = 5.0e-6 brusselatorWithJacobian :: Vector Double -> Bool -> CV.SolverResult brusselatorWithJacobian ts usejac = CV.odeSolveRootVWith' opts (\t v -> vector $ brusselator t (toList v)) (if usejac then Just brussJac else Nothing) (vector [1.2, 3.1, 3.0]) [] 0 ts where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.XX' 1.0e-6 1.0e-10 1 1 , initStep = Nothing } brussRoot :: CV.SolverResult brussRoot = CV.odeSolveRootVWith' opts (\t v -> vector $ brusselator t (toList v)) Nothing (vector [1.2, 3.1, 3.0]) events 100 (vector [0.0, 0.1 .. 10.0]) where events = [ CV.EventSpec { CV.eventCondition = brussRootFn , CV.eventUpdate = \_ev x -> let y = toList x in vector [(y!!0) + 0.5 , (y!!1), (y!!2)] , CV.eventDirection = CV.AnyDirection } ] opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.XX' 1.0e-6 1.0e-10 1 1 , initStep = Nothing } brussRootFn :: Double -> Vector Double -> Double brussRootFn _ v = case xs of [y1, _y2, y3] -> y1 - y3 _ -> error "brusselator root function RHS not defined" where xs = toList v exponential :: CV.SolverResult exponential = CV.odeSolveRootVWith' opts (\t y -> vector [y ! 0]) Nothing (vector [1]) events 100 (vector [ fromIntegral k / 100 | k <- [0..(22::Int)]]) where events = [ CV.EventSpec { CV.eventCondition = \t y -> y ! 0 - 1.1 , CV.eventUpdate = \ev y -> vector [ 2 ] , CV.eventDirection = CV.Upwards } ] opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.XX' 1.0e-6 1.0e-10 1 1 , initStep = Nothing } -- A sine wave that only changes direction once it reaches ±0.9. -- Illustrates event-specific reset function boundedSine :: CV.SolverResult boundedSine = CV.odeSolveRootVWith' opts (\_t y -> vector [y ! 1, - y ! 0]) -- ODE RHS Nothing (vector [0, 1]) -- initial conditions events 100 -- maximum number of events (vector [ 2 * pi * k / 360 | k <- [0..360]]) -- solution times where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.ADAMS , stepControl = CV.XX' 1.0e-6 1.0e-10 1 1 , initStep = Nothing } events = [ CV.EventSpec { CV.eventCondition = \_t y -> y ! 0 - 0.9 , CV.eventUpdate = \_ y -> vector [ y ! 0, - abs (y ! 1) ] , CV.eventDirection = CV.Upwards } , CV.EventSpec { CV.eventCondition = \_t y -> y ! 0 + 0.9 , CV.eventUpdate = \_ y -> vector [ y ! 0, abs (y ! 1) ] , CV.eventDirection = CV.Downwards } ] stiffish :: Double -> [Double] -> [Double] stiffish t v = [ lamda * u + 1.0 / (1.0 + t * t) - lamda * atan t ] where lamda = -100.0 u = v !! 0 stiffishV :: Double -> Vector Double -> Vector Double stiffishV t v = fromList [ lamda * u + 1.0 / (1.0 + t * t) - lamda * atan t ] where lamda = -100.0 u = v ! 0 _stiffJac :: Double -> Vector Double -> Matrix Double _stiffJac _t _v = (1><1) [ lamda ] where lamda = -100.0 predatorPrey :: Double -> [Double] -> [Double] predatorPrey _t v = [ x * a - b * x * y , d * x * y - c * y - e * y * z , (-f) * z + g * y * z ] where x = v!!0 y = v!!1 z = v!!2 a = 1.0 b = 1.0 c = 1.0 d = 1.0 e = 1.0 f = 1.0 g = 1.0 roberts :: Double -> Vector Double -> Vector Double roberts t v = vector $ robertsAux t (toList v) where robertsAux _ [y1, y2, y3] = [ -0.04 * y1 + 1.0e4 * y2 * y3 , 0.04 * y1 - 1.0e4 * y2 * y3 - 3.0e7 * (y2)^(2 :: Int) , 3.0e7 * (y2)^(2 :: Int) ] robertsAux _ _ = error "roberts RHS not defined" robertsJac :: Double -> Vector Double -> Matrix Double robertsJac _t (toList -> [y1, y2, y3]) = (3 >< 3) [ -0.04, 1.0e4 * y3, 1.0e4 * y2 , 0.04, -1.0e4*y3 - 3.0e7*2*y2, -1.0e4*y2 , 0, 3.0e7*2*y2, 0 ] ts :: [Double] ts = take 12 $ map (* 10.0) (0.04 : ts) solve :: CV.SolverResult solve = CV.odeSolveRootVWith' opts roberts Nothing (vector [1.0, 0.0, 0.0]) events 100 (vector (0.0 : ts)) where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.ScXX' 1.0 1.0e-4 1.0 1.0 (vector [1.0e-8, 1.0e-14, 1.0e-6]) , initStep = Nothing } events = [ CV.EventSpec { CV.eventCondition = \_t y -> y ! 0 - 0.0001 , CV.eventUpdate = const id , CV.eventDirection = CV.AnyDirection } , CV.EventSpec { CV.eventCondition = \_t y -> y ! 2 - 0.01 , CV.eventUpdate = const id , CV.eventDirection = CV.AnyDirection } ] solve2 :: CV.SolverResult solve2 = CV.odeSolveRootVWith' opts roberts Nothing (vector [1.0, 0.0, 0.0]) events 100 (vector (0.0 : ts)) where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.ScXX' 1.0 1.0e-4 1.0 1.0 (vector [1.0e-8, 1.0e-14, 1.0e-6]) , initStep = Nothing } events = [ CV.EventSpec { CV.eventCondition = \_t y -> y ! 0 - 0.0001 , CV.eventUpdate = upd , CV.eventDirection = CV.AnyDirection } , CV.EventSpec { CV.eventCondition = \_t y -> y ! 2 - 0.01 , CV.eventUpdate = upd , CV.eventDirection = CV.AnyDirection } ] upd _ _ = vector [1.0, 0.0, 0.0] solve1 :: CV.SolverResult solve1 = CV.odeSolveRootVWith' opts roberts Nothing (vector [1.0, 0.0, 0.0]) events 100 (vector (0.0 : ts)) where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.ScXX' 1.0 1.0e-4 1.0 1.0 (vector [1.0e-8, 1.0e-14, 1.0e-6]) , initStep = Nothing } events = [ CV.EventSpec { CV.eventCondition = \t _y -> t - 1.0 , CV.eventUpdate = \t y -> vector [2.0, y!1, y!2] , CV.eventDirection = CV.AnyDirection } ] robertsonWithJacobian :: Vector Double -> Bool -> CV.SolverResult robertsonWithJacobian ts usejac = CV.odeSolveRootVWith' opts roberts (if usejac then Just robertsJac else Nothing) (vector [1.0, 0.0, 0.0]) [] 0 ts where opts = ODEOpts { maxNumSteps = 10000 , minStep = 1.0e-12 , maxFail = 10 , odeMethod = CV.BDF , stepControl = CV.ScXX' 1.0 1.0e-4 1.0 1.0 (vector [1.0e-8, 1.0e-14, 1.0e-6]) , initStep = Nothing } lSaxis :: [[Double]] -> P.Axis B D.V2 Double lSaxis xs = P.r2Axis &~ do let zs = xs!!0 us = xs!!1 vs = xs!!2 ws = xs!!3 P.linePlot' $ zip zs us P.linePlot' $ zip zs vs P.linePlot' $ zip zs ws lSaxis2 :: [[Double]] -> P.Axis B D.V2 Double lSaxis2 xs = P.r2Axis &~ do let zs = xs!!0 us = xs!!1 vs = xs!!2 P.linePlot' $ zip zs us P.linePlot' $ zip zs vs kSaxis :: [(Double, Double)] -> P.Axis B D.V2 Double kSaxis xs = P.r2Axis &~ do P.linePlot' xs main :: IO () main = do let res1 = ARK.odeSolve brusselator [1.2, 3.1, 3.0] (fromList [0.0, 0.1 .. 10.0]) renderRasterific "diagrams/brusselator.png" (D.dims2D 500.0 500.0) (renderAxis $ lSaxis $ [0.0, 0.1 .. 10.0]:(toLists $ tr res1)) let res1a = ARK.odeSolve brusselator [1.2, 3.1, 3.0] (fromList [0.0, 0.1 .. 10.0]) renderRasterific "diagrams/brusselatorA.png" (D.dims2D 500.0 500.0) (renderAxis $ lSaxis $ [0.0, 0.1 .. 10.0]:(toLists $ tr res1a)) let res2 = ARK.odeSolve stiffish [0.0] (fromList [0.0, 0.1 .. 10.0]) renderRasterific "diagrams/stiffish.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip [0.0, 0.1 .. 10.0] (concat $ toLists res2)) let res2a = ARK.odeSolveV (ARK.SDIRK_5_3_4') Nothing 1e-6 1e-10 stiffishV (fromList [0.0]) (fromList [0.0, 0.1 .. 10.0]) let res2b = ARK.odeSolveV (ARK.TRBDF2_3_3_2') Nothing 1e-6 1e-10 stiffishV (fromList [0.0]) (fromList [0.0, 0.1 .. 10.0]) let maxDiffA = maximum $ map abs $ zipWith (-) ((toLists $ tr res2a)!!0) ((toLists $ tr res2b)!!0) let res2c = CV.odeSolveV (CV.BDF) Nothing 1e-6 1e-10 stiffishV (fromList [0.0]) (fromList [0.0, 0.1 .. 10.0]) let maxDiffB = maximum $ map abs $ zipWith (-) ((toLists $ tr res2a)!!0) ((toLists $ tr res2c)!!0) let maxDiffC = maximum $ map abs $ zipWith (-) ((toLists $ tr res2b)!!0) ((toLists $ tr res2c)!!0) let res3 = ARK.odeSolve lorenz [-5.0, -5.0, 1.0] (fromList [0.0, 0.01 .. 20.0]) renderRasterific "diagrams/lorenz.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res3)!!0) ((toLists $ tr res3)!!1)) renderRasterific "diagrams/lorenz1.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res3)!!0) ((toLists $ tr res3)!!2)) renderRasterific "diagrams/lorenz2.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res3)!!1) ((toLists $ tr res3)!!2)) let res4 = CV.odeSolve predatorPrey [0.5, 1.0, 2.0] (fromList [0.0, 0.01 .. 10.0]) renderRasterific "diagrams/predatorPrey.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res4)!!0) ((toLists $ tr res4)!!1)) renderRasterific "diagrams/predatorPrey1.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res4)!!0) ((toLists $ tr res4)!!2)) renderRasterific "diagrams/predatorPrey2.png" (D.dims2D 500.0 500.0) (renderAxis $ kSaxis $ zip ((toLists $ tr res4)!!1) ((toLists $ tr res4)!!2)) let res4a = ARK.odeSolve predatorPrey [0.5, 1.0, 2.0] (fromList [0.0, 0.01 .. 10.0]) let maxDiffPpA = maximum $ map abs $ zipWith (-) ((toLists $ tr res4)!!0) ((toLists $ tr res4a)!!0) let cond5 = case solve of CV.SolverSuccess events _ _ -> do length events `shouldBe` 2 (abs (CV.eventTime (events!!0) - 0.2640208751331032) / 0.2640208751331032 < 1.0e-8) `shouldBe` True (abs (CV.eventTime (events!!1) - 2.0786731062254436e7) / 2.0786731062254436e7 < 1.0e-8) `shouldBe` True CV.SolverError _ _ -> error "Root finding error!" let cond6 = case solve1 of CV.SolverSuccess events _ _ -> do length events `shouldBe` 1 (abs (CV.eventTime (events!!0) - 1.0) / 1.0 < 1.0e-10) `shouldBe` True CV.SolverError _ _ -> error "Root finding error!" let cond7 = case solve2 of CV.SolverSuccess {} -> error "Solver returned Success" CV.SolverError _ _ -> True case brussRoot of CV.SolverSuccess events m _diagn -> do renderRasterific "diagrams/brussRoot.png" (D.dims2D 500.0 500.0) (renderAxis $ lSaxis $ toLists $ tr m) CV.SolverError m n -> expectationFailure $ show n let boundedSineSpec = do case boundedSine of CV.SolverSuccess events m _ -> do renderRasterific "diagrams/boundedSine.png" (D.dims2D 500.0 500.0) (renderAxis $ lSaxis2 $ toLists $ tr m) length events `shouldBe` 3 map CV.rootDirection events `shouldBe` [CV.Upwards, CV.Downwards, CV.Upwards] map CV.eventIndex events `shouldBe` [0, 1, 0] all ((< 1e-8) . abs) (zipWith (-) (map CV.eventTime events) [1.1197660081724263,3.3592952656818404,5.5988203973243]) `shouldBe` True CV.SolverError m n -> expectationFailure "Solver error" let exponentialSpec = do case exponential of CV.SolverSuccess events _m _diagn -> do length events `shouldBe` 1 (abs (CV.eventTime (events!!0) - log 1.1) < 1e-4) `shouldBe` True CV.rootDirection (events!!0) `shouldBe` CV.Upwards CV.eventIndex (events!!0) `shouldBe` 0 CV.SolverError m n -> expectationFailure $ show n robertsonJac = do let ts = vector [0, 1 .. 10] CV.SolverSuccess _ m1 _ = robertsonWithJacobian ts True CV.SolverSuccess _ m2 _ = robertsonWithJacobian ts False (norm_2 (m1-m2) < 1e-4) `shouldBe` True brusselatorJac = do let ts = [0.0, 0.1 .. 10.0] CV.SolverSuccess _ m1 _ = brusselatorWithJacobian (vector ts) True CV.SolverSuccess _ m2 _ = brusselatorWithJacobian (vector ts) False (norm_2 (m1-m2) < 1e-3) `shouldBe` True hspec $ describe "Compare results" $ do it "Robertson should fail" $ cond7 it "Robertson time only" $ cond6 it "Robertson from SUNDIALS manual" $ cond5 it "Robertson with explicit Jacobian up to t=10" robertsonJac it "Brusselator with explicit Jacobian" brusselatorJac it "for SDIRK_5_3_4' and TRBDF2_3_3_2'" $ maxDiffA < 1.0e-6 it "for SDIRK_5_3_4' and BDF" $ maxDiffB < 1.0e-6 it "for TRBDF2_3_3_2' and BDF" $ maxDiffC < 1.0e-6 it "for CV and ARK for the Predator Prey model" $ maxDiffPpA < 1.0e-3 it "Bounded sine events" $ boundedSineSpec it "Exponential events" $ exponentialSpec
Formal statement is: theorem split_inside_simple_closed_curve: fixes c :: "real \<Rightarrow> complex" assumes "simple_path c1" and c1: "pathstart c1 = a" "pathfinish c1 = b" and "simple_path c2" and c2: "pathstart c2 = a" "pathfinish c2 = b" and "simple_path c" and c: "pathstart c = a" "pathfinish c = b" and "a \<noteq> b" and c1c2: "path_image c1 \<inter> path_image c2 = {a,b}" and c1c: "path_image c1 \<inter> path_image c = {a,b}" and c2c: "path_image c2 \<inter> path_image c = {a,b}" and ne_12: "path_image c \<inter> inside(path_image c1 \<union> path_image c2) \<noteq> {}" obtains "inside(path_image c1 \<union> path_image c) \<inter> inside(path_image c2 \<union> path_image c) = {}" "inside(path_image c1 \<union> path_image c) \<union> inside(path_image c2 \<union> path_image c) \<union> (path_image c - {a,b}) = inside(path_image c1 \<union> path_image c2)" Informal statement is: If $c_1$ and $c_2$ are simple closed curves that intersect only at their endpoints, and $c$ is a simple curve that intersects $c_1$ and $c_2$ only at their endpoints, then $c$ splits the region inside $c_1$ and $c_2$ into two disjoint regions.
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file rk_3_3.c * \brief Source file to optimize Runge-Kutta 3 steps 3rd order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_3_3.h" #define DEBUG_RK_3_3 0 ///< macro to debug. /** * Function to obtain the coefficients of a 3 steps 3rd order Runge-Kutta * method. */ int rk_tb_3_3 (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (b32 (tb))) return 0; b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb))); if (isnan (b31 (tb))) return 0; b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb)); if (isnan (b21 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_3 rk_print_tb (optimize, "rk_tb_3_3", stderr); fprintf (stderr, "rk_tb_3_3: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 3rd order, 4th order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_3_3t (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t3 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = (4.L * t1 (tb) - 3.L) / (6.L * t1 (tb) - 4.L); if (isnan (t2 (tb))) return 0; b32 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if ((b32 (tb))) return 0; b31 (tb) = (1.L / 3.L - 0.5L * t2 (tb)) / (t1 (tb) * (t1 (tb) - t2 (tb))); if (isnan (b31 (tb))) return 0; b21 (tb) = 1 / 6.L / (b32 (tb) * t1 (tb)); if (isnan (b21 (tb))) return 0; rk_b_3 (tb); #if DEBUG_RK_3_3 rk_print_tb (optimize, "rk_tb_3_3t", stderr); fprintf (stderr, "rk_tb_3_3t: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 2nd-3rd order Runge-Kutta * pair. */ int rk_tb_3_3p (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3p: start\n"); #endif if (!rk_tb_3_3 (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.5L / t1 (tb); rk_e_3 (tb); #if DEBUG_RK_3_3 rk_print_e (optimize, "rk_tb_3_3p", stderr); fprintf (stderr, "rk_tb_3_3p: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 3 steps 2nd-3rd order, 2nd-4th order * in equations depending only in time, Runge-Kutta pair. */ int rk_tb_3_3tp (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_3_3 fprintf (stderr, "rk_tb_3_3tp: start\n"); #endif if (!rk_tb_3_3t (optimize)) return 0; tb = optimize->coefficient; e31 (tb) = 0.5L / t1 (tb); rk_e_3 (tb); #if DEBUG_RK_3_3 rk_print_e (optimize, "rk_tb_3_3tp", stderr); fprintf (stderr, "rk_tb_3_3tp: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 3 steps 3rd order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_3 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 3rd order, 4th * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_3_3t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3t: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3: optimal=%Lg\n", o); #endif if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3t: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3t: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 2nd-3rd order * Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_3_3p (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (e30 (tb) < 0.L) o += e30 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3p: end\n"); #endif return o; } /** * Function to calculate the objective function of a 3 steps 2nd-3rd order, * 3rd-4th order in equations depending only in time, Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_3_3tp (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3tp: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b21 (tb) < 0.L) o += b21 (tb); if (b30 (tb) < 0.L) o += b30 (tb); if (b31 (tb) < 0.L) o += b31 (tb); if (b32 (tb) < 0.L) o += b32 (tb); if (e30 (tb) < 0.L) o += e30 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), t2 (tb))); #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3p: optimal=%Lg\n", o); #endif if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_3_3 fprintf (stderr, "rk_objective_tb_3_3tp: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_3_3tp: end\n"); #endif return o; }
State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s ⊢ f 1 ∈ s State After: no goals Tactic: (rw [IsMonoidHom.map_one hf]; exact hs.one_mem) State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s ⊢ f 1 ∈ s State After: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s ⊢ 1 ∈ s Tactic: rw [IsMonoidHom.map_one hf] State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s ⊢ 1 ∈ s State After: no goals Tactic: exact hs.one_mem State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s a b : M ha : f a ∈ s hb : f b ∈ s ⊢ f (a * b) ∈ s State After: no goals Tactic: (rw [IsMonoidHom.map_mul' hf]; exact hs.mul_mem ha hb) State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s a b : M ha : f a ∈ s hb : f b ∈ s ⊢ f (a * b) ∈ s State After: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s a b : M ha : f a ∈ s hb : f b ∈ s ⊢ f a * f b ∈ s Tactic: rw [IsMonoidHom.map_mul' hf] State Before: M : Type u_2 inst✝² : Monoid M s✝ : Set M A : Type ?u.24553 inst✝¹ : AddMonoid A t : Set A N : Type u_1 inst✝ : Monoid N f : M → N hf : IsMonoidHom f s : Set N hs : IsSubmonoid s a b : M ha : f a ∈ s hb : f b ∈ s ⊢ f a * f b ∈ s State After: no goals Tactic: exact hs.mul_mem ha hb
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.rat.meta_defs import Mathlib.tactic.norm_num import Mathlib.data.tree import Mathlib.meta.expr import Mathlib.PostPort universes u_1 namespace Mathlib /-! # A tactic for canceling numeric denominators This file defines tactics that cancel numeric denominators from field expressions. As an example, we want to transform a comparison `5*(a/3 + b/4) < c/3` into the equivalent `5*(4*a + 3*b) < 4*c`. ## Implementation notes The tooling here was originally written for `linarith`, not intended as an interactive tactic. The interactive version has been split off because it is sometimes convenient to use on its own. There are likely some rough edges to it. Improving this tactic would be a good project for someone interested in learning tactic programming. -/ namespace cancel_factors /-! ### Lemmas used in the procedure -/ theorem mul_subst {α : Type u_1} [comm_ring α] {n1 : α} {n2 : α} {k : α} {e1 : α} {e2 : α} {t1 : α} {t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1 * n2 = k) : k * (e1 * e2) = t1 * t2 := sorry theorem div_subst {α : Type u_1} [field α] {n1 : α} {n2 : α} {k : α} {e1 : α} {e2 : α} {t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1 * n2 = k) : k * (e1 / e2) = t1 := sorry theorem cancel_factors_eq_div {α : Type u_1} [field α] {n : α} {e : α} {e' : α} (h : n * e = e') (h2 : n ≠ 0) : e = e' / n := eq_div_of_mul_eq h2 (eq.mp (Eq._oldrec (Eq.refl (n * e = e')) (mul_comm n e)) h) theorem add_subst {α : Type u_1} [ring α] {n : α} {e1 : α} {e2 : α} {t1 : α} {t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := sorry theorem sub_subst {α : Type u_1} [ring α] {n : α} {e1 : α} {e2 : α} {t1 : α} {t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := sorry theorem neg_subst {α : Type u_1} [ring α] {n : α} {e : α} {t : α} (h1 : n * e = t) : n * -e = -t := sorry theorem cancel_factors_lt {α : Type u_1} [linear_ordered_field α] {a : α} {b : α} {ad : α} {bd : α} {a' : α} {b' : α} {gcd : α} (ha : ad * a = a') (hb : bd * b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a < b = (1 / gcd * (bd * a') < 1 / gcd * (ad * b')) := sorry theorem cancel_factors_le {α : Type u_1} [linear_ordered_field α] {a : α} {b : α} {ad : α} {bd : α} {a' : α} {b' : α} {gcd : α} (ha : ad * a = a') (hb : bd * b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a ≤ b = (1 / gcd * (bd * a') ≤ 1 / gcd * (ad * b')) := sorry theorem cancel_factors_eq {α : Type u_1} [linear_ordered_field α] {a : α} {b : α} {ad : α} {bd : α} {a' : α} {b' : α} {gcd : α} (ha : ad * a = a') (hb : bd * b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a = b = (1 / gcd * (bd * a') = 1 / gcd * (ad * b')) := sorry /-! ### Computing cancelation factors -/ /-- `find_cancel_factor e` produces a natural number `n`, such that multiplying `e` by `n` will be able to cancel all the numeric denominators in `e`. The returned `tree` describes how to distribute the value `n` over products inside `e`. -/ /-- `mk_prod_prf n tr e` produces a proof of `n*e = e'`, where numeric denominators have been canceled in `e'`, distributing `n` proportionally according to `tr`. -/ /-- Given `e`, a term with rational division, produces a natural number `n` and a proof of `n*e = e'`, where `e'` has no division. Assumes "well-behaved" division. -/ /-- Given `e`, a term with rational divison, produces a natural number `n` and a proof of `e = e' / n`, where `e'` has no divison. Assumes "well-behaved" division. -/ /-- `find_comp_lemma e` arranges `e` in the form `lhs R rhs`, where `R ∈ {<, ≤, =}`, and returns `lhs`, `rhs`, and the `cancel_factors` lemma corresponding to `R`. -/ /-- `cancel_denominators_in_type h` assumes that `h` is of the form `lhs R rhs`, where `R ∈ {<, ≤, =, ≥, >}`. It produces an expression `h'` of the form `lhs' R rhs'` and a proof that `h = h'`. Numeric denominators have been canceled in `lhs'` and `rhs'`. -/ end cancel_factors /-! ### Interactive version -/ /-- `cancel_denoms` attempts to remove numerals from the denominators of fractions. It works on propositions that are field-valued inequalities. ```lean variables {α : Type} [linear_ordered_field α] (a b c : α) example (h : a / 5 + b / 4 < c) : 4*a + 5*b < 20*c := begin cancel_denoms at h, exact h end example (h : a > 0) : a / 5 > 0 := begin cancel_denoms, exact h end ``` -/
theory MMU_Instants_TLB imports TLBJ.Simp_Lemmas TLBJ.ARM_Monadic begin record non_det_tlb_state = state + non_det_tlb :: "unit tlb" record det_tlb_state = state + det_tlb :: "unit tlb" record sat_tlb_state = state + sat_tlb :: "unit tlb" record set_tlb_state = state + set_tlb :: "vaddr set" definition typ_non_det_tlb :: "'a non_det_tlb_state_scheme \<Rightarrow> unit tlb state_scheme" where "typ_non_det_tlb s = state.extend (state.truncate s) (non_det_tlb s)" definition typ_det_tlb :: "'a det_tlb_state_scheme \<Rightarrow> unit tlb state_scheme" where "typ_det_tlb s = state.extend (state.truncate s) (det_tlb s)" definition typ_sat_tlb :: "'a sat_tlb_state_scheme \<Rightarrow> unit tlb state_scheme" where "typ_sat_tlb s = state.extend (state.truncate s) (sat_tlb s)" definition typ_set_tlb :: "'a set_tlb_state_scheme \<Rightarrow> vaddr set state_scheme" where "typ_set_tlb s = state.extend (state.truncate s) (set_tlb s)" lemma non_det_tlb_more [simp]: "state.more (typ_non_det_tlb s) = non_det_tlb s" by (clarsimp simp: typ_non_det_tlb_def state.defs) lemma det_tlb_more [simp]: "state.more (typ_det_tlb s) = det_tlb s" by (clarsimp simp: typ_det_tlb_def state.defs) lemma sat_tlb_more [simp]: "state.more (typ_sat_tlb s) = sat_tlb s" by (clarsimp simp: typ_sat_tlb_def state.defs) lemma set_tlb_more [simp]: "state.more (typ_set_tlb s) = set_tlb s" by (clarsimp simp: typ_set_tlb_def state.defs) lemma non_det_tlb_truncate [simp]: "state.truncate (typ_non_det_tlb s') = state.truncate s'" by (clarsimp simp: typ_non_det_tlb_def state.defs) lemma det_tlb_truncate [simp]: "state.truncate (typ_det_tlb s') = state.truncate s'" by (clarsimp simp: typ_det_tlb_def state.defs) lemma sat_tlb_truncate [simp]: "state.truncate (typ_sat_tlb s') = state.truncate s'" by (clarsimp simp: typ_sat_tlb_def state.defs) lemma set_tlb_truncate [simp]: "state.truncate (typ_set_tlb s') = state.truncate s'" by (clarsimp simp: typ_set_tlb_def state.defs) lemma typ_non_det_prim_parameter [simp]: "TTBR0 (typ_non_det_tlb s) = TTBR0 s \<and> MEM (typ_non_det_tlb s) = MEM s \<and> exception (typ_non_det_tlb s) = exception s" by (clarsimp simp: typ_non_det_tlb_def state.defs) lemma typ_det_prim_parameter [simp]: "TTBR0 (typ_det_tlb s) = TTBR0 s \<and> MEM (typ_det_tlb s) = MEM s \<and> exception (typ_det_tlb s) = exception s" by (clarsimp simp: typ_det_tlb_def state.defs) lemma typ_sat_prim_parameter [simp]: "TTBR0 (typ_sat_tlb s) = TTBR0 s \<and> MEM (typ_sat_tlb s) = MEM s \<and> exception (typ_sat_tlb s) = exception s" by (clarsimp simp: typ_sat_tlb_def state.defs) lemma typ_set_prim_parameter [simp]: "TTBR0 (typ_set_tlb s) = TTBR0 s \<and> MEM (typ_set_tlb s) = MEM s \<and> exception (typ_set_tlb s) = exception s" by (clarsimp simp: typ_set_tlb_def state.defs) abbreviation "consistent (s:: unit tlb_entry set state_scheme) \<equiv> consistent0 (lookup' (state.more s)) (pt_walk () (MEM s) (TTBR0 s))" definition saturated :: "unit tlb_entry set state_scheme \<Rightarrow> bool" where "saturated s \<equiv> the ` {e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not>is_fault e} \<subseteq> state.more s" definition tlb_rel_det :: "unit tlb_entry set state_scheme \<Rightarrow> unit tlb_entry set state_scheme \<Rightarrow> bool" where "tlb_rel_det s t \<equiv> state.truncate s = state.truncate t \<and> state.more s \<subseteq> state.more t" definition tlb_rel_sat :: "unit tlb_entry set state_scheme \<Rightarrow> unit tlb_entry set state_scheme \<Rightarrow> bool" where "tlb_rel_sat s t \<equiv> state.truncate s = state.truncate t \<and> state.more s \<subseteq> state.more t \<and> saturated t" definition inconsistent_vaddrs :: "unit tlb_entry set state_scheme \<Rightarrow> vaddr set" where "inconsistent_vaddrs s \<equiv> {va. lookup' (state.more s) va = Incon}" definition incoherrent_vaddrs :: "unit tlb_entry set state_scheme \<Rightarrow> vaddr set" where "incoherrent_vaddrs s \<equiv> {va. \<exists>x. lookup' (state.more s) va = Hit x \<and> is_fault (pt_walk () (MEM s) (TTBR0 s) va)} " definition incon_addrs :: "unit tlb_entry set state_scheme \<Rightarrow> vaddr set" where "incon_addrs s \<equiv> inconsistent_vaddrs s \<union> incoherrent_vaddrs s" definition tlb_rel_abs :: "unit tlb_entry set state_scheme \<Rightarrow> vaddr set state_scheme \<Rightarrow> bool" where "tlb_rel_abs s t \<equiv> state.truncate s = state.truncate t \<and> incon_addrs s \<subseteq> state.more t \<and> saturated s" declare return_def [simp add] declare bind_def [simp add] declare read_state_def [simp add] declare update_state_def [simp add] declare extend_state_def [simp add] declare trim_state_def [simp add] lemma tlb_rel_detD: "tlb_rel_det s t \<Longrightarrow> MEM t = MEM s \<and> TTBR0 t = TTBR0 s \<and> state.more s \<subseteq> state.more t \<and> exception t = exception s" by (clarsimp simp: tlb_rel_det_def state.defs) lemma tlb_rel_satD: "tlb_rel_sat s t \<Longrightarrow> MEM t = MEM s \<and> TTBR0 t = TTBR0 s \<and> state.more s \<subseteq> state.more t \<and> exception t = exception s \<and> saturated t" by (clarsimp simp: tlb_rel_sat_def state.defs) lemma tlb_rel_det_consistent: "\<lbrakk> tlb_rel_det s t; consistent t va \<rbrakk> \<Longrightarrow> consistent s va" by (insert tlb_rel_detD [of s t] , clarsimp ,drule tlb_mono [of _ _ "va"] ,auto simp: consistent0_def less_eq_lookup_type) lemma tlb_rel_sat_consistent: "\<lbrakk> tlb_rel_sat s t; consistent t va \<rbrakk> \<Longrightarrow> consistent s va" by (insert tlb_rel_satD [of s t] , clarsimp ,drule tlb_mono [of _ _ "va"] ,auto simp: consistent0_def less_eq_lookup_type) lemma sat_state_tlb: "saturated s \<Longrightarrow> state.more s = state.more s \<union> the ` {e \<in> range (pt_walk () (MEM s) (TTBR0 s)). \<not> is_fault e}" by (fastforce simp: saturated_def) lemma saturated_tlb_pde: "saturated (typ_sat_tlb s) \<Longrightarrow> (sat_tlb s) = sat_tlb s \<union> the ` {e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not>is_fault e}" apply (clarsimp simp: saturated_def fst_def) apply (cases s ; clarsimp) by blast lemma sat_miss_fault: "\<lbrakk> saturated (typ_sat_tlb s); lookup' (sat_tlb s) va = Miss \<rbrakk> \<Longrightarrow> is_fault (pt_walk () (MEM s) (TTBR0 s) va)" apply (subgoal_tac " lookup' ((sat_tlb s) \<union> the ` {e \<in> range (pt_walk () (MEM s) (TTBR0 s)). \<not> is_fault e}) va = Miss") apply (thin_tac "lookup' ((sat_tlb s)) va = Miss") apply (drule lookup_miss_union) apply clarsimp apply (drule lookup_miss_is_fault) apply clarsimp using sat_state_tlb by force lemma saturatd_lookup_hit_no_fault: "\<lbrakk>saturated (typ_sat_tlb s); lookup' (sat_tlb s) b = Hit x; \<not> is_fault (pt_walk () (MEM s) (TTBR0 s) b)\<rbrakk> \<Longrightarrow> x = the (pt_walk () (MEM s) (TTBR0 s) b)" apply (subgoal_tac "lookup'(sat_tlb s \<union> the ` {e \<in> range (pt_walk () (MEM s) (TTBR0 s)). \<not> is_fault e}) ( b) = Hit x") prefer 2 apply (drule sat_state_tlb, clarsimp simp: state.defs) apply (drule lookup_hit_miss_or_hit') apply (erule disjE) apply (clarsimp simp: lookup_range_pt_walk_hit) apply (frule lookup_range_fault_pt_walk) apply (drule_tac x = b in bspec; clarsimp simp: lookup_hit_entry_range) done lemma saturated_tlb: "saturated (typ_sat_tlb s) \<Longrightarrow> sat_tlb s = sat_tlb s \<union> the ` {e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not>is_fault e} " apply (clarsimp simp: saturated_def fst_def) apply (cases s ; clarsimp) by blast lemma write_mem_eq_TLB: "\<lbrakk> write'mem1 (val, va, sz) s = ((), s') \<rbrakk> \<Longrightarrow> state.more s' = state.more s" by (clarsimp simp: write'mem1_def raise'exception_def split: if_split_asm) lemma write_same_mem: "\<lbrakk> write'mem1 (val, va, sz) s = ((), s') ; write'mem1 (val, va, sz) t = ((), t') ; MEM s = MEM t\<rbrakk> \<Longrightarrow> MEM s' = MEM t'" by (clarsimp simp: write'mem1_def raise'exception_def split:if_split_asm) lemma write_same_mem_excep: "\<lbrakk> write'mem1 (val, pa, sz) s = ((), s') ; write'mem1 (val, pa, sz) t = ((), t') ; MEM s = MEM t ; exception s = exception t \<rbrakk> \<Longrightarrow> exception s' = exception t'" by (clarsimp simp: write'mem1_def raise'exception_def split:if_split_asm) lemma write_mem_rel: "\<lbrakk> write'mem1 (val, va, sz) s = ((), s') \<rbrakk> \<Longrightarrow> s' = s \<lparr> MEM:= MEM s' , exception:= exception s' \<rparr>" by (clarsimp simp: write'mem1_def raise'exception_def split: if_split_asm) lemma not_member_incon_consistent: "\<lbrakk>va \<notin> incon_addrs (typ_sat_tlb s) ; saturated (typ_sat_tlb s) \<rbrakk> \<Longrightarrow> consistent (typ_sat_tlb s) va" apply (clarsimp simp: incon_addrs_def inconsistent_vaddrs_def incoherrent_vaddrs_def consistent0_def) apply (erule disjE) apply (rule conjI) apply (meson lookup_type.exhaust ) apply (meson lookup_type.exhaust) using not_miss_incon_hit saturatd_lookup_hit_no_fault by blast lemma tlb_rel_abs_consistent [simp]: "\<lbrakk>va \<notin> set_tlb t ; tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t) \<rbrakk> \<Longrightarrow> consistent (typ_sat_tlb s) va " apply (rule not_member_incon_consistent ; clarsimp simp: tlb_rel_abs_def) by blast lemma tlb_rel_absD: "tlb_rel_abs s t \<Longrightarrow> MEM t = MEM s \<and> TTBR0 t = TTBR0 s \<and> saturated s \<and> incon_addrs s \<subseteq> state.more t \<and> exception t = exception s" by (clarsimp simp: tlb_rel_abs_def state.defs) (* ARM Monadic Simplification Lemmas *) lemma mem1_exception: "mem1 p s = (val, t) \<Longrightarrow> t = s\<lparr>exception := exception t\<rparr>" apply (clarsimp simp: mem1_def) apply (cases "MEM s p") apply (clarsimp simp: raise'exception_def split: if_split_asm) apply clarsimp done lemma mem1_read_exception: "mem_read1 (a, sz) b = (val, r) \<Longrightarrow> r = b \<lparr>exception := exception r\<rparr>" apply (clarsimp simp: mem_read1_def) apply (clarsimp split: if_split_asm) apply (case_tac "mem1 (a r+ 0) b" , clarsimp) apply (clarsimp simp: mem1_exception) apply (case_tac "mem1 (a r+ 1) b" , clarsimp) apply (case_tac "mem1 (a r+ 0) ba", clarsimp) apply (drule mem1_exception) apply (drule mem1_exception) apply (cases b, case_tac ba, cases r ,clarsimp) apply (case_tac "mem1 (a r+ 3) b" , clarsimp) apply (case_tac "mem1 (a r+ 2) ba", clarsimp) apply (case_tac "mem1 (a r+ 1) baa", clarsimp) apply (case_tac "mem1 (a r+ 0) bb", clarsimp) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (cases b, case_tac ba, case_tac baa, case_tac bb , cases r ,clarsimp) apply (case_tac "mem1 (a r+ 7) b" , clarsimp) apply (case_tac "mem1 (a r+ 6) ba", clarsimp) apply (case_tac "mem1 (a r+ 5) baa", clarsimp) apply (case_tac "mem1 (a r+ 4) bb", clarsimp) apply (case_tac "mem1 (a r+ 3) bc", clarsimp) apply (case_tac "mem1 (a r+ 2) bd", clarsimp) apply (case_tac "mem1 (a r+ 1) be", clarsimp) apply (case_tac "mem1 (a r+ 0) bf", clarsimp) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (drule mem1_exception) apply (cases b, case_tac ba, case_tac baa, case_tac bb ,case_tac bc , case_tac bd , case_tac be , case_tac bf , cases r ,clarsimp) apply (clarsimp simp: raise'exception_def split:if_split_asm) done lemma write_mem_state_trun_equal: "\<lbrakk> write'mem1 (val, pa, sz) s = ((), s'); write'mem1 (val, pa, sz) t = ((), t'); state.truncate s = state.truncate t \<rbrakk> \<Longrightarrow> state.truncate s' = state.truncate t'" apply (frule write_mem_rel) apply rotate_tac apply (frule write_mem_rel) apply (subgoal_tac "MEM s' = MEM t' \<and> exception s' = exception t'") apply clarsimp apply (cases s, cases t, cases s', cases t', clarsimp simp: state.defs) apply (cases s, cases t, cases s', cases t', clarsimp simp: state.defs) apply (clarsimp simp: write'mem1_def Let_def state.defs raise'exception_def split:if_split_asm) done lemma write_mem1_eq_ASID_TTBR0: "\<lbrakk> write'mem1 (val, va, sz) s = ((), s') \<rbrakk> \<Longrightarrow> TTBR0 s' = TTBR0 s" by (clarsimp simp: write'mem1_def raise'exception_def split: if_split_asm) lemma tlb_sat_set_mem1 [simp]: "sat_tlb (snd (mem1 ps s)) = sat_tlb s" by (simp add: mem1_def raise'exception_def split: option.splits) consts tlb_evict :: "'a state_scheme \<Rightarrow> 'a" instantiation non_det_tlb_state_ext :: (type) mmu begin definition "(mmu_translate va :: ('a non_det_tlb_state_scheme \<Rightarrow> _)) = do { update_state (\<lambda>s. s\<lparr> non_det_tlb := non_det_tlb s - tlb_evict (typ_non_det_tlb s) \<rparr>); mem <- read_state MEM; ttbr0 <- read_state TTBR0; tlb <- read_state non_det_tlb; case lookup' tlb va of Hit entry \<Rightarrow> return (va_to_pa va entry) | Miss \<Rightarrow> do { let entry = pt_walk () mem ttbr0 va; if is_fault entry then raise'exception (PAGE_FAULT ''more info'') else do { update_state (\<lambda>s. s\<lparr> non_det_tlb := non_det_tlb s \<union> {the entry} \<rparr>); return (va_to_pa va (the entry)) } } | Incon \<Rightarrow> raise'exception (IMPLEMENTATION_DEFINED ''set on fire'') }" thm mmu_translate_non_det_tlb_state_ext_def definition "(mmu_read_size :: (vaddr \<times> nat \<Rightarrow> 'a non_det_tlb_state_scheme \<Rightarrow> bool list \<times> 'a non_det_tlb_state_scheme)) \<equiv> \<lambda>(va,size). do { pa \<leftarrow> mmu_translate va :: ('a non_det_tlb_state_scheme \<Rightarrow> _); mem_read1 (pa , size) }" definition "(mmu_write_size :: (bool list \<times> vaddr \<times> nat \<Rightarrow> 'a non_det_tlb_state_scheme \<Rightarrow> unit \<times> 'a non_det_tlb_state_scheme)) \<equiv> \<lambda>(value, va, size). do { pa <- mmu_translate va :: ('a non_det_tlb_state_scheme \<Rightarrow> _); exception <- read_state exception; if exception = NoException then write'mem1 (value, pa, size) else return () }" (* print_context *) definition "(update_TTBR0 r :: ('a non_det_tlb_state_scheme \<Rightarrow> _)) = do { update_state (\<lambda>s. s\<lparr> TTBR0 := r \<rparr>) } " definition "(flush f :: ('a non_det_tlb_state_scheme \<Rightarrow> _)) \<equiv> case f of FlushTLB \<Rightarrow> update_state (\<lambda>s. s\<lparr> non_det_tlb := {} \<rparr>) | Flushvarange vset \<Rightarrow> do { update_state (\<lambda>s. s\<lparr> non_det_tlb := flush_tlb_vset (non_det_tlb s) vset \<rparr>)}" instance .. end instantiation det_tlb_state_ext :: (_) mmu begin definition "(mmu_translate va :: ('a det_tlb_state_scheme \<Rightarrow> _)) = do { mem <- read_state MEM; ttbr0 <- read_state TTBR0; tlb <- read_state det_tlb; case lookup' tlb va of Hit entry \<Rightarrow> return (va_to_pa va entry) | Miss \<Rightarrow> do { let entry = pt_walk () mem ttbr0 va; if is_fault entry then raise'exception (PAGE_FAULT ''more info'') else do { update_state (\<lambda>s. s\<lparr> det_tlb := det_tlb s \<union> {the entry} \<rparr>); return (va_to_pa va (the entry)) } } | Incon \<Rightarrow> raise'exception (IMPLEMENTATION_DEFINED ''set on fire'') }" thm mmu_translate_non_det_tlb_state_ext_def definition "(mmu_read_size :: (vaddr \<times> nat \<Rightarrow> 'a det_tlb_state_scheme \<Rightarrow> bool list \<times> 'a det_tlb_state_scheme)) \<equiv> \<lambda>(va,size). do { pa \<leftarrow> mmu_translate va :: ('a det_tlb_state_scheme \<Rightarrow> _); mem_read1 (pa , size) }" definition "(mmu_write_size :: (bool list \<times> vaddr \<times> nat \<Rightarrow> 'a det_tlb_state_scheme \<Rightarrow> unit \<times> 'a det_tlb_state_scheme)) \<equiv> \<lambda>(value, va, size). do { pa <- mmu_translate va :: ('a det_tlb_state_scheme \<Rightarrow> _); exception <- read_state exception; if exception = NoException then write'mem1 (value, pa, size) else return () }" (* print_context *) definition "(update_TTBR0 r :: ('a det_tlb_state_scheme \<Rightarrow> _)) = do { update_state (\<lambda>s. s\<lparr> TTBR0 := r \<rparr>) } " definition "(flush f :: ('a det_tlb_state_scheme \<Rightarrow> _)) \<equiv> case f of FlushTLB \<Rightarrow> update_state (\<lambda>s. s\<lparr> det_tlb := {} \<rparr>) | Flushvarange vset \<Rightarrow> do { update_state (\<lambda>s. s\<lparr> det_tlb := flush_tlb_vset (det_tlb s) vset \<rparr>)}" instance .. end instantiation sat_tlb_state_ext :: (_) mmu begin definition "(mmu_translate va :: ('a sat_tlb_state_scheme \<Rightarrow> _)) = do { mem <- read_state MEM; ttbr0 <- read_state TTBR0; let tlb_new = the ` {e\<in>pt_walk () mem ttbr0 ` UNIV. \<not>is_fault e}; tlb <- read_state sat_tlb; let sat_tlb' = tlb \<union> tlb_new; update_state (\<lambda>s. s\<lparr> sat_tlb := sat_tlb' \<rparr>); case lookup' sat_tlb' va of Hit entry \<Rightarrow> return (va_to_pa va entry) | Miss \<Rightarrow> raise'exception (PAGE_FAULT ''more info'') | Incon \<Rightarrow> raise'exception (IMPLEMENTATION_DEFINED ''set on fire'') }" thm mmu_translate_non_det_tlb_state_ext_def definition "(mmu_read_size :: (vaddr \<times> nat \<Rightarrow> 'a sat_tlb_state_scheme \<Rightarrow> bool list \<times> 'a sat_tlb_state_scheme)) \<equiv> \<lambda>(va,size). do { pa \<leftarrow> mmu_translate va :: ('a sat_tlb_state_scheme \<Rightarrow> _); mem_read1 (pa , size) }" definition "(mmu_write_size :: (bool list \<times> vaddr \<times> nat \<Rightarrow> 'a sat_tlb_state_scheme \<Rightarrow> unit \<times> 'a sat_tlb_state_scheme)) \<equiv> \<lambda>(value, va, size). do { ttbr0 <- read_state TTBR0; pa <- mmu_translate va :: ('a sat_tlb_state_scheme \<Rightarrow> _); tlb <- read_state sat_tlb; exception <- read_state exception; if exception = NoException then do { write'mem1 (value, pa, size); mem' <- read_state MEM; let tlb_new = the ` {e\<in>pt_walk () mem' ttbr0 ` UNIV. \<not>is_fault e}; update_state (\<lambda>s. s\<lparr> sat_tlb := tlb \<union> tlb_new \<rparr>) } else return () }" (* print_context *) definition "(update_TTBR0 r :: ('a sat_tlb_state_scheme \<Rightarrow> _)) = do { update_state (\<lambda>s. s\<lparr> TTBR0 := r \<rparr>); mem <- read_state MEM; let all_entries = the ` {e\<in>pt_walk () mem r ` UNIV. \<not>is_fault e}; tlb <- read_state sat_tlb; update_state (\<lambda>s. s\<lparr> sat_tlb := tlb \<union> all_entries \<rparr>)}" definition "(flush f :: ('a sat_tlb_state_scheme \<Rightarrow> _)) \<equiv> case f of FlushTLB \<Rightarrow> do {update_state (\<lambda>s. s\<lparr> sat_tlb := {} \<rparr>); mem <- read_state MEM; ttbr0 <- read_state TTBR0; let tlb_new = the ` {e\<in>pt_walk () mem ttbr0 ` UNIV. \<not>is_fault e}; update_state (\<lambda>s. s\<lparr> sat_tlb := tlb_new \<rparr>)} | Flushvarange vset \<Rightarrow> do { mem <- read_state MEM; ttbr0 <- read_state TTBR0; let tlb_new = the ` {e\<in>pt_walk () mem ttbr0 ` UNIV. \<not>is_fault e}; tlb_pde <- read_state sat_tlb; update_state (\<lambda>s. s\<lparr> sat_tlb := flush_tlb_vset tlb_pde vset \<union> tlb_new \<rparr>)}" instance .. end (*definition ptable_comp :: "(vaddr \<Rightarrow> pt_walk_typ) \<Rightarrow> (vaddr \<Rightarrow> pt_walk_typ) \<Rightarrow> vaddr set" where "ptable_comp walk walk' \<equiv> {va. \<not>(walk va \<preceq> walk' va)}" *) definition ptable_comp :: "(vaddr \<Rightarrow> unit tlb_entry option) \<Rightarrow> (vaddr \<Rightarrow> unit tlb_entry option) \<Rightarrow> vaddr set" where "ptable_comp wlk wlk' \<equiv> {va. \<not> is_fault (wlk va) \<and> \<not> is_fault (wlk' va) \<and> wlk va \<noteq> wlk' va \<or> \<not> is_fault (wlk va) \<and> is_fault (wlk' va)}" definition incon_comp :: " heap \<Rightarrow> heap \<Rightarrow> paddr \<Rightarrow> paddr \<Rightarrow> vaddr set" where "incon_comp hp hp' rt rt' \<equiv> ptable_comp (pt_walk () hp rt) (pt_walk () hp' rt')" instantiation set_tlb_state_ext :: (_) mmu begin definition "(mmu_translate va :: ('a set_tlb_state_scheme \<Rightarrow> _)) = do { mem <- read_state MEM; ttbr0 <- read_state TTBR0; incon_vaddrs <- read_state set_tlb; if va \<in> incon_vaddrs then raise'exception (IMPLEMENTATION_DEFINED ''set on fire'') else let entry = pt_walk () mem ttbr0 va in if is_fault entry then raise'exception (PAGE_FAULT ''more info'') else return (va_to_pa va (the entry)) }" definition "(mmu_read_size :: (vaddr \<times> nat \<Rightarrow> 'a set_tlb_state_scheme \<Rightarrow> bool list \<times> 'a set_tlb_state_scheme)) \<equiv> \<lambda>(va,size). do { pa \<leftarrow> mmu_translate va :: ('a set_tlb_state_scheme \<Rightarrow> _); mem_read1 (pa , size) }" definition "(mmu_write_size :: (bool list \<times> vaddr \<times> nat \<Rightarrow> 'a set_tlb_state_scheme \<Rightarrow> unit \<times> 'a set_tlb_state_scheme)) \<equiv> \<lambda>(value, va, size). do { ttbr0 <- read_state TTBR0; mem <- read_state MEM; paddr <- mmu_translate va :: ('a set_tlb_state_scheme \<Rightarrow> _); incon_vaddrs <- read_state set_tlb; exception <- read_state exception; if exception = NoException then do { write'mem1 (value, paddr, size); mem' <- read_state MEM; let ptable_comp = incon_comp mem mem' ttbr0 ttbr0; let incon_vaddrs_new = incon_vaddrs \<union> ptable_comp; update_state (\<lambda>s. s\<lparr> set_tlb := incon_vaddrs_new \<rparr>) } else return () }" definition "(update_TTBR0 r :: ('a set_tlb_state_scheme \<Rightarrow> _)) = do { ttbr0 <- read_state TTBR0; update_state (\<lambda>s. s\<lparr> TTBR0 := r \<rparr>); incon_vaddrs <- read_state set_tlb; mem <- read_state MEM; let ptable_comp = incon_comp mem mem ttbr0 r; let incon_vaddrs_new = incon_vaddrs \<union> ptable_comp; update_state (\<lambda>s. s\<lparr> set_tlb := incon_vaddrs_new \<rparr>) }" definition "(flush f :: ('a set_tlb_state_scheme \<Rightarrow> _)) \<equiv> case f of FlushTLB \<Rightarrow> update_state (\<lambda>s. s\<lparr> set_tlb := {} \<rparr>) | Flushvarange vset \<Rightarrow> do { incon_vaddrs <- read_state set_tlb; update_state (\<lambda>s. s\<lparr> set_tlb := incon_vaddrs -vset\<rparr>)}" instance .. end end
%Terminals DollarSign ::= '$' Percent ::= '%' _ a b c d e f g h i j k l m n o p q r s t u v w x y z %End %Headers /. final static int tokenKind[] = new int[128]; static { tokenKind['$'] = $sym_type.$prefix$DollarSign$suffix$; tokenKind['%'] = $sym_type.$prefix$Percent$suffix$; tokenKind['_'] = $sym_type.$prefix$_$suffix$; tokenKind['a'] = $sym_type.$prefix$a$suffix$; tokenKind['b'] = $sym_type.$prefix$b$suffix$; tokenKind['c'] = $sym_type.$prefix$c$suffix$; tokenKind['d'] = $sym_type.$prefix$d$suffix$; tokenKind['e'] = $sym_type.$prefix$e$suffix$; tokenKind['f'] = $sym_type.$prefix$f$suffix$; tokenKind['g'] = $sym_type.$prefix$g$suffix$; tokenKind['h'] = $sym_type.$prefix$h$suffix$; tokenKind['i'] = $sym_type.$prefix$i$suffix$; tokenKind['j'] = $sym_type.$prefix$j$suffix$; tokenKind['k'] = $sym_type.$prefix$k$suffix$; tokenKind['l'] = $sym_type.$prefix$l$suffix$; tokenKind['m'] = $sym_type.$prefix$m$suffix$; tokenKind['n'] = $sym_type.$prefix$n$suffix$; tokenKind['o'] = $sym_type.$prefix$o$suffix$; tokenKind['p'] = $sym_type.$prefix$p$suffix$; tokenKind['q'] = $sym_type.$prefix$q$suffix$; tokenKind['r'] = $sym_type.$prefix$r$suffix$; tokenKind['s'] = $sym_type.$prefix$s$suffix$; tokenKind['t'] = $sym_type.$prefix$t$suffix$; tokenKind['u'] = $sym_type.$prefix$u$suffix$; tokenKind['v'] = $sym_type.$prefix$v$suffix$; tokenKind['w'] = $sym_type.$prefix$w$suffix$; tokenKind['x'] = $sym_type.$prefix$x$suffix$; tokenKind['y'] = $sym_type.$prefix$y$suffix$; tokenKind['z'] = $sym_type.$prefix$z$suffix$; }; final int getKind(int c) { return ((c & 0xFFFFFF80) == 0 /* 0 <= c < 128? */ ? tokenKind[c] : 0); } ./ %End
module Dbcritic.Check.PrimaryKey import Control.IOExcept import Dbcritic.Check import Dbcritic.Libpq mkIssue : String -> Issue mkIssue table = let identifier = [ table ] description = "The table ‘" ++ table ++ "’ is missing a primary key constraint." problems = [ "Rows cannot be individually addressed when updating or deleting them." , "Rows cannot be individually addressed by potential foreign keys." , "Some tools expect tables to have primary keys to function properly." ] solutions = [ "Create a primary key constraint on ‘" ++ table ++ "’." ] in MkIssue identifier description problems solutions IsNonEmpty IsNonEmpty IsNonEmpty export checkPrimaryKey : Check checkPrimaryKey = MkCheck name help inspect where name = "primary_key" help = "Check that each table has a primary key constraint." inspectRow : List (Maybe String) -> IOExcept String Issue inspectRow [Just table] = pure (mkIssue table) inspectRow _ = ioe_fail "checkPrimaryKey: Bad result" inspect : PgConnection -> IOExcept String (List Issue) inspect conn = do res <- pgExecute conn """ SELECT relname FROM pg_class WHERE relkind = 'r' AND NOT EXISTS ( SELECT FROM pg_constraint WHERE conrelid = pg_class.oid AND contype = 'p' ) AND relnamespace <> regnamespace 'information_schema' AND relnamespace <> regnamespace 'pg_catalog' ORDER BY relname ASC """ traverse inspectRow (pgGrid res)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F import numpy as np import numpy.random as npr from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.modeling.matcher import Matcher from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou from maskrcnn_benchmark.modeling.balanced_positive_negative_sampler import ( BalancedPositiveNegativeSampler ) from maskrcnn_benchmark.modeling.utils import cat class FastRCNNSampling(object): """ Sampling RoIs """ def __init__( self, proposal_matcher, fg_bg_sampler, box_coder, ): """ Arguments: proposal_matcher (Matcher) fg_bg_sampler (BalancedPositiveNegativeSampler) box_coder (BoxCoder) """ self.proposal_matcher = proposal_matcher self.fg_bg_sampler = fg_bg_sampler self.box_coder = box_coder def match_targets_to_proposals(self, proposal, target): match_quality_matrix = boxlist_iou(target, proposal) matched_idxs = self.proposal_matcher(match_quality_matrix) # Fast RCNN only need "labels" field for selecting the targets target = target.copy_with_fields(["labels", "attributes"]) # get the targets corresponding GT for each proposal # NB: need to clamp the indices because we can have a single # GT in the image, and matched_idxs can be -2, which goes # out of bounds matched_targets = target[matched_idxs.clamp(min=0)] matched_targets.add_field("matched_idxs", matched_idxs) return matched_targets def prepare_targets(self, proposals, targets): labels = [] attributes = [] regression_targets = [] matched_idxs = [] for proposals_per_image, targets_per_image in zip(proposals, targets): matched_targets = self.match_targets_to_proposals( proposals_per_image, targets_per_image ) matched_idxs_per_image = matched_targets.get_field("matched_idxs") labels_per_image = matched_targets.get_field("labels") attris_per_image = matched_targets.get_field("attributes") labels_per_image = labels_per_image.to(dtype=torch.int64) attris_per_image = attris_per_image.to(dtype=torch.int64) # Label background (below the low threshold) bg_inds = matched_idxs_per_image == Matcher.BELOW_LOW_THRESHOLD labels_per_image[bg_inds] = 0 attris_per_image[bg_inds,:] = 0 # Label ignore proposals (between low and high thresholds) ignore_inds = matched_idxs_per_image == Matcher.BETWEEN_THRESHOLDS labels_per_image[ignore_inds] = -1 # -1 is ignored by sampler # compute regression targets regression_targets_per_image = self.box_coder.encode( matched_targets.bbox, proposals_per_image.bbox ) labels.append(labels_per_image) attributes.append(attris_per_image) regression_targets.append(regression_targets_per_image) matched_idxs.append(matched_idxs_per_image) return labels, attributes, regression_targets, matched_idxs def subsample(self, proposals, targets): """ This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state. Arguments: proposals (list[BoxList]) targets (list[BoxList]) """ labels, attributes, regression_targets, matched_idxs = self.prepare_targets(proposals, targets) sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) proposals = list(proposals) # add corresponding label and regression_targets information to the bounding boxes for labels_per_image, attributes_per_image, regression_targets_per_image, matched_idxs_per_image, proposals_per_image in zip( labels, attributes, regression_targets, matched_idxs, proposals ): proposals_per_image.add_field("labels", labels_per_image) proposals_per_image.add_field("attributes", attributes_per_image) proposals_per_image.add_field("regression_targets", regression_targets_per_image) proposals_per_image.add_field("matched_idxs", matched_idxs_per_image) # distributed sampled proposals, that were obtained on all feature maps # concatenated via the fg_bg_sampler, into individual feature map levels for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)): img_sampled_inds = torch.nonzero(pos_inds_img | neg_inds_img).squeeze(1) proposals_per_image = proposals[img_idx][img_sampled_inds] proposals[img_idx] = proposals_per_image return proposals def assign_label_to_proposals(self, proposals, targets): for img_idx, (target, proposal) in enumerate(zip(targets, proposals)): match_quality_matrix = boxlist_iou(target, proposal) # proposal.bbox.shape[0]; -1 is below low threshold; -2 is between thresholds; the others are matched gt indices matched_idxs = self.proposal_matcher(match_quality_matrix) # Fast RCNN only need "labels" field for selecting the targets target = target.copy_with_fields(["labels", "attributes"]) # only copy "labels" and "attributes" to extra_fields (dict) matched_targets = target[matched_idxs.clamp(min=0)] # index items like List labels_per_image = matched_targets.get_field("labels").to(dtype=torch.int64) attris_per_image = matched_targets.get_field("attributes").to(dtype=torch.int64) labels_per_image[matched_idxs < 0] = 0 # background attris_per_image[matched_idxs < 0, :] = 0 # background proposals[img_idx].add_field("labels", labels_per_image) proposals[img_idx].add_field("attributes", attris_per_image) return proposals def assign_label_to_proposals_by_dict(self, proposals, targets, cls_dict): """ Instead of using box location to match gt objects, use a dictionary to assign gt object labels """ device = proposals[0].bbox.device for img_idx, (target, proposal) in enumerate(zip(targets, proposals)): # detected cls --> vg cls --> check whether exist in gt cls --> if so, randomly select the gt cls, and then random one gt object det_dist = proposal.extra_fields['det_dist'] # the dist after softmax det_cls = torch.argmax(det_dist, dim=1).cpu().numpy() gt_cls = target.get_field("labels").cpu().numpy() dict_matched_idxs = [] for i, det_c in enumerate(det_cls): # for each detector cls, there might be multiple corresponding vg cls vg_cls = cls_dict[det_c] cls_cand = [vg_c for vg_c in vg_cls if vg_c in gt_cls] if len(cls_cand) == 0: # no matched gt cls dict_matched_idxs.append(-99) else: # there are gt cls that can be matched to detected objects, then randomly select one selected_cls = cls_cand[npr.permutation(np.arange(len(cls_cand)))[0]] # there are multiple gt objects that have same gt cls, then randomly select one, # though it's class-level selection in this function (not instance-level selection) obj_cand = [gt_i for gt_i, gt_c in enumerate(gt_cls) if gt_c == selected_cls] selected_obj = obj_cand[npr.permutation(np.arange(len(obj_cand)))[0]] dict_matched_idxs.append(selected_obj) dict_matched_idxs = torch.tensor(dict_matched_idxs, dtype=torch.long).to(device) ################# the following is the same as assign_label_to_proposals ################# #match_quality_matrix = boxlist_iou(target, proposal) # proposal.bbox.shape[0]; -1 is below low threshold; -2 is between thresholds; the others are matched gt indices #matched_idxs = self.proposal_matcher(match_quality_matrix) matched_idxs = dict_matched_idxs # Fast RCNN only need "labels" field for selecting the targets target = target.copy_with_fields(["labels", "attributes"]) # only copy "labels" and "attributes" to extra_fields (dict) matched_targets = target[matched_idxs.clamp(min=0)] # index items like List labels_per_image = matched_targets.get_field("labels").to(dtype=torch.int64) attris_per_image = matched_targets.get_field("attributes").to(dtype=torch.int64) labels_per_image[matched_idxs < 0] = 0 # background attris_per_image[matched_idxs < 0, :] = 0 # background proposals[img_idx].add_field("labels", labels_per_image) proposals[img_idx].add_field("attributes", attris_per_image) return proposals def make_roi_box_samp_processor(cfg): matcher = Matcher( cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD, cfg.MODEL.ROI_HEADS.BG_IOU_THRESHOLD, allow_low_quality_matches=False, ) bbox_reg_weights = cfg.MODEL.ROI_HEADS.BBOX_REG_WEIGHTS box_coder = BoxCoder(weights=bbox_reg_weights) fg_bg_sampler = BalancedPositiveNegativeSampler( cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE, cfg.MODEL.ROI_HEADS.POSITIVE_FRACTION ) samp_processor = FastRCNNSampling( matcher, fg_bg_sampler, box_coder, ) return samp_processor
State Before: l : Type ?u.894994 m : Type ?u.894997 n : Type u_1 o : Type ?u.895003 m' : o → Type ?u.895008 n' : o → Type ?u.895013 R : Type ?u.895016 S : Type ?u.895019 α : Type v β : Type w γ : Type ?u.895026 inst✝¹ : NonUnitalSemiring α inst✝ : Fintype n A B C : Matrix n n α i j : n ⊢ (A ⬝ B ⬝ C) i j = A i ⬝ᵥ mulVec B (Cᵀ j) State After: l : Type ?u.894994 m : Type ?u.894997 n : Type u_1 o : Type ?u.895003 m' : o → Type ?u.895008 n' : o → Type ?u.895013 R : Type ?u.895016 S : Type ?u.895019 α : Type v β : Type w γ : Type ?u.895026 inst✝¹ : NonUnitalSemiring α inst✝ : Fintype n A B C : Matrix n n α i j : n ⊢ (A ⬝ (B ⬝ C)) i j = A i ⬝ᵥ mulVec B (Cᵀ j) Tactic: rw [Matrix.mul_assoc] State Before: l : Type ?u.894994 m : Type ?u.894997 n : Type u_1 o : Type ?u.895003 m' : o → Type ?u.895008 n' : o → Type ?u.895013 R : Type ?u.895016 S : Type ?u.895019 α : Type v β : Type w γ : Type ?u.895026 inst✝¹ : NonUnitalSemiring α inst✝ : Fintype n A B C : Matrix n n α i j : n ⊢ (A ⬝ (B ⬝ C)) i j = A i ⬝ᵥ mulVec B (Cᵀ j) State After: l : Type ?u.894994 m : Type ?u.894997 n : Type u_1 o : Type ?u.895003 m' : o → Type ?u.895008 n' : o → Type ?u.895013 R : Type ?u.895016 S : Type ?u.895019 α : Type v β : Type w γ : Type ?u.895026 inst✝¹ : NonUnitalSemiring α inst✝ : Fintype n A B C : Matrix n n α i j : n ⊢ ∑ x : n, A i x * ∑ j_1 : n, B x j_1 * C j_1 j = ∑ x : n, A i x * ∑ x_1 : n, B x x_1 * Cᵀ j x_1 Tactic: simp only [mul_apply, dotProduct, mulVec] State Before: l : Type ?u.894994 m : Type ?u.894997 n : Type u_1 o : Type ?u.895003 m' : o → Type ?u.895008 n' : o → Type ?u.895013 R : Type ?u.895016 S : Type ?u.895019 α : Type v β : Type w γ : Type ?u.895026 inst✝¹ : NonUnitalSemiring α inst✝ : Fintype n A B C : Matrix n n α i j : n ⊢ ∑ x : n, A i x * ∑ j_1 : n, B x j_1 * C j_1 j = ∑ x : n, A i x * ∑ x_1 : n, B x x_1 * Cᵀ j x_1 State After: no goals Tactic: rfl
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.smooth_functions import ring_theory.derivation /-! # Derivation bundle In this file we define the derivations at a point of a manifold on the algebra of smooth fuctions. Moreover, we define the differential of a function in terms of derivations. The content of this file is not meant to be regarded as an alternative definition to the current tangent bundle but rather as a purely algebraic theory that provides a purely algebraic definition of the Lie algebra for a Lie group. -/ variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] (n : ℕ∞) open_locale manifold -- the following two instances prevent poorly understood type class inference timeout problems instance smooth_functions_algebra : algebra 𝕜 C^∞⟮I, M; 𝕜⟯ := by apply_instance instance smooth_functions_tower : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯ := by apply_instance /-- Type synonym, introduced to put a different `has_smul` action on `C^n⟮I, M; 𝕜⟯` which is defined as `f • r = f(x) * r`. -/ @[nolint unused_arguments] def pointed_smooth_map (x : M) := C^n⟮I, M; 𝕜⟯ localized "notation (name := pointed_smooth_map) `C^` n `⟮` I `, ` M `; ` 𝕜 `⟯⟨` x `⟩` := pointed_smooth_map 𝕜 I M n x" in derivation variables {𝕜 M} namespace pointed_smooth_map instance {x : M} : has_coe_to_fun C^∞⟮I, M; 𝕜⟯⟨x⟩ (λ _, M → 𝕜) := cont_mdiff_map.has_coe_to_fun instance {x : M} : comm_ring C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.comm_ring instance {x : M} : algebra 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.algebra instance {x : M} : inhabited C^∞⟮I, M; 𝕜⟯⟨x⟩ := ⟨0⟩ instance {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := algebra.id C^∞⟮I, M; 𝕜⟯ instance {x : M} : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := is_scalar_tower.right variable {I} /-- `smooth_map.eval_ring_hom` gives rise to an algebra structure of `C^∞⟮I, M; 𝕜⟯` on `𝕜`. -/ instance eval_algebra {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := (smooth_map.eval_ring_hom x : C^∞⟮I, M; 𝕜⟯⟨x⟩ →+* 𝕜).to_algebra /-- With the `eval_algebra` algebra structure evaluation is actually an algebra morphism. -/ def eval (x : M) : C^∞⟮I, M; 𝕜⟯ →ₐ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := algebra.of_id C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 lemma smul_def (x : M) (f : C^∞⟮I, M; 𝕜⟯⟨x⟩) (k : 𝕜) : f • k = f x * k := rfl instance (x : M) : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := { smul_assoc := λ k f h, by { simp only [smul_def, algebra.id.smul_eq_mul, smooth_map.coe_smul, pi.smul_apply, mul_assoc]} } end pointed_smooth_map open_locale derivation /-- The derivations at a point of a manifold. Some regard this as a possible definition of the tangent space -/ @[reducible] def point_derivation (x : M) := derivation 𝕜 (C^∞⟮I, M; 𝕜⟯⟨x⟩) 𝕜 section variables (I) {M} (X Y : derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) (f g : C^∞⟮I, M; 𝕜⟯) (r : 𝕜) /-- Evaluation at a point gives rise to a `C^∞⟮I, M; 𝕜⟯`-linear map between `C^∞⟮I, M; 𝕜⟯` and `𝕜`. -/ def smooth_function.eval_at (x : M) : C^∞⟮I, M; 𝕜⟯ →ₗ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := (pointed_smooth_map.eval x).to_linear_map namespace derivation variable {I} /-- The evaluation at a point as a linear map. -/ def eval_at (x : M) : (derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) →ₗ[𝕜] point_derivation I x := (smooth_function.eval_at I x).comp_der lemma eval_at_apply (x : M) : eval_at x X f = (X f) x := rfl end derivation variables {I} {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] /-- The heterogeneous differential as a linear map. Instead of taking a function as an argument this differential takes `h : f x = y`. It is particularly handy to deal with situations where the points on where it has to be evaluated are equal but not definitionally equal. -/ def hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) : point_derivation I x →ₗ[𝕜] point_derivation I' y := { to_fun := λ v, derivation.mk' { to_fun := λ g, v (g.comp f), map_add' := λ g g', by rw [smooth_map.add_comp, derivation.map_add], map_smul' := λ k g, by simp only [smooth_map.smul_comp, derivation.map_smul, ring_hom.id_apply], } (λ g g', by simp only [derivation.leibniz, smooth_map.mul_comp, linear_map.coe_mk, pointed_smooth_map.smul_def, cont_mdiff_map.comp_apply, h]), map_smul' := λ k v, rfl, map_add' := λ v w, rfl } /-- The homogeneous differential as a linear map. -/ def fdifferential (f : C^∞⟮I, M; I', M'⟯) (x : M) : point_derivation I x →ₗ[𝕜] point_derivation I' (f x) := hfdifferential (rfl : f x = f x) /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation (name := fdifferential) `𝒅` := fdifferential" in manifold /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation (name := hfdifferential) `𝒅ₕ` := hfdifferential" in manifold @[simp] lemma apply_fdifferential (f : C^∞⟮I, M; I', M'⟯) {x : M} (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅f x v g = v (g.comp f) := rfl @[simp] lemma apply_hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅ₕh v g = 𝒅f x v g := rfl variables {E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] @[simp] lemma fdifferential_comp (g : C^∞⟮I', M'; I'', M''⟯) (f : C^∞⟮I, M; I', M'⟯) (x : M) : 𝒅(g.comp f) x = (𝒅g (f x)).comp (𝒅f x) := rfl end
library(npowerPrioR) library(rstan) rstan_options(auto_write = TRUE) options(mc.cores = 4) source("data_Gaussian.r") #### Sampling from the "prior" prior <- stan_model("stan/simple_Gaussian_prior.stan") gs.data <- list( N0 = N_0, y0 = y_0, mu0 = mu_0, kappa0 = kappa_0, alpha0 = alpha_0, beta0 = beta_0, a_0 = 1 ) #################### J <- 20 maxA <- 10 epsilon <- 0.05 # uniform.a0s <- seq(epsilon, maxA, length.out = J) uniform.time <- system.time( uniform.ca0.estimates <- create_lc_df(a0_grid = uniform.a0s, compiled.model.prior = prior, stan.list = gs.data, pars = c("mu", "sigma")) ) adaptive.time <- system.time( adaptive.ca0.estimates <- build_grid(compiled.model.prior = prior, eps = epsilon, M = maxA, J = J, v1 = 10, v2 = 10, stan.list = gs.data, pars = c("mu", "sigma")) ) adaptive.derivOnly.time <- system.time( adaptive.ca0.estimates.derivOnly <- build_grid_derivOnly(compiled.model.prior = prior, eps = epsilon, M = maxA, J = J, v1 = 10, v2 = 10, stan.list = gs.data, pars = c("mu", "sigma")) ) ## Exporting write.csv(uniform.ca0.estimates$result, row.names = FALSE, file = paste("../data/constant_data/Gaussian_logCA0_uniform", "_J=", J, ".csv", sep = "")) write.csv(adaptive.ca0.estimates$result, row.names = FALSE, file = paste("../data/constant_data/Gaussian_logCA0_adaptive", "_J=", J, ".csv", sep = "")) write.csv(adaptive.ca0.estimates.derivOnly$result, row.names = FALSE, file = paste("../data/constant_data/Gaussian_logCA0_adaptive_derivOnly", "_J=", J, ".csv", sep = "")) ## Exporting sensitivity stuff summaries.uniform <- uniform.ca0.estimates$summaries for (i in 1:length(summaries.uniform)){ summaries.uniform[[i]] <- data.frame(summaries.uniform[[i]], a_0 = uniform.ca0.estimates$result$a0[i]) } summaries.uniform.dt <- do.call(rbind, summaries.uniform) summaries.adaptive <- adaptive.ca0.estimates$summaries for (j in 1:length(summaries.adaptive)){ summaries.adaptive[[j]] <- data.frame(summaries.adaptive[[j]], a_0 = adaptive.ca0.estimates$result$a0[j]) } summaries.adaptive.dt <- do.call(rbind, summaries.adaptive) write.csv(summaries.uniform.dt, file = paste("../data/sensitivity_data/priorSensitivity_simpleGaussian_uniform_J=", J, ".csv", sep = "")) write.csv(summaries.adaptive.dt, file = paste("../data/sensitivity_data/priorSensitivity_simpleGaussian_adaptive_J=", J, ".csv", sep = ""))
c This module/program is part of DaliLite (c) L. Holm 1999 c program wolf c c f77 wolf.f subfitz.f u3b-8.f c c use as: c cp list.sep list2 c echo "codeX" > list1 c wolf-one | sort -nr +1 > codeX.wolf c implicit none include 'parsizes.for' character secstr(maxseg),secstrx(maxseg) integer nseg real midy(3,maxseg+3),diry(3,maxseg+3) c integer nprot1,nprot2,ns character*5 cd,list1(maxprot),list2(maxprot),cd1 c integer*4 box(-20:20,-20:20,-20:20),link_a(10000),link_c(10000), $ link_b(10000) real link_from(3,10000),link_to(3,10000) integer lastlink,link_next(10000) integer i,j,protcount,bestpair(4) logical lverb c character*80 dalidatpath_1,dalidatpath_2 c real xca(3,maxres),yca(3,maxres),x(3,maxres),y(3,maxres),rms integer nx,ny,ali(maxres),k,lali,niter,nsegx real midx(3,maxseg+3),dirx(3,maxseg+3),neidist(maxseg,maxseg) integer nocc,occ(3,60000), fitzmaxiter real neiborcutoff, fitzrcut c write(*,*),'enter dalidatpath_1, _2, fitzrcut, fitzmaxiter, neiborcutoff' read(*,520) dalidatpath_1 read(*,520) dalidatpath_2 read(*,*) fitzrcut read(*,*) fitzmaxiter read(*,*) neiborcutoff write(*,*),'imported parameters are:',dalidatpath_1, $ dalidatpath_2,fitzrcut,fitzmaxiter, $ neiborcutoff c lverb=.false. nprot1=0 nprot2=0 call getlist('list1',90,list1,nprot1) call getlist('list2',90,list2,nprot2) c call initgrid(box,20,20,20) c c search-loop c nocc=0 cd=list1(1) cd1=cd if(cd1(5:5).eq.' ') cd1(5:5)='_' call setupprotein(cd,nsegx,midx,dirx,secstrx,90,xca,nx,neidist, $ dalidatpath_1) call loadprotein(box,20,20,20,nsegx,midx,dirx,ns,neiborcutoff, $ link_a,link_b, $ link_c,link_from,link_to,lastlink,link_next,neidist,nocc,occ) if (nsegx.gt.2) then do i=1,nprot2 cd=list2(i) call setupprotein(cd,nseg,midy,diry,secstr,90, $ yca,ny,neidist,dalidatpath_2) if(nseg.gt.2) then if(lverb) write(*,*),ns,' AB pairs boxed',lastlink call compare(nseg,midy,diry,secstr,cd,nseg,secstrx, $ link_next,link_from,link_to,link_a,link_b,link_c, $ box,20,20,20,neiborcutoff,protcount,bestpair,neidist) write(*,500),cd,protcount,(bestpair(j),j=1,4) c c fitz C(alphas) in best-per-protein trial superimpositions c if(bestpair(1).eq.0.or.bestpair(2).eq.0) goto 39 if(lverb) write(*,*),'fitzing ',cd,i call preparex(x,bestpair(3),bestpair(4),0,midx,dirx) do j=1,nx do k=1,3 x(k,j+3)=xca(k,j) end do end do call twist(x,3+nx) ! prepare sets twist frame, transform CA do j=1,nx do k=1,3 x(k,j)=x(k,j+3) end do end do call preparex(y,bestpair(1),bestpair(2),0,midy,diry) do j=1,ny do k=1,3 y(k,j+3)=yca(k,j) end do end do call twist(y,3+ny) ! prepare sets twist frame, transform CA do j=1,ny do k=1,3 y(k,j)=y(k,j+3) end do end do call fitz(x,nx,y,ny,ali,fitzrcut,fitzmaxiter,rms,lali,niter) write(*,510),cd1,cd,protcount,(bestpair(j),j=3,4), $ (bestpair(j),j=1,2),rms,lali,niter,nx,(ali(j),j=1,nx) end if 39 end do end if 500 format(a5,i20,4i10) 510 format('WOLFITZ ',2a5,5i5,f10.1,3i5,<maxres>i4) 520 format(a80) end c c---------------------------------------------------------------------- c subroutine preparex(x,iseg,jseg,nx,midpoint,direction) implicit none include 'parsizes.for' integer nx,iseg,jseg real x(3,*),midpoint(3,*),direction(3,*) c integer i,kseg c do i=1,3 x(i,1)=midpoint(i,iseg) x(i,2)=midpoint(i,iseg)+direction(i,iseg) x(i,3)=midpoint(i,jseg) end do do kseg=1,nx do i=1,3 x(i,3+kseg)=midpoint(i,kseg)-direction(i,kseg) x(i,3+nx+kseg)=midpoint(i,kseg)+direction(i,kseg) end do end do return end c c---------------------------------------------------------------------- c subroutine compare(nseg,midpoint,direction,secstr,protein_code, $ protein_nseg,protein_secstr,link_next,link_from,link_to, $ link_a,link_b,link_c,box,boxdim1,boxdim2,boxdim3, $ rcut,protcount,bestpair,neidist) implicit none include 'parsizes.for' integer nseg,boxdim1,boxdim2,boxdim3,bestpair(4) real midpoint(3,maxseg),direction(3,maxseg),rcut integer*4 box(-boxdim1:boxdim1,-boxdim2:boxdim2,-boxdim3:boxdim3), $ link_a(10000),link_b(10000),link_c(10000) real link_from(3,10000),link_to(3,10000),neidist(maxseg,maxseg) integer link_next(10000),protcount character secstr(maxseg) c integer protein_nseg,count(maxseg,maxseg) character*5 protein_code character protein_secstr(maxseg) c integer cur_a,cur_c,cur_link,iseg,jseg,kseg,gx,gy,gz,fung,i,j real mid(3),r,distance,x(3,maxseg+maxseg+3),cosi,dir(3),midx(3),dirx(3) character atype,ctype logical lgrid,less,lest integer dgx,dgy,dgz,gx0,gy0,gz0,cur_b,useg,vseg,lseg c dgx=2 dgy=2 dgz=2 c write(*,*) 'this is compare',nseg,rcut protcount=0 do j=1,4 bestpair(j)=0 end do do iseg=1,nseg atype=secstr(iseg) do jseg=1,nseg lest=(iseg.lt.jseg) if(iseg.ne.jseg) then r=neidist(iseg,jseg) if(r.lt.rcut) then call initcomparison(protein_nseg,count) call preparex(x,iseg,jseg,nseg,midpoint,direction) call twist(x,3+nseg+nseg) ! require midpoint distance < 3 A and cosi(c,c')>0.5 do kseg=1,nseg if(kseg.ne.iseg) then less=(iseg.lt.kseg) do i=1,3 midx(i)=(x(i,3+kseg)+x(i,3+nseg+kseg))/2 dirx(i)=x(i,3+nseg+kseg)-midx(i) end do ctype=secstr(kseg) r=(x(1,3+kseg)+x(1,3+nseg+kseg))/2.0 gx0=fung(r) r=(x(2,3+kseg)+x(2,3+nseg+kseg))/2.0 gy0=fung(r) r=(x(3,3+kseg)+x(3,3+nseg+kseg))/2.0 gz0=fung(r) do gx=gx0-dgx,gx0+dgx do gy=gy0-dgy,gy0+dgy do gz=gz0-dgz,gz0+dgz if(lgrid(gx,gy,gz,20)) then cur_link=box(gx,gy,gz) c write(*,*) cur_link,gx,gy,gz do while(cur_link.ne.0) cur_a=link_a(cur_link) cur_b=link_b(cur_link) cur_c=link_c(cur_link) c write(*,*) 'test:',iseg,jseg,kseg,atype,ctype,cur_link, c $ link_a(cur_link),link_c(cur_link), c $ protein_secstr(cur_a),protein_secstr(cur_c) if(protein_secstr(cur_a).ne.atype) goto 19 if(protein_secstr(cur_c).ne.ctype) goto 19 if(less) then ! simple topology filters if(cur_a.ge.cur_c) goto 19 else if(cur_a.le.cur_c) goto 19 end if if(lest) then if(cur_a.ge.cur_b) goto 19 else if(cur_a.le.cur_b) goto 19 end if do i=1,3 mid(i)=(link_from(i,cur_link)+link_to(i,cur_link))/2 dir(i)=link_to(i,cur_link)-mid(i) end do if(distance(mid(1),mid(2),mid(3),midx(1),midx(2),midx(3)) $ .gt.4.0) goto 19 if(cosi(dir(1),dir(2),dir(3),dirx(1),dirx(2),dirx(3)).lt.0.5) goto 19 count(cur_a,cur_b)=count(cur_a,cur_b)+1 19 cur_link=link_next(cur_link) end do end if end do end do end do end if end do c c report counts c i=0 useg=0 vseg=0 do lseg=1,protein_nseg do kseg=1,protein_nseg if(count(lseg,kseg).gt.i) then i=count(lseg,kseg) useg=lseg vseg=kseg end if end do end do c write(*,*) 'counts: ',protein_code,iseg,jseg,useg,vseg,i if(i.gt.protcount) then protcount=i bestpair(1)=iseg bestpair(2)=jseg bestpair(3)=useg bestpair(4)=vseg end if end if end if end do end do return end c c---------------------------------------------------------------------- c subroutine loadprotein(box,boxdim1,boxdim2,boxdim3, $ nseg,midpoint,direction,ns,rcut, $ link_a,link_b,link_c,link_from,link_to, $ lastlink,link_next,neidist,nocc,occ) implicit none include 'parsizes.for' integer nocc,occ(3,60000) integer boxdim1,boxdim2,boxdim3 integer*4 box(-boxdim1:boxdim1,-boxdim2:boxdim2,-boxdim3:boxdim3) integer nseg,ns real midpoint(3,maxseg),direction(3,maxseg),rcut integer*4 link_a(10000),link_c(10000) integer*4 link_b(10000) real link_from(3,10000),link_to(3,10000),neidist(maxseg,maxseg) integer lastlink,link_next(10000) c integer iseg,jseg,i real r,x(3,3+maxseg+maxseg) c c clean up box c c write(*,*),'unload',nocc do i=1,nocc box(occ(1,i),occ(2,i),occ(3,i))=0 end do nocc=0 lastlink=0 c c c ns=0 do iseg=1,nseg do jseg=1,nseg if(jseg.ne.iseg.and.neidist(iseg,jseg).lt.rcut) then r=neidist(iseg,jseg) if(r.lt.rcut) then call preparex(x,iseg,jseg,nseg,midpoint,direction) call twist(x,3+nseg+nseg) call boxit(nseg,x,iseg,jseg,lastlink,link_a,link_b, $ link_c,link_from,link_to,link_next, $ box,boxdim1,boxdim2,boxdim3,nocc,occ) ns=ns+1 end if end if end do end do 500 format('before',12f5.1) 505 format('after ',12f5.1) 510 format('line',3f10.1,' to ',3f10.1,';') return end c c---------------------------------------------------------------------- c subroutine boxit(nseg,x,aseg,bseg,lastlink,link_a, $ link_b,link_c,link_from,link_to, $ link_next,box,boxdim1,boxdim2,boxdim3,nocc,occ) implicit none include 'parsizes.for' integer nseg,aseg,bseg real x(3,maxseg+maxseg+3) integer boxdim1,boxdim2,boxdim3 integer*4 box(-boxdim1:boxdim1,-boxdim2:boxdim2,-boxdim3:boxdim3) integer*4 link_a(10000),link_c(10000) integer*4 link_b(10000) real link_from(3,10000),link_to(3,10000) integer lastlink,link_next(10000),nocc,occ(3,60000) c integer fung logical lgrid c integer gx,gy,gz,iseg,i,nx real mid(3) c nx=0 do iseg=1,nseg if(iseg.ne.aseg.and.lastlink.lt.10000) then lastlink=lastlink+1 if(lastlink.gt.10000) stop 'link overflow' link_a(lastlink)=aseg link_b(lastlink)=bseg link_c(lastlink)=iseg do i=1,3 link_from(i,lastlink)=x(i,3+iseg) link_to(i,lastlink)=x(i,3+nseg+iseg) mid(i)=(x(i,3+iseg)+x(i,3+nseg+iseg))/2.0 end do gx=fung(mid(1)) gy=fung(mid(2)) gz=fung(mid(3)) if(lgrid(gx,gy,gz,20)) then link_next(lastlink)=box(gx,gy,gz) if(box(gx,gy,gz).eq.0) then nocc=nocc+1 occ(1,nocc)=gx occ(2,nocc)=gy occ(3,nocc)=gz end if box(gx,gy,gz)=lastlink c write(*,*) 'boxed',lastlink,aseg,iseg,gx,gy,gz else lastlink=lastlink-1 nx=nx+1 end if end if end do c if(nx.gt.0) write(*,*) nx,' elements ignored by boxit' return end c c---------------------------------------------------------------------- c subroutine initcomparison(protein_nseg,count) implicit none include 'parsizes.for' integer protein_nseg,count(maxseg,maxseg) c integer j,k c do j=1,protein_nseg do k=1,protein_nseg count(j,k)=0 end do end do return end c c---------------------------------------------------------------------- c function cosi(z1,z2,z3,x1,x2,x3) implicit none real cosi,z1,z2,z3,x1,x2,x3 c real lz,lx,norm c lz=sqrt(z1*z1+z2*z2+z3*z3) lx=sqrt(x1*x1+x2*x2+x3*x3) norm=max(1e-6,lz*lx) cosi=(z1*x1+z2*x2+z3*x3)/norm c return end c c---------------------------------------------------------------------- c function distance(a1,a2,a3,b1,b2,b3) implicit none real distance,a1,a2,a3,b1,b2,b3 c distance=sqrt((a1-b1)*(a1-b1)+(a2-b2)*(a2-b2)+(a3-b3)*(a3-b3)) c return end c c---------------------------------------------------------------------- c subroutine initgrid(box,boxdim1,boxdim2,boxdim3) implicit none integer boxdim1,boxdim2,boxdim3 integer*4 box(-boxdim1:boxdim1,-boxdim2:boxdim2,-boxdim3:boxdim3) c integer i,j,k c do k=-boxdim3,boxdim3 do j=-boxdim2,boxdim2 do i=-boxdim1,boxdim1 box(i,j,k)=0 end do end do end do return end c c---------------------------------------------------------------------- c subroutine vec(ca,nres,nseg,segmentrange,midpoint,direction) implicit none include 'parsizes.for' integer nseg,segmentrange(2,maxseg),nres real ca(3,maxres),midpoint(3,maxseg+3),direction(3,maxseg+3) c integer iseg,ires,left,rite,mid,i,l,r real nmid(3),cmid(3) c do iseg=1,nseg left=segmentrange(1,iseg) rite=segmentrange(2,iseg) mid=(left+rite)/2 l=mid-left+1 r=rite-mid+1 do i=1,3 nmid(i)=0 cmid(i)=0 end do do ires=left,mid do i=1,3 nmid(i)=nmid(i)+ca(i,ires)/l end do end do do ires=mid,rite do i=1,3 cmid(i)=cmid(i)+ca(i,ires)/r end do end do do i=1,3 midpoint(i,iseg)=(nmid(i)+cmid(i))/2 direction(i,iseg)=cmid(i)-nmid(i) end do end do return end c c---------------------------------------------------------------------- c subroutine readproteindata(nseg,secstr,segmentrange,ca,nres,iunit) implicit none include 'parsizes.for' integer ndom,node_child(2,maxdom),nres,nseg,iunit character node_type(maxdom),secstr(maxseg) integer domns(maxdom),domseglist(maxseg,maxdom),na,nb real ca(3,maxres) integer segmentrange(2,maxseg),checkrange(2,maxseg),checkx(maxseg) c integer i,j,idom,iseg c read(iunit,500) nres,nseg,na,nb,(secstr(i),i=1,nseg) do iseg=1,nseg read(iunit,510) i,(segmentrange(j,i),j=1,2),(checkrange(j,i),j=1,2), $ checkx(i) end do read(iunit,520) ((ca(j,i),j=1,3),i=1,nres) read(iunit,500) ndom do idom=1,ndom read(iunit,530) i,node_type(i),(node_child(j,i),j=1,2),domns(i), $ (domseglist(j,i),j=1,domns(i)) end do 500 format(10x,4i5,2x,<maxseg>a1) 510 format(6i10) 520 format(10f8.1) 530 format(i4,1x,a1,1x,3i4,<maxseg>i4) return end c c------------------------------------------------------------------------------- c subroutine setupprotein(cd,nseg,midpoint,direction,secstr,iunit, $ ca,nres,neidist,dalidatpath) implicit none include 'parsizes.for' character*5 cd integer nseg,iunit character secstr(maxseg) real midpoint(3,maxseg+3),direction(3,maxseg+3),neidist(maxseg,maxseg) c character*80 filnam,constructfilnam,dalidatpath integer segmentrange(2,maxseg),nres,jseg,iseg real ca(3,maxres),distance,r c filnam=constructfilnam(cd,dalidatpath,'.dat') write(*,*),'setup: ',filnam open(iunit,file=filnam,status='old') call readproteindata(nseg,secstr,segmentrange,ca,nres,iunit) close(iunit) c write(*,*) cd,nseg,nres,' ',(secstr(i),i=1,nseg) call vec(ca,nres,nseg,segmentrange,midpoint,direction) ! remember all distances in neidist do iseg=1,nseg do jseg=1,nseg if(iseg.ne.jseg) then r=distance(midpoint(1,iseg),midpoint(2,iseg),midpoint(3,iseg), $ midpoint(1,jseg),midpoint(2,jseg),midpoint(3,jseg)) neidist(iseg,jseg)=r else neidist(iseg,jseg)=0.0 end if end do end do 500 format(a4,a1) end c c---------------------------------------------------------------------- c subroutine getlist(filnam,iunit,list,nprot) implicit none include 'parsizes.for' character*5 list(maxprot) integer nprot,iunit character*(*) filnam c character*5 cd c nprot=0 open(iunit,file=filnam,status='old') 10 read(iunit,500,end=19) cd if(nprot.eq.maxprot) then c write(*,*) 'WARNING: skip reading list after maxprot',maxprot goto 19 end if nprot=nprot+1 list(nprot)=cd goto 10 19 close(iunit) c write(*,*) nprot,' proteins in list from ',filnam c 500 format(a5) c return end c c---------------------------------------------------------------------- c subroutine twist(x,looplen) c c puts x(*,1) in origo, x(*,2) along y axis, x(*,3) in positive yz plane c output: transrotated coordinates x c implicit none integer looplen real x(3,looplen) c real pii parameter(pii=3.141592653589793) c integer i,j real u,sinu,cosu,y(3) c c set origo c do i=looplen,1,-1 do j=1,3 x(j,i)=x(j,i)-x(j,1) end do end do c c rotate around x c -- if y=0 do first 90 deg around z c if(abs(x(2,2)).lt.1e-6) then do i=2,looplen y(1)=-x(2,i) y(2)=x(1,i) y(3)=x(3,i) do j=1,3 x(j,i)=y(j) end do end do end if c c -- if y=0 & x=0 do first 90 deg around x c if(abs(x(2,2)).lt.1e-6.and.abs(x(1,2)).lt.1e-6) then do i=2,looplen y(2)=-x(3,i) y(3)=x(2,i) y(1)=x(1,i) do j=1,3 x(j,i)=y(j) end do end do end if if(abs(x(2,2)).gt.1e-6) then u=atan(x(3,2)/x(2,2)) else u=0.0 end if sinu=sin(u) cosu=cos(u) do i=2,looplen y(2)=cosu*x(2,i)+sinu*x(3,i) y(3)=-sinu*x(2,i)+cosu*x(3,i) y(1)=x(1,i) do j=1,3 x(j,i)=y(j) end do end do c if(x(2,2).eq.0.0) write(*,*) ' y=0 !!!',u,sinu,cosu c c rotate around z c if(abs(x(2,2)).gt.1e-6) then u=-atan(x(1,2)/x(2,2)) else u=0.0 end if if(x(2,2).lt.0.0) u=pii+u sinu=sin(u) cosu=cos(u) do i=2,looplen y(1)=cosu*x(1,i)+sinu*x(2,i) y(2)=-sinu*x(1,i)+cosu*x(2,i) y(3)=x(3,i) do j=1,3 x(j,i)=y(j) end do end do c c rotate around y c -- if z=0 do first 90 deg around y c if(abs(x(3,3)).lt.1e-6) then do i=2,looplen y(1)=x(3,i) y(2)=x(2,i) y(3)=-x(1,i) do j=1,3 x(j,i)=y(j) end do end do end if if(x(3,3).ne.0.0) then u=atan(x(1,3)/x(3,3)) else u=0.0 end if sinu=sin(u) cosu=cos(u) do i=3,looplen y(3)=cosu*x(3,i)+sinu*x(1,i) y(1)=-sinu*x(3,i)+cosu*x(1,i) y(2)=x(2,i) do j=1,3 x(j,i)=y(j) end do end do c c -- if z<0 then rotate 180 deg around y c if(x(3,3).lt.0.0) then do i=2,looplen y(1)=-x(1,i) y(2)=x(2,i) y(3)=-x(3,i) do j=1,3 x(j,i)=y(j) end do end do end if c if(x(3,3).lt.0) write(*,*) ' z<0 !!!',u,sinu,cosu return end c c--------------------------------------------------------------------------- c function lgrid(gx,gy,gz,maxgrid) c c check that g* are inside -maxgrid..+maxgrid c .true. if ok, .false. if outside c implicit none logical lgrid integer gx,gy,gz,maxgrid c lgrid=.true. if(gx.gt.maxgrid) lgrid=.false. if(gx.lt.-maxgrid)lgrid=.false. if(gy.gt.maxgrid) lgrid=.false. if(gy.lt.-maxgrid)lgrid=.false. if(gz.gt.maxgrid) lgrid=.false. if(gz.lt.-maxgrid)lgrid=.false. return end c c------------------------------------------------------------------------------ c function fung(x) implicit none integer fung real x fung=nint(x/2) return end c c------------------------------------------------------------------------------ c
[GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β ⊢ zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) ≤ comap (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (stabilizer { x // x ∈ zmultiples a } b) [PROOFSTEP] rw [zmultiples_le, mem_comap, mem_stabilizer_iff, zmultiplesHom_apply, coe_nat_zsmul] [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β ⊢ minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b • { val := a, property := (_ : a ∈ zmultiples a) } +ᵥ b = b [PROOFSTEP] simp_rw [← vadd_iterate] [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β ⊢ (fun x => { val := a, property := (_ : a ∈ zmultiples a) } +ᵥ x)^[minimalPeriod (fun x => a +ᵥ x) b] b = b [PROOFSTEP] exact isPeriodicPt_minimalPeriod ((· +ᵥ ·) a) b [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β ⊢ Injective ↑(QuotientAddGroup.map (zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b)) (stabilizer { x // x ∈ zmultiples a } b) (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (_ : zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) ≤ comap (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (stabilizer { x // x ∈ zmultiples a } b))) [PROOFSTEP] rw [← ker_eq_bot_iff, eq_bot_iff] [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β ⊢ ker (QuotientAddGroup.map (zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b)) (stabilizer { x // x ∈ zmultiples a } b) (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (_ : zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) ≤ comap (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (stabilizer { x // x ∈ zmultiples a } b))) ≤ ⊥ [PROOFSTEP] refine' fun q => induction_on' q fun n hn => _ [GOAL] n✝ : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β q : ℤ ⧸ zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) n : ℤ hn : ↑n ∈ ker (QuotientAddGroup.map (zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b)) (stabilizer { x // x ∈ zmultiples a } b) (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (_ : zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) ≤ comap (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (stabilizer { x // x ∈ zmultiples a } b))) ⊢ ↑n ∈ ⊥ [PROOFSTEP] rw [mem_bot, eq_zero_iff, Int.mem_zmultiples_iff, ← zsmul_vadd_eq_iff_minimalPeriod_dvd] [GOAL] n✝ : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β q : ℤ ⧸ zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) n : ℤ hn : ↑n ∈ ker (QuotientAddGroup.map (zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b)) (stabilizer { x // x ∈ zmultiples a } b) (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (_ : zmultiples ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b) ≤ comap (↑(zmultiplesHom { x // x ∈ zmultiples a }) { val := a, property := (_ : a ∈ zmultiples a) }) (stabilizer { x // x ∈ zmultiples a } b))) ⊢ n • a +ᵥ b = b [PROOFSTEP] exact (eq_zero_iff _).mp hn [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : Group α a : α inst✝ : MulAction α β b : β k : ℤ ⊢ ↑(orbitZpowersEquiv a b).symm ↑k = { val := a, property := (_ : a ∈ zpowers a) } ^ k • { val := b, property := (_ : b ∈ orbit { x // x ∈ zpowers a } b) } [PROOFSTEP] rw [orbitZpowersEquiv_symm_apply, ZMod.coe_int_cast] [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝³ : AddGroup A inst✝² : Ring R α : Type u_3 β : Type u_4 inst✝¹ : Group α a : α inst✝ : MulAction α β b : β k : ℤ ⊢ { val := a, property := (_ : a ∈ zpowers a) } ^ (k % ↑(minimalPeriod ((fun x x_1 => x • x_1) a) b)) • { val := b, property := (_ : b ∈ orbit { x // x ∈ zpowers a } b) } = { val := a, property := (_ : a ∈ zpowers a) } ^ k • { val := b, property := (_ : b ∈ orbit { x // x ∈ zpowers a } b) } [PROOFSTEP] exact Subtype.ext (zpow_smul_mod_minimalPeriod _ _ k) [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝⁵ : AddGroup A inst✝⁴ : Ring R α✝ : Type u_3 β✝ : Type u_4 inst✝³ : Group α✝ a✝ : α✝ inst✝² : MulAction α✝ β✝ b✝ : β✝ α : Type u_5 β : Type u_6 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β k : ℤ ⊢ ↑(orbitZmultiplesEquiv a b).symm ↑k = k • { val := a, property := (_ : a ∈ zmultiples a) } +ᵥ { val := b, property := (_ : b ∈ AddAction.orbit { x // x ∈ zmultiples a } b) } [PROOFSTEP] rw [AddAction.orbit_zmultiples_equiv_symm_apply, ZMod.coe_int_cast] -- porting note: times out without `a b` explicit [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝⁵ : AddGroup A inst✝⁴ : Ring R α✝ : Type u_3 β✝ : Type u_4 inst✝³ : Group α✝ a✝ : α✝ inst✝² : MulAction α✝ β✝ b✝ : β✝ α : Type u_5 β : Type u_6 inst✝¹ : AddGroup α a : α inst✝ : AddAction α β b : β k : ℤ ⊢ (k % ↑(minimalPeriod ((fun x x_1 => x +ᵥ x_1) a) b)) • { val := a, property := (_ : a ∈ zmultiples a) } +ᵥ { val := b, property := (_ : b ∈ AddAction.orbit { x // x ∈ zmultiples a } b) } = k • { val := a, property := (_ : a ∈ zmultiples a) } +ᵥ { val := b, property := (_ : b ∈ AddAction.orbit { x // x ∈ zmultiples a } b) } [PROOFSTEP] exact Subtype.ext (zsmul_vadd_mod_minimalPeriod a b k) [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝⁴ : AddGroup A inst✝³ : Ring R α : Type u_3 β : Type u_4 inst✝² : Group α a : α inst✝¹ : MulAction α β b : β inst✝ : Fintype ↑(orbit { x // x ∈ zpowers a } b) ⊢ minimalPeriod ((fun x x_1 => x • x_1) a) b = Fintype.card ↑(orbit { x // x ∈ zpowers a } b) [PROOFSTEP] rw [← Fintype.ofEquiv_card (orbitZpowersEquiv a b), @ZMod.card _ (_)] [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝⁴ : AddGroup A inst✝³ : Ring R α : Type u_3 β : Type u_4 inst✝² : Group α a : α inst✝¹ : MulAction α β b : β inst✝ : Finite ↑(orbit { x // x ∈ zpowers a } b) ⊢ minimalPeriod ((fun x x_1 => x • x_1) a) b ≠ 0 [PROOFSTEP] cases nonempty_fintype (orbit (zpowers a) b) [GOAL] case intro n : ℕ A : Type u_1 R : Type u_2 inst✝⁴ : AddGroup A inst✝³ : Ring R α : Type u_3 β : Type u_4 inst✝² : Group α a : α inst✝¹ : MulAction α β b : β inst✝ : Finite ↑(orbit { x // x ∈ zpowers a } b) val✝ : Fintype ↑(orbit { x // x ∈ zpowers a } b) ⊢ minimalPeriod ((fun x x_1 => x • x_1) a) b ≠ 0 [PROOFSTEP] haveI : Nonempty (orbit (zpowers a) b) := (orbit_nonempty b).to_subtype [GOAL] case intro n : ℕ A : Type u_1 R : Type u_2 inst✝⁴ : AddGroup A inst✝³ : Ring R α : Type u_3 β : Type u_4 inst✝² : Group α a : α inst✝¹ : MulAction α β b : β inst✝ : Finite ↑(orbit { x // x ∈ zpowers a } b) val✝ : Fintype ↑(orbit { x // x ∈ zpowers a } b) this : Nonempty ↑(orbit { x // x ∈ zpowers a } b) ⊢ minimalPeriod ((fun x x_1 => x • x_1) a) b ≠ 0 [PROOFSTEP] rw [minimalPeriod_eq_card] [GOAL] case intro n : ℕ A : Type u_1 R : Type u_2 inst✝⁴ : AddGroup A inst✝³ : Ring R α : Type u_3 β : Type u_4 inst✝² : Group α a : α inst✝¹ : MulAction α β b : β inst✝ : Finite ↑(orbit { x // x ∈ zpowers a } b) val✝ : Fintype ↑(orbit { x // x ∈ zpowers a } b) this : Nonempty ↑(orbit { x // x ∈ zpowers a } b) ⊢ Fintype.card ↑(orbit { x // x ∈ zpowers a } b) ≠ 0 [PROOFSTEP] exact Fintype.card_ne_zero [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝² : AddGroup A inst✝¹ : Ring R α : Type u_3 inst✝ : Group α a : α ⊢ orderOf a = Nat.card { x // x ∈ zpowers a } [PROOFSTEP] have := Nat.card_congr (MulAction.orbitZpowersEquiv a (1 : α)) [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝² : AddGroup A inst✝¹ : Ring R α : Type u_3 inst✝ : Group α a : α this : Nat.card ↑(MulAction.orbit { x // x ∈ zpowers a } 1) = Nat.card (ZMod (Function.minimalPeriod ((fun x x_1 => x • x_1) a) 1)) ⊢ orderOf a = Nat.card { x // x ∈ zpowers a } [PROOFSTEP] rwa [Nat.card_zmod, orbit_subgroup_one_eq_self, eq_comm] at this [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝² : AddGroup A inst✝¹ : Ring R α : Type u_3 inst✝ : Group α a : α h : IsOfFinOrder a ⊢ Finite { x // x ∈ zpowers a } [PROOFSTEP] rw [← orderOf_pos_iff, order_eq_card_zpowers'] at h [GOAL] n : ℕ A : Type u_1 R : Type u_2 inst✝² : AddGroup A inst✝¹ : Ring R α : Type u_3 inst✝ : Group α a : α h : 0 < Nat.card { x // x ∈ zpowers a } ⊢ Finite { x // x ∈ zpowers a } [PROOFSTEP] exact Nat.finite_of_card_ne_zero h.ne.symm
%% LyX 2.3.1-1 created this file. For more info, see http://www.lyx.org/. %% Do not edit unless you really know what you are doing. \documentclass[11pt,english]{article} \usepackage{ae,aecompl} \usepackage[T1]{fontenc} \usepackage[latin9]{inputenc} \usepackage[letterpaper]{geometry} \geometry{verbose,tmargin=2.54cm,bmargin=2.54cm} \setcounter{secnumdepth}{4} \usepackage{amsmath} \usepackage{graphicx} \usepackage[numbers]{natbib} \makeatletter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands. \usepackage{graphicx} \usepackage{pdflscape} %\usepackage[cm]{fullpage} %\usepackage[compact]{titlesec} %\date{} \usepackage{scicite} \makeatother \usepackage{babel} \begin{document} \title{Supplementary Materials} \author{Mohammed Chamma} \maketitle \section*{Materials and Methods} This section will describe the process of deriving measurements of the sub-burst drift rate and the burst duration from dynamic spectra of Fast Radio Bursts, and is largely based on the autocorrelation technique described in \cite{Hessels2019,CHIME2019c}. In addition, we describe tests to the robustness of the inverse trend between the drift rate and the burst duration through variations of the DM, which show that small variations of the DM serve to rotate the FRB dynamic spectra, and, even though they affect the measured value of the sub-burst drift rate, do not affect the relative trend between bursts. Dynamic spectra of bursts are obtained from several sources and processed based on the format they are made available in, and are typically dedispersed to the DMs presented in their respective publications. Bursts from the repeater FRB121102 were obtained from \cite{Gajjar2018,Michilli2018,CHIME2019c}. These data were taken as presented in Fig. 2 of \cite{Gajjar2018}, Fig. 1 of \cite{Michilli2018}, and Fig. 5 of \cite{CHIME2019c}, and range in frequency from \textasciitilde 600 Mhz to 8 GHz. For all bursts from FRB121102, we used the structure-optimized dedispersed spectra without modification which corresponds to DMs of 565, 559.7, and 563.6 pc/cm$^{3}$ from \cite{Gajjar2018,Michilli2018,CHIME2019c}, respectively. Data for FRB180916.J0158+65 and FRB180814.J0422+73 are available from the public data archive for the CHIME telescope (chime-frb-open-data.github.io) \cite{CHIME2019a,Amiri2020periodic}. Dedispersed bursts from FRB180916.J0158+65 are used at a DM of 348.82 pc/cm$^{3}$, though we also investigated the effect of small variations of this DM, as discussed later. Data for FRB180814.J0422+74 is provided at its original resolution and without dedispersion. The range of DMs used for this source in \cite{CHIME2019a} vary between 188.9-190 pc/cm$^{3}$. We find that a good fit between this data and our model exists for DMs in between 188.9-189.4 pc/cm$^{3}$. However we will tentatively argue that the shape of the FRB180814.J0422+7 bursts suggests too aggressive of a dedispersion and that a slightly lower DM of 188.7-188.8 pc/cm$^{3}$ is optimal in terms of the burst shape expected when taken in context with the bursts from the other two sources. In all cases dynamic spectra are downsampled in frequency to increase SNR. When a dynamic spectrum consists of a train of multiple bursts, we separate the components and measure the drift rate and duration of each burst separately, as described in Fig 3. of \cite{Rajabi2020b}. Even when from the same source, fast radio bursts can have DMs that differ from each other and that potentially also vary with time \cite{Gajjar2018}, which raises questions about which DM is appropriate to use. For this work we choose a single DM per source since multiple bursts from short duration pulse trains (which should have a single canonical DM) obey the inverse relationship between the sub-burst drift rate and burst duration, and a single DM simplifies the analysis. We found that small variations in the DM (on the order of 5\%) can increase the spread of the points on a drift vs. duration plot and can translate the points up or down, which clearly affects the fit, but the existence of the relationship in general remains. Additionally, because the DM is primarily a property of the interstellar medium and not the source, any model that requires a fine-tuned selection of DMs adds additional parameters and complexity that require justification. For example, a model that selects DMs based on maximizing structure \cite{Gajjar2018,Hessels2019} as a selection criteria brings with it assumptions that components of the burst are emitted (and arrive) simultaneously across a large frequency range \cite{Hessels2019}. While this criteria advantageously gives a narrow range of DMs to choose from, there is no reason to strictly adhere to it from burst to burst. Therefore, in general, we limit ourselves to the range of DMs found from all the bursts as a whole when considering variations, and for the analysis proper we select a single DM for every burst from a particular source. The general pipeline that every burst is put through is written in Python and consists of computing the autocorrelation of the signal, fitting a two-dimensional Gaussian to the resulting autocorrelation, and a calculation of the physical quantities of interest from the fit parameters: namely the sub-burst drift rate and the burst duration. The autocorrelation of the spectrum measures the self-similarity of the burst in frequency and time space and for FRBs results in an ellipsoid with an intensity that follows a 2D Gaussian \cite{Hessels2019}. Before autocorrelation and depending on the source and/or burst, some noise removal is performed. For the bursts from FRB121102 and FRB180916.J0158+65 this is done by subtracting the background from the entire spectrum, which is obtained from a time-average of twenty or so samples taken prior to the burst. For FRB180814.J0422+73, due to the raw format the bursts are provided in, a noise mask was acquired through correspondence and the channels are normalized by the standard deviation of the intensity. We compute the autocorrelation of the dynamic spectrum using an intermediate FFT, which allows us to perform the correlation through a multiplication and is much faster. After multiplication we perform an inverse FFT and the result is the autocorrelation of the burst. The shape of the autocorrelation is an ellipsoid centered about its peak that varies in width and angle. Thus, the next step is to find parameters for the following functional form of a rotate-able two-dimensional Gaussian, \begin{align} G(x,y) & =A\exp(-a(x-x_{0})^{2}-b(x-x_{0})(y-y_{0})-c(y-y_{0})^{2}),\\ a & =\frac{\cos^{2}(\theta)}{2\sigma_{x}^{2}}+\frac{\sin^{2}(\theta)}{2\sigma_{y}^{2}},\\ b & =\frac{\sin(2\theta)}{2\sigma_{x}^{2}}-\frac{\sin(2\theta)}{2\sigma_{y}^{2}},\\ c & =\frac{\sin^{2}(\theta)}{2\sigma_{x}^{2}}+\frac{\cos^{2}(\theta)}{2\sigma_{y}^{2}}, \end{align} where the free parameters are $A,x_{0},y_{0},\sigma_{x},\sigma_{y}$, and $\theta$, which are the amplitude, position of the center, standard deviation along the $x$ and $y$ axes, and angle from the positive x-axis to the semi-major axis of the ellipsoid. To find these parameters we use the\texttt{ scipy.optimize.curve\_fit }package, which performs a non-linear least squares to find a fit. The package also returns a covariance matrix, which we calculate the standard deviation of the parameters from by taking the square root of the diagonal terms. These errors are then scaled by the reduced $\chi^{2}$ computed from the residual between the autocorrelation and the Gaussian fit. The error calculated this way while useful does not capture the entire error budget which depends more significantly on the error in the DM as well the parts of the burst spectra that have been masked out. With the parameters found, we check which of the two widths $\sigma_{x}$ and $\sigma_{y}$ is larger and rotate $\theta$ by $\pi/2$ to coincide with the definition of $\theta$ we have chosen, which is the angle to the semi-major axis. We then choose to transform $\theta$ so that it lies within the range $(0,\pi)$ to simplify later comparisons. It is possible to constrain the solver so that it only searches for solutions where one of the widths is larger or for angles that lie in our preferred range but this often results in no solution being found. With $\theta$, the sub-burst drift rate of the burst is calculated via \begin{equation} \frac{d\nu_{\mathrm{obs}}}{dt_{D}}=\frac{\nu_{\mathrm{res}}}{t_{\mathrm{res}}}\tan\theta,\label{eq:drifttheta} \end{equation} where $\nu_{\mathrm{res}}$ and $t_{\mathrm{res}}$ are the frequency and time resolutions of the dynamic spectrum. The burst duration measured from the fit parameters is found through \begin{equation} t_{\mathrm{w}}=t_{\mathrm{res}}\frac{\sigma_{m}\sigma_{M}}{\sqrt{\sigma_{m}^{2}\cos^{2}(\theta)+\sigma_{M}^{2}\sin^{2}(\theta)}}, \end{equation} where $\sigma_{m}$ and $\sigma_{M}$ are the minimum and maximum of $\sigma_{x}$ and $\sigma_{y}$, respectively. This expression is derived by projecting the semi-minor axis of an ellipse rotated through $\theta$ onto the time-axis. These expressions are also used to derive error formulae in order to propagate the parameter errors to the the values of $d\nu_{\mathrm{obs}}/dt_{D}$ and $t_{\mathrm{w}}$. These are the error bars shown in Fig (??), and do not take into account errors on the DM or other sources of error. With these measurements of the sub-burst drift rate $d\nu_{\mathrm{obs}}/dt_{D}$ and the burst duration $t_{w}$ from each burst, we plot their relationship and compare it to the model described by eq. (??) and in \cite{Rajabi2020b}. Because of the dependance on the frequency of observation $\nu_{\mathrm{obs}}$ on the right-hand-side, we plot $\nu_{\mathrm{obs}}^{-1}d\nu_{\mathrm{obs}}/dt_{D}$ vs. $t_{\mathrm{w}}$, which provides us a fit parameter that is independent of the observation frequency. We calculate the observation frequency $\nu_{\mathrm{obs}}$ of each burst via an intensity-weighted average of the time-averaged frequency series. We used the \texttt{scipy.odr.RealData }package, which uses orthogonal distance regression and incorporates the errors on the data to find a fit. This fit differs slightly between sources, and a single fit that includes all sources can be found. ============================ \textasciicircum{} edited on overleaf \textbf{TODO:} \textbf{How do you test its robustness with DM variations?} Since a variation in the DM used to de-disperse a burst will translate to a variation in its fit angle $\theta$ and thus a variation in the measured sub-burst drift rate, we varied the DM used to test the robustness of the relationship found between the sub-burst drift rate and burst duration. We found that a variation in the DM acts as a rotation of the fit angle $\theta$, which shifts the final fit found but preserves the aforementioned relationship. Using the bursts from FRB\textasciitilde 180916, we repeated the autocorrelation analysis described above while varying the original DM of 348.82 pc/cm$^{3}$ with steps of $\Delta\mathrm{DM}=$0.5, -1, and -2 pc/cm$^{3}$, which is within the range of DMs found by \cite{Amiri2020periodic} for this source. Values of $\Delta\mathrm{DM}$ larger than 0.5 pc/cm$^{3}$ yielded positive sub-burst drift rates which indicates over-de-dispersion. Figure \ref{fig:Angle-at-different} shows the fit angles $\theta$ and durations $t_{\mathrm{w}}$ found for the collection of bursts used from FRB\textasciitilde 180916 dedispersed to the different DM values. Using eq. (\ref{eq:drifttheta}), the angle is related to the burst duration through \begin{equation} \theta=\arctan(t_{\mathrm{w}}/A), \end{equation} where $A$ is a constant and $\theta$ is transformed to fit in the range of $\arctan(x)$. Using the fit found with the above form for the bursts at $\Delta\mathrm{DM}=0$, we find angles that offset this fit to satisfactorily fit the bursts at each of the other DM values. We also note that the subburst durations found largely stay the same under different DMs. This result indicates that even though the sub-burst drift rate is quite sensitive to the DM chosen, the relative differences of the drifts between a cohort of bursts is consistent and indeed that the overall inverse trend between the sub-burst drift rate and burst duration exists even at different choices of DM. \begin{figure} \begin{centering} \includegraphics[width=1\textwidth]{B:/dev/sadtrombone/universal/angleatdifferentDMs} \par\end{centering} \caption{\label{fig:Angle-at-different}Robustness test: the fit angle $\theta$ vs. sub-burst duration $t_{\mathrm{w}}$ from bursts dedispersed to small variations in the DM for the source FRB\textasciitilde 180916. Red points are bursts at $\Delta\mathrm{DM}=0$ which corresponds to a DM of 348.82 pc/cm$^{3}$. Blue, cyan, and green points are bursts de-dispersed to $\Delta\mathrm{DM}=0.5,$-1, and -2 pc/cm$^{3}$, respectively. The red line is fit to the red points and is of the form $\arctan(t_{\mathrm{w}}/A)$ derived from the dynamical model described in the main text. Blue, cyan, and green lines are fits found by adding a rotation (adding an angle) to the $\Delta\mathrm{DM}=0$ model. This plot demonstrates the rotational effect small variations in the DM has on dynamic spectra of FRBs.} \end{figure} \textbf{How do you optimize DM based on the previous test?} \textbf{Stampcard} \bibliographystyle{Science} \bibliography{scibib} \end{document}
# Case 1: No Water Layer * Author: **Team G15** * Attempt: 3 ## Analysis ### To find 1. Temperature of Roof Surface $(T_s)$ 2. Total heat flux entering the house through the roof, $(q_t)$ when no water layer is present ### Nomenclature * $T_s$ = roof surface temperature (outside) * $T_a$ = ambient air temperature (outside) * $T_r$ = room temperature (inside) * $Nu_a$ = Nusselt number of air * $Ra_a$ = Rayleigh number of air * $Re_a$ = Reynolds number of air * $Pr_a$ = Prandtl number of air * $\alpha_a$ = thermal diffusivity of air * $k_a$ = thermal conductivity of air * $h_r$ = free convection coefficient of room air * $\nu_a$ = dynamic Viscosity of air * Roof layers: * 1: Concrete * 2: Brick * 3: Lime * $k_i$ = thermal conductivity of $i^{th}$ roof layer * $L_i$ = length of $i^{th}$ roof layer * $q_{r}$ = radiative heat transfer (per unit area) * $q_{c}$ = convective heat transfer (per unit area) * $q_{t}$ = net heat transfer into the room (per unit area) * $\beta$ = coefficient of thermal expansion * $S$ = Intensity of Solar Radiation (i.e. solar constant) ### Assumptions * Steady state with room maintained at fixed ambient temperature ### Equations #### Energy balance, $$ q_t = q_c + q_r $$ #### Radiation heat transfer, \begin{align*} q_r &= \tau_s\cdot S - h_r \cdot (T_a - T_s) \\ \\ h_r &= \epsilon_s\cdot \sigma\cdot \frac{(\overline T_s)^4 - (\overline T_a - 12)^4}{\overline T_a - \overline T_s} \end{align*} #### Convection heat transfer, \begin{align*} q_c &= h_c\cdot (T_a - T_w) \\ \\ h_c &= \frac{k_a}{L_s}\cdot Nu_a \\ \\ Nu_a &= 0.15\cdot Ra_a^{1/3} + 0.664\cdot Re_a^{1/2}\cdot Pr_a^{1/3} \\ \\ Re_a &= \frac{v_a\cdot L_s}{\nu_a} \\ \\ Ra_L &= \frac{g\cdot \beta\cdot (T_s - T_a)\cdot L_s^3}{\nu_a\cdot \alpha_a} \end{align*} #### Total heat transfer, \begin{align*} q_t &= \frac{T_w - T_r}{R_{net}} \\ \\ R_{net} &= \frac{1}{h_r} + \sum_{i=1}^{3} \frac{L_i}{k_i} \end{align*} ### Properties #### Outside Air * Mild breeze $v_a = 2.78\ m/s$ * $T_a \in [305, 320] K$ * $T_f = 320K$ * $\beta = \frac{1}{T_f} = 0.0031\ K^{-1}$ * Table A.4, air ($T_f$): * $\nu = 18 \cdot 10^{-6}\ m^2/s$ * $\alpha = 25 \cdot 10^{-6}\ m^2/s$ * $Pr = 0.702$ * $k = 27.7 \cdot 10^{-3}\ W/m\cdot K$ * $S = 1366\ W/m^2$ #### Roof * $L_s = 5\ m$ (approx thickness of water layer) * $\epsilon_s = 0.9$ (concrete surface) * $\tau_s=0.9$ * $t = 0.2\ m$ thick with, * Cement = $5\ cm$ * Brick = $10\ cm$ * Lime = $5\ cm$ * $K_i$, Conductivity of each layer, * Cement = $0.72\ W/m\cdot K$ * Brick = $0.71\ W/m\cdot K$ * Lime = $0.73\ W/m\cdot K$ #### Inside air * $T_r = 300K$ (Room Temperature) * $h_r = 8.4\ W/m^2\cdot K$ ### Tools used * **Python** * **SymPy** for creating symbolic equations and solving them * **NumPy** * **Matplotlib** for plotting results ## Solving (Python Code) ### Initialize Values ```python %matplotlib inline import sympy as sp import numpy as np import matplotlib.pyplot as plt # Initialize matplotlib plt.rc('text', usetex=True) # Unnecessary plt.style.use('ggplot') plt.rcParams['grid.color'] = '#C0C0C0' ``` #### Outside Air * Table A.4 used (from reference #2) ```python v_a = 2.78 # Velocity (m / s) # Temperatures T_f = 320.0 # (K) beta = 1/T_f # (K) T_a = np.array([305.0, 310.0, 315.0, 320.0]) # (K) T_a_avg = 273 + 37 # (K) # Universal Constants sigma = 5.67e-8 # Stefan Boltzmann constant (W / m^2 * K^4) g = 9.8 # (m / s^2) S = 1366 # Solar constant # Table A.6, air @ T = T_f nu_a = 18e-6 # dynamic visosity (m^2 / s) alpha_a = 25e-6 # (m^2 / s) k_a = 27.7e-3 # thermal conductivity (W / m * K) Pr_a = 0.702 ``` #### Roof Layers ```python # Temperatures T_s = sp.symbols('T_s') # Roof surface temp (K) T_s_avg = 273.0 + 35.0 # (K) # Surface L_s = 5 # Dimensions (m) tau_s = 0.9 # Roof's solar absorbtivity epsilon_s = 0.9 # Emissivity of roof surface (concrete) # Layer 1: Concrete k_1 = 0.72 # (W / m * K) L_1 = 0.05 # (m) # Layer 2: Brick k_2 = 0.71 # (W / m * K) L_2 = 0.10 # (m) # Layer 3: Lime k_3 = 0.73 # (W / m * K) L_3 = 0.05 # (m) ``` #### Inside Air ```python h_r = 8.4 # (W / m^2 * K) T_r = 300 # (K) ``` ### Equations #### Radiation Heat ```python h_r = epsilon_s * sigma * (T_s_avg**4 - (T_a_avg - 12)**4)/(T_a_avg - T_s_avg) # (W / m^2 * K) q_r = tau_s * S - h_r * (T_a - T_s) # (W / m^2) # Example at T_a = 310K and T_s = 314K q_r_test = q_r[1].replace(T_s, 314) print('Approximate value of q_r = %.2f W/m^2' % (q_r_test)) ``` Approximate value of q_r = 1343.00 W/m^2 #### Convection Heat * From below analysis, we can neglect free convection in comparison to forced convection ##### Free Convection ```python Ra_a = (g * beta * (T_s - T_a) * L_s**3) / (nu_a * alpha_a) Nu_a_fr = 0.15 * Ra_a**(1/3) h_c_fr = k_a / L_s * Nu_a_fr # Example at T_a = 310K and T_s = 314K h_c_fr_test = h_c_fr[1].replace(T_s, 314) print('Approximate value of free convection coefficient = %.2f W/K*m^2' % (h_c_fr_test)) ``` Approximate value of free convection coefficient = 2.69 W/K*m^2 ##### Forced Convection ```python Re_a = v_a * L_s / nu_a Nu_a_fo = 0.664 * Re_a**1/2 * Pr_a**1/3 h_c_fo = k_a / L_s * Nu_a_fo # Example at T_a = 310K and T_s = 314K print('Approximate value of forced convection coefficient = %.2f W/K*m^2' % (h_c_fo)) ``` Approximate value of forced convection coefficient = 332.36 W/K*m^2 ##### Total Convection ```python h_c = h_c_fo # Neglicting free convection q_c = h_c * (T_a - T_s) # (W / m^2) # Example at T_a = 310K and T_s = 314K q_c_test = q_c[1].replace(T_s, 314) print('Approximate value of q_c = %.2f W/m^2' % (q_c_test)) ``` Approximate value of q_c = -1329.43 W/m^2 #### Total Heat: ```python R = 1/h_r + L_1/k_1 + L_2/k_2 + L_3/k_3 # (m^2 * K / W) q_t = (T_s - T_r) / R # (W / m^2) # Example at T_a = 310K and T_s = 314K q_t_test = q_t.replace(T_s, 314) print('Approximate value of q_t = %.2f W/m^2' % (q_t_test)) ``` Approximate value of q_t = 44.59 W/m^2 ### Solving \begin{align*} q_c + q_r &= q_t \\ \therefore\hspace{3pt} q_c + q_r - q_t &= 0 \end{align*} #### Calculate $T_s$ ```python eq = q_c + q_r - q_t n = len(eq) T_s_calc = np.empty(n, dtype=object) for i in range(n): T_s_calc[i] = round(sp.solve(eq[i], T_s)[0], 2) for i in range(n): print('T_s = %.1f K for T_a = %.1f K' % (T_s_calc[i], T_a[i])) ``` T_s = 309.0 K for T_a = 305.0 K T_s = 313.9 K for T_a = 310.0 K T_s = 318.9 K for T_a = 315.0 K T_s = 323.8 K for T_a = 320.0 K #### Calculate $q_t$ ```python q_t_calc_1 = np.empty(n, dtype=object) for i in range(n): q_t_calc_1[i] = q_t.replace(T_s, T_s_calc[i]) for i in range(n): print('Heat entering = %.1f W/m^2 for T_a = %.1f K' % (q_t_calc_1[i], T_a[i])) ``` Heat entering = 28.5 W/m^2 for T_a = 305.0 K Heat entering = 44.3 W/m^2 for T_a = 310.0 K Heat entering = 60.0 W/m^2 for T_a = 315.0 K Heat entering = 75.8 W/m^2 for T_a = 320.0 K ### Plot * Total Heat Flux Entering ($q_t$) vs Outside Air Temp ($T_a$) ```python def make_plot(x, y, xlabel, ylabel, title): plt.plot(x, y, color='#1F77B4cc', marker='o') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel(xlabel, fontsize=20) plt.ylabel(ylabel, fontsize=20) plt.title(title, fontsize=18, pad=15) ``` ```python fig = plt.figure(figsize=(10, 6)) make_plot(x=T_a, y=q_t_calc_1, xlabel='$T_a$', ylabel='$q_t$', title='Total Heat Flux Entering ($q_t$) vs Outside Air Temp ($T_a$)') ``` # Case 2: Water Layer * Author: **Team G15** * Attempt: 3 ## Analysis ### To find 1. Temperature of Water Surface $(T_w)$ 2. Total heat flux entering the house through the roof, $(q_t)$ when a water layer is present ### Nomenclature * $S$ = Intensity of Solar Radiation (i.e. solar constant) * $v_w$ = water velocity * $v_a$ = wind velocity * $\epsilon_w$ = emissivity of water surface * $\sigma$ = Stefan-Boltzmann constant $(5.67*10^{-8}\ W/m^2K^4)$ * $T_r$ = room temperature (inside) * $T_w$ = water surface temperature (outside) * $T_a$ = ambient air temperature (outside) * $\overline T_w$ = average water surface temperature (outside) * $\overline T_a$ = average air temperature (outside) * $\tau_w$ = fraction of solar radiation absorbed by water * $k_w$ = thermal conductivity of water * $L_w$ = length of water layer * $h_w$ = convection coefficient of water layer * $h_r$ = radiative heat transfer coefficient * $h_c$ = convective heat transfer coefficient * $h_e$ = evaporative heat transfer coefficient ### Assumptions 1. Steady state with room maintained at fixed ambient temperature 2. Water is still ($v_w = 0$) but gentle breeze is present ($v_a = 10\ km/h$) 3. Dry Surroundings ### Equations #### Energy balance, $$ q_t = q_c + q_r - q_e $$ #### Radiation heat transfer, \begin{align*} q_r &= \tau_w\cdot S - h_r \cdot (T_a - T_w) \\ \\ h_r &= \epsilon_w\cdot \sigma\cdot \frac{(\overline T_w)^4 - (\overline T_a - 12)^4}{\overline T_a - \overline T_w} \end{align*} #### Convection heat transfer, \begin{align*} q_c &= h_c\cdot (T_a - T_w) \\ \\ h_c &= 5.678 \cdot (1 + 0.85\cdot(v_a - v_w)) \end{align*} #### Evaporative heat transfer, \begin{align*} q_e &= 0.013\cdot h_c\cdot (p(\overline T_w) - \gamma\cdot p(\overline T_a)) \\ \\ p(T) &= R_1\cdot T + R_2 \end{align*} #### Total heat transfer, \begin{align*} q_t &= \frac{T_w - T_r}{R_{net}} \\ \\ R_{net} &= \frac{1}{h_r} + \sum_{i=1}^{3} \frac{L_i}{k_i} + \frac{1}{h_{w}} \\ \\ h_w &= \frac{k_w}{L_w}\cdot (0.14\cdot(Gr\cdot Pr)^{1/3} + 0.644\cdot (Pr\cdot Re)^{1/3}) \\ \\ Gr &= \frac{g\cdot\beta\cdot(T_w-T_a)\cdot(L_w)^{3}}{\nu^2} \end{align*} ### Properties #### Outside Air * Mild breeze $v_a = 2.78\ m/s$ * $T_a \in [305, 320] K$ * $T_f = 320K$ * $\beta = \frac{1}{T_f} = 0.0031\ K^{-1}$ * Table A.4, air ($T_f$): * $\nu = 18 \cdot 10^{-6}\ m^2/s$ * $\alpha = 25 \cdot 10^{-6}\ m^2/s$ * $Pr = 0.702$ * $k = 27.7 \cdot 10^{-3}\ W/m\cdot K$ * $S = 1366\ W/m^2$ * $R_1=325\ Pa/^\circ C$ and $R_2 = -5155\ Pa$ (*from reference* **#1**) * $\gamma=0.27$ (approx average over a day) #### Water layer * $L_w = 0.1\ m$ (approx thickness of water layer) * Table A.6, water ($T_w$): * $\nu = 18 \cdot 10^{-6}\ m^2/s$ * Still water $v_w = 0$ * $\epsilon_w = 0.95$ * $\tau_w=0.6$ #### Roof * $t = 0.2\ m$ thick with, * Cement = $5\ cm$ * Brick = $10\ cm$ * Lime = $5\ cm$ * $K_i$, Conductivity of each layer, * Cement = $0.72\ W/m\cdot K$ * Brick = $0.71\ W/m\cdot K$ * Lime = $0.73\ W/m\cdot K$ #### Inside air * $T_r = 300K$ (Room Temperature) * $h_r = 8.4\ W/m^2\cdot K$ ### Tools used * **Python** * **SymPy** for creating symbolic equations and solving them * **NumPy** * **Matplotlib** for plotting results ## Solving (Python Code) ### Initialize Values #### Outside Air * Saturation pressure of water p = R_1\*T + R_2 ```python v_a = 2.78 # Velocity (m / s) # Temperatures T_f = 320 # (K) beta = 1/T_f # (K) T_a = np.array([305.0, 310.0, 315.0, 320.0]) # (K) T_a_avg = 273 + 37 # (K) # Constants sigma = 5.67e-8 # Stefan Boltzmann constant (W / m^2 * K^4) g = 9.8 # (m / s^2) R_1 = 325 # (N / m^2 °C) R_2 = -5155 # (N / m^2) gamma = 0.27 S = 1366 # Solar constant def p(T): # Saturation pressure of water as a function of temperature (N / m^2) return R_1 * (T-273) + R_2 ``` #### Water Layer ```python v_w = 0 # Velocity (m / s) L_w = 5 # Dimensions (m) # Temperatures T_w = sp.symbols('T_w') # (K) T_w_avg = 273 + 32 # (K) # Constants epsilon_w = 0.95 # Emissivity of water surface tau_w = 0.6 # Water's solar absorbtivity ``` * Table A.6 used (*from reference* **#2**) * Upon analysing the below data, we can approximate $h_w$ to $950\ W/m^2$ ```python rho_w = 990 # density (kg / m^3) k_w = 0.63 # thermal conductivity (W / m * K) mu_w = 1e-6 * np.array([769, 695, 631, 577]) # viscosity (N * s / m^2) nu_w = mu_w / rho_w # dynamic visosity (m^2 / s) Pr_w = np.array([5.20, 4.62, 4.16, 3.77]) # Prandtl number Re_w = 0 # Reynolds number, still water Gr_w = g * beta * (T_a - T_w) * L_w**3 / nu_w**2 # Grashof number # Water free convection coeffecient h_w = (k_w/L_w) * (0.14 * (Gr_w*Pr_w)**(1/3) + 0.644 * (Pr_w*Re_w)**(1/3)) # Example at T_a = 310K and T_w = 306K h_w_test = h_w[1].replace(T_w, 306) print('Approximate min value of h_w = %.2f W/K*m^2' % (h_w_test)) ``` Approximate min value of h_w = 923.62 W/K*m^2 #### Roof Layers ```python # Layer 1: Concrete k_1 = 0.72 # (W / m * K) L_1 = 0.05 # (m) # Layer 2: Brick k_2 = 0.71 # (W / m * K) L_2 = 0.10 # (m) # Layer 3: Lime k_3 = 0.73 # (W / m * K) L_3 = 0.05 # (m) ``` #### Inside Air ```python h_r = 8.4 # (W / m^2 * K) T_r = 300 # (K) ``` ### Equations #### Radiation Heat ```python h_r = epsilon_w * sigma * (T_w_avg**4 - (T_a_avg - 12)**4)/(T_a_avg - T_w_avg) # (W / m^2 * K) q_r = tau_w * S - h_r * (T_a - T_w) # (W / m^2) # Example at T_a = 310K and T_w = 306K q_r_test = q_r[1].replace(T_w, 306) print('Approximate value of q_r = %.2f W/m^2' % (q_r_test)) ``` Approximate value of q_r = 786.53 W/m^2 #### Convection Heat * Forced convection and free convection both have been used ```python h_c = 5.678 * (1 + 0.85 * (v_a - v_w)) print('h_c = %.2f W/K*m^2' % (h_c)) q_c = h_c * (T_a - T_w) # (W / m^2) # Example at T_a = 310K and T_w = 306K q_c_test = q_c[1].replace(T_w, 306) print('Approximate value of q_c = %.2f W/m^2' % (q_c_test)) ``` h_c = 19.10 W/K*m^2 Approximate value of q_c = 76.38 W/m^2 #### Evaporation Heat: ```python q_e = 0.013 * h_c * (p(T_w_avg) - gamma * p(T_a_avg)) # function p defined above, (W / m^2) # Example at T_a = 310K and T_w = 306K print('Approximate value of q_e = %.2f' % (q_e)) ``` Approximate value of q_e = 841.55 #### Total Heat: ```python h_w = 1200 # from above approximation (W / m^2 * K) R = 1/h_r + L_1/k_1 + L_2/k_2 + L_3/k_3 + 1/h_w # (m^2 * K / W) q_t = (T_w - T_r) / R # (W / m^2) # Example at T_a = 310K and T_w = 306K q_t_test = q_t.replace(T_w, 306) print('Approximate value of q_t = %.2f W/m^2' % (q_t_test)) ``` Approximate value of q_t = 14.98 W/m^2 ### Solving \begin{align*} q_c + q_r - q_e &= q_t \\ \therefore\hspace{3pt} q_c + q_r - q_e - q_t &= 0 \end{align*} #### Calculate $T_w$ ```python eq = q_c + q_r - q_e - q_t n = len(eq) T_w_calc = np.empty(n, dtype=object) for i in range(n): T_w_calc[i] = round(sp.solve(eq[i], T_w)[0], 2) for i in range(n): print('T_w = %.1f K for T_a = %.1f K' % (T_w_calc[i], T_a[i])) ``` T_w = 302.4 K for T_a = 305.0 K T_w = 306.5 K for T_a = 310.0 K T_w = 310.5 K for T_a = 315.0 K T_w = 314.6 K for T_a = 320.0 K #### Calculate $q_t$ ```python q_t_calc_2 = np.empty(n, dtype=object) for i in range(n): q_t_calc_2[i] = q_t.replace(T_w, T_w_calc[i]) for i in range(n): print('Heat entering = %.1f W/m^2 for T_a = %.1f K' % (q_t_calc_2[i], T_a[i])) ``` Heat entering = 6.0 W/m^2 for T_a = 305.0 K Heat entering = 16.2 W/m^2 for T_a = 310.0 K Heat entering = 26.3 W/m^2 for T_a = 315.0 K Heat entering = 36.5 W/m^2 for T_a = 320.0 K ### Plot * Temp Drop Due to Water ($T_a - T_w$) vs Outside Air Temp ($T_a$) * Total Heat Flux Entering ($q_t$) vs Outside Air Temp ($T_a$) ```python fig = plt.figure(figsize=(16, 6)) ax1 = fig.add_subplot(121) make_plot(x=T_a, y=T_a-T_w_calc, xlabel='$T_a$', ylabel='$T_w$', title='Temp Drop Due to Water ($T_a - T_w$) vs Outside Air Temp ($T_a$)') ax2 = fig.add_subplot(122) make_plot(x=T_a, y=q_t_calc_2, xlabel='$T_a$', ylabel='$q_t$', title='Total Heat Flux Entering ($q_t$) vs Outside Air Temp ($T_a$)') fig.tight_layout(w_pad=10) ``` ## References 1. A. Shrivastava *et al*. ["Evaporative cooling model..."](https://github.com/relaxxpls/CL246-G15/blob/main/docs/papers/Experimental_validation_of_a_thermal_mod.pdf) (1984) 2. F. Incropera *et al*. ["Fundamentals of Heat and Mass Transfer"](https://books.google.co.in/books?id=5cgbAAAAQBAJ&newbks=0&hl=en&source=newbks_fb&redir_esc=y)
The passage of the Act in the Irish Parliament was ultimately achieved with substantial majorities , having failed on the first attempt in 1799 . According to contemporary documents and historical analysis , this was achieved through a considerable degree of bribery , with funding provided by the British Secret Service Office , and the awarding of peerages , places and honours to secure votes . Thus , the parliament in Ireland was abolished and replaced by a united parliament at Westminster in London , though resistance remained , as evidenced by Robert Emmet 's failed Irish Rebellion of 1803 .
a <- read.table("allNN_nolabel.txt",sep="\t",header=F) b <- read.table("label.txt",sep="\t",header=F) b1 <- as.factor(b) for (i in 1:nrow(a)){ a1 <- as.numeric(a[i,]) c <- data.frame(a1,b1) score_aov<-aov(a1~b1,data = c) x <- anova(score_aov) x1 <- x$ 'Pr(>F)' x2 <- as.matrix(x1) x3 <- x2[1,] write.table(x3,"gene_p.txt",sep = "\t", append=T ,quote=F, col.names=F, row.names=F) }
open import Function open import Relation.Nullary open import Relation.Binary hiding (_⇒_) open import Relation.Binary.PropositionalEquality hiding ([_]) open import Data.Sum open import Data.Product delim : ∀ {α β} {A : Set α} {B : Dec A -> Set β} -> (d : Dec A) -> (∀ x -> B (yes x)) -> (∀ c -> B (no c)) -> B d delim (yes x) f g = f x delim (no c) f g = g c drec = λ {α β} {A : Set α} {B : Set β} -> delim {A = A} {B = λ _ -> B} dcong₂ : ∀ {α β γ} {A : Set α} {B : Set β} {C : Set γ} {x y v w} -> (f : A -> B -> C) -> (∀ {x y} -> f x v ≡ f y w -> x ≡ y × v ≡ w) -> Dec (x ≡ y) -> Dec (v ≡ w) -> Dec (f x v ≡ f y w) dcong₂ f inj d₁ d₂ = drec d₁ (λ p₁ -> drec d₂ (λ p₂ -> yes (cong₂ f p₁ p₂)) (λ c -> no (c ∘ proj₂ ∘ inj))) (λ c -> no (c ∘ proj₁ ∘ inj)) infixl 5 _▻_ infixr 6 _⇒_ infix 4 _≟ᵗ_ _≟ᶜ_ _∈_ _⊂[_]_ _⊂?_ _⊢_ infixr 6 vs_ infixr 5 ƛ_ infixl 7 _·_ data Type : Set where ⋆ : Type _⇒_ : Type -> Type -> Type data Con : Set where ε : Con _▻_ : Con -> Type -> Con data _∈_ σ : Con -> Set where vz : ∀ {Γ} -> σ ∈ Γ ▻ σ vs_ : ∀ {Γ τ} -> σ ∈ Γ -> σ ∈ Γ ▻ τ data _⊢_ Γ : Type -> Set where var : ∀ {σ} -> σ ∈ Γ -> Γ ⊢ σ ƛ_ : ∀ {σ τ} -> Γ ▻ σ ⊢ τ -> Γ ⊢ σ ⇒ τ _·_ : ∀ {σ τ} -> Γ ⊢ σ ⇒ τ -> Γ ⊢ σ -> Γ ⊢ τ ⇒-inj : ∀ {σ₁ σ₂ τ₁ τ₂} -> σ₁ ⇒ τ₁ ≡ σ₂ ⇒ τ₂ -> σ₁ ≡ σ₂ × τ₁ ≡ τ₂ ⇒-inj refl = refl , refl ▻-inj : ∀ {Γ₁ Γ₂ σ₁ σ₂} -> Γ₁ ▻ σ₁ ≡ Γ₂ ▻ σ₂ -> Γ₁ ≡ Γ₂ × σ₁ ≡ σ₂ ▻-inj refl = refl , refl _≟ᵗ_ : Decidable (_≡_ {A = Type}) ⋆ ≟ᵗ ⋆ = yes refl (σ₁ ⇒ τ₁) ≟ᵗ (σ₂ ⇒ τ₂) = dcong₂ _⇒_ ⇒-inj (σ₁ ≟ᵗ σ₂) (τ₁ ≟ᵗ τ₂) ⋆ ≟ᵗ (σ₂ ⇒ τ₂) = no λ() (σ₁ ⇒ τ₁) ≟ᵗ ⋆ = no λ() _≟ᶜ_ : Decidable (_≡_ {A = Con}) ε ≟ᶜ ε = yes refl Γ ▻ σ ≟ᶜ Δ ▻ τ = dcong₂ _▻_ ▻-inj (Γ ≟ᶜ Δ) (σ ≟ᵗ τ) ε ≟ᶜ Δ ▻ τ = no λ() Γ ▻ σ ≟ᶜ ε = no λ() data _⊂[_]_ : Con -> Type -> Con -> Set where stop : ∀ {Γ σ} -> Γ ⊂[ σ ] Γ ▻ σ skip : ∀ {Γ Δ σ τ} -> Γ ⊂[ σ ] Δ -> Γ ⊂[ σ ] Δ ▻ τ sub : ∀ {Γ Δ σ} -> Γ ⊂[ σ ] Δ -> σ ∈ Δ sub stop = vz sub (skip p) = vs (sub p) ⊂-inj : ∀ {Γ Δ σ τ} -> Γ ⊂[ σ ] Δ ▻ τ -> Γ ⊂[ σ ] Δ ⊎ Γ ≡ Δ × σ ≡ τ ⊂-inj stop = inj₂ (refl , refl) ⊂-inj (skip p) = inj₁ p _⊂?_ : ∀ {σ} -> Decidable _⊂[ σ ]_ _⊂?_ Γ ε = no λ() _⊂?_ {σ} Γ (Δ ▻ τ) with λ c₁ -> drec (Γ ⊂? Δ) (yes ∘ skip) (λ c₂ -> no ([ c₂ , c₁ ] ∘ ⊂-inj)) ... | r with σ ≟ᵗ τ ... | no c₁ = r (c₁ ∘ proj₂) ... | yes p₁ rewrite p₁ with Γ ≟ᶜ Δ ... | no c₁ = r (c₁ ∘ proj₁) ... | yes p₂ rewrite p₂ = yes stop ⊢_ : Type -> Set ⊢ σ = ∀ {Γ} -> Γ ⊢ σ ⟦_⟧ᵗ : Type -> Set ⟦ ⋆ ⟧ᵗ = ⊢ ⋆ ⟦ σ ⇒ τ ⟧ᵗ = ⟦ σ ⟧ᵗ -> ⟦ τ ⟧ᵗ mutual ↑ : ∀ {σ} -> ⊢ σ -> ⟦ σ ⟧ᵗ ↑ {⋆} t = t ↑ {σ ⇒ τ} f = λ x -> ↑ (f · ↓ x) ↓ : ∀ {σ} -> ⟦ σ ⟧ᵗ -> ⊢ σ ↓ {⋆} t = t ↓ {σ ⇒ τ} f = λ {Γ} -> ƛ (↓ (f (varˢ Γ σ))) varˢ : ∀ Γ σ -> ⟦ σ ⟧ᵗ varˢ Γ σ = ↑ (λ {Δ} -> var (diff Δ Γ σ)) where diff : ∀ Δ Γ σ -> σ ∈ Δ diff Δ Γ σ = drec (Γ ⊂? Δ) sub ⊥ where postulate ⊥ : _ data ⟦_⟧ᶜ : Con -> Set where Ø : ⟦ ε ⟧ᶜ _▷_ : ∀ {Γ σ} -> ⟦ Γ ⟧ᶜ -> ⟦ σ ⟧ᵗ -> ⟦ Γ ▻ σ ⟧ᶜ lookupᵉ : ∀ {Γ σ} -> σ ∈ Γ -> ⟦ Γ ⟧ᶜ -> ⟦ σ ⟧ᵗ lookupᵉ vz (ρ ▷ x) = x lookupᵉ (vs v) (ρ ▷ x) = lookupᵉ v ρ idᵉ : ∀ {Γ} -> ⟦ Γ ⟧ᶜ idᵉ {ε} = Ø idᵉ {Γ ▻ σ} = idᵉ ▷ varˢ Γ σ ⟦_⟧ : ∀ {Γ σ} -> Γ ⊢ σ -> ⟦ Γ ⟧ᶜ -> ⟦ σ ⟧ᵗ ⟦ var v ⟧ ρ = lookupᵉ v ρ ⟦ ƛ b ⟧ ρ = λ x -> ⟦ b ⟧ (ρ ▷ x) ⟦ f · x ⟧ ρ = ⟦ f ⟧ ρ (⟦ x ⟧ ρ) eval : ∀ {Γ σ} -> Γ ⊢ σ -> ⟦ σ ⟧ᵗ eval t = ⟦ t ⟧ idᵉ norm : ∀ {Γ σ} -> Γ ⊢ σ -> Γ ⊢ σ norm t = ↓ (eval t) Term : Type -> Set Term σ = ε ⊢ σ I : Term (⋆ ⇒ ⋆) I = ↓ id K : Term (⋆ ⇒ ⋆ ⇒ ⋆) K = ↓ const S : Term ((⋆ ⇒ ⋆ ⇒ ⋆) ⇒ (⋆ ⇒ ⋆) ⇒ ⋆ ⇒ ⋆) S = ↓ _ˢ_ B : Term ((⋆ ⇒ ⋆) ⇒ (⋆ ⇒ ⋆) ⇒ ⋆ ⇒ ⋆) B = ↓ _∘′_ C : Term ((⋆ ⇒ ⋆ ⇒ ⋆) ⇒ ⋆ ⇒ ⋆ ⇒ ⋆) C = ↓ flip W : Term ((⋆ ⇒ ⋆ ⇒ ⋆) ⇒ ⋆ ⇒ ⋆) W = ↓ λ f x -> f x x P : Term ((⋆ ⇒ ⋆ ⇒ ⋆) ⇒ (⋆ ⇒ ⋆) ⇒ ⋆ ⇒ ⋆ ⇒ ⋆) P = ↓ _on_ O : Term (((⋆ ⇒ ⋆) ⇒ ⋆) ⇒ (⋆ ⇒ ⋆) ⇒ ⋆) O = ↓ λ g f -> f (g f) test₁ : norm (ε ▻ ⋆ ⇒ ⋆ ▻ ⋆ ⊢ ⋆ ∋ (ƛ var (vs vs vz) · var vz) · var vz) ≡ var (vs vz) · var vz test₁ = refl test₂ : S ≡ ƛ ƛ ƛ var (vs vs vz) · var vz · (var (vs vz) · var vz) test₂ = refl
We need pillows and and men's body wash. Beyond these two items, we are overflowing with donations and ask that you hang onto goods at this time. We will let you know when the need for new tangible donations arises. We also need volunteers to help man the distribution center.
module Data.Algebraic.Graph %default total %access public export data Graph : Type -> Type where Empty : Graph type Vertex : (elem : type) -> Graph type Overlay : Graph type -> Graph type -> Graph type Connect : Graph type -> Graph type -> Graph type Show type => Show (Graph type) where show Empty = "Empty" show (Vertex elem) = unwords ["Vertex", show elem] show (Overlay x y) = unwords ["Overlay", show x, show y] show (Connect x y) = unwords ["Connect", show x, show y] Functor Graph where map func Empty = Empty map func (Vertex elem) = Vertex $ func elem map func (Overlay x y) = Overlay (map func x) (map func y) map func (Connect x y) = Connect (map func x) (map func y) Foldable Graph where foldr func init Empty = init foldr func init (Vertex x) = func x init foldr func init (Overlay x y) = foldr func (foldr func init y) x foldr func init (Connect x y) = foldr func (foldr func init y) x Traversable Graph where traverse func Empty = pure Empty traverse func (Vertex elem) = [| Vertex (func elem)|] traverse func (Overlay x y) = [| Overlay (traverse func x) (traverse func y) |] traverse func (Connect x y) = [| Connect (traverse func x) (traverse func y) |] Num type => Num (Graph type) where fromInteger x = Vertex (fromInteger x) (+) = Overlay (*) = Connect -- Do we need abs, negate, and signum? empty : Graph a empty = Empty vertex : a -> Graph a vertex a = Vertex a connect : Graph a -> Graph a -> Graph a connect = Connect edge : a -> a -> Graph a edge x y = connect (vertex x) (vertex y) combine : Graph a -> Graph a -> Graph a combine = Overlay overlay : Graph a -> Graph a -> Graph a overlay = combine foldg : (init : type) -> (whenVertex : a -> type) -> (whenOverlay : type -> type -> type) -> (whenConnect : type -> type -> type) -> (graph : Graph a) -> type foldg init whenVertex whenOverlay whenConnect = go where go : Graph a -> type go Empty = init go (Vertex elem) = whenVertex elem go (Overlay x y) = whenOverlay (go x) (go y) go (Connect x y) = whenConnect (go x) (go y) overlays : List (Graph a) -> Graph a overlays = foldr overlay empty vertices : List a -> Graph a vertices = overlays . map vertex connects : List (Graph a) -> Graph a connects = foldr connect empty edges : List (a,a) -> Graph a edges = overlays . map (uncurry edge) graph : List a -> List (a,a) -> Graph a graph vs es = overlay (vertices vs) (edges es) data HasVertex : (elem : type) -> Graph type -> Type where Here : HasVertex e (Vertex e) ThereOL : HasVertex e l -> HasVertex e (Overlay l r) ThereOR : HasVertex e r -> HasVertex e (Overlay l r) ThereCL : HasVertex e l -> HasVertex e (Connect l r) ThereCR : HasVertex e r -> HasVertex e (Connect l r) graphIsEmpty : HasVertex e Empty -> Void graphIsEmpty Here impossible graphIsEmpty (ThereOL _) impossible graphIsEmpty (ThereOR _) impossible graphIsEmpty (ThereCL _) impossible graphIsEmpty (ThereCR _) impossible notSameVertex : (contra : (e = x) -> Void) -> HasVertex e (Vertex x) -> Void notSameVertex contra Here = contra Refl notOverlay : (contra : HasVertex e x -> Void) -> (f : HasVertex e y -> Void) -> HasVertex e (Overlay x y) -> Void notOverlay contra f x with (x) notOverlay contra f x | (ThereOL y) = contra y notOverlay contra f x | (ThereOR y) = f y notConnect : (contra : HasVertex e x -> Void) -> (f : HasVertex e y -> Void) -> HasVertex e (Connect x y) -> Void notConnect contra f x with (x) notConnect contra f x | (ThereCL y) = contra y notConnect contra f x | (ThereCR y) = f y hasVertex : DecEq type => (elem : type) -> (graph : Graph type) -> Dec (HasVertex elem graph) hasVertex elem Empty = No graphIsEmpty hasVertex elem (Vertex x) with (decEq elem x) hasVertex x (Vertex x) | (Yes Refl) = Yes Here hasVertex elem (Vertex x) | (No contra) = No (notSameVertex contra) hasVertex elem (Overlay x y) with (hasVertex elem x) hasVertex elem (Overlay x y) | (Yes prf) = Yes (ThereOL prf) hasVertex elem (Overlay x y) | (No contra) with (hasVertex elem y) hasVertex elem (Overlay x y) | (No contra) | (Yes prf) = Yes (ThereOR prf) hasVertex elem (Overlay x y) | (No contra) | (No f) = No (notOverlay contra f) hasVertex elem (Connect x y) with (hasVertex elem x) hasVertex elem (Connect x y) | (Yes prf) = Yes (ThereCL prf) hasVertex elem (Connect x y) | (No contra) with (hasVertex elem y) hasVertex elem (Connect x y) | (No contra) | (Yes prf) = Yes (ThereCR prf) hasVertex elem (Connect x y) | (No contra) | (No f) = No (notConnect contra f)
% child script of canlab_glm_publish % runs robust_results_batch in publishable manner % runs in directory containing robust* directories %% prep z = '________________________________________________________________________________________________________'; assignin('base','z',z); if ~exist('thresh','var'), thresh = [.001 .005 .05]; assignin('base','thresh',thresh); end if ~exist('size','var'), size = [5 1 1]; assignin('base','size',size); end if exist('EXPT','var') for i = 1:length(EXPT.SNPM.P) robregdirs{i} = fullfile(pwd,sprintf('robust%04d',i)); connames{i} = EXPT.SNPM.connames(i,:); end else d = filenames('robust[0-9][0-9][0-9][0-9]','absolute'); if isempty(d), d{1} = pwd; end for i = 1:numel(d) robregdirs{i} = d{i}; load(fullfile(robregdirs{i},'SETUP.mat')); load(fullfile(fileparts(SETUP.files(1,:)),'SPM.mat')); c = regexprep(SETUP.files(1,:),'.*con_0*([0-9]*)\.nii','$1'); connames{i} = SPM.xCon(str2num(c)).name; end end %% write script scriptfile = 'robfit_results.m'; scriptfileabs = fullfile(pwd,scriptfile); fid = fopen(scriptfile,'w'); for i = 1:length(robregdirs) fprintf(fid,'%%%% contrast(%d) %s\n',i,connames{i}); fprintf(fid,'cd(''%s'')\n',robregdirs{i}); fprintf(fid,'fprintf(''%%s\\n%%s\\n%%s\\n%%s\\n%%s\\n%%s\\n'',z,z,''%s'',''%s'',z,z)\n',connames{i},robregdirs{i}); fprintf(fid,'try\n'); maskimg = fullfile(robregdirs{i}, 'rob_tmap_0001.img'); % any image in space with non-zero vals for all vox would do %fprintf(fid,'robust_results_batch(''thresh'', thresh, ''size'', size, ''prune'', ''mask'', ''%s'');\n',maskimg); fprintf(fid,'robust_results_batch;\n'); fprintf(fid,'catch exc\n'); fprintf(fid,'disp(getReport(exc,''extended''))\n'); fprintf(fid,'end\n'); end fprintf(fid,'close all\n'); fclose(fid); %% publish script outputdir = fullfile(pwd, 'Robust_Regression_Results_html'); mkdir(outputdir); p = struct('useNewFigure', false, 'maxHeight', 1500, 'maxWidth', 1200, ... 'outputDir', outputdir, 'showCode', false); fout = publish(scriptfile, p); fprintf('Created robfit results directory:\n%s\nHTML report: %s\n', outputdir, fout); %% clean up close all delete(scriptfileabs)
" Clearly , the armies of industry professionals that put Beyoncé together aren 't sure of her core audience . A vague Saturday night TV , family entertainment feel gradually gives way to a more intriguing cross between Liza Minelli showbiz and thumping R & B. However , a ticker tape festooned Crazy In Love and a belting Work It Out suggest Beyoncé is best sticking to her roots . <unk> , if implausibly , she puts the carnage down to her tour manager falling off stage , but at least she 's grasped one showbiz adage : the show must go on . "
module Abishekrajan.Odds import Evens import Intro data IsOdd : Nat -> Type where OneOdd : IsOdd 1 SSOdd : (n : Nat) -> IsOdd n -> IsOdd (S (S n)) threeOdd : IsOdd 3 threeOdd = SSOdd 1 OneOdd twoNotOdd : IsOdd 2 -> Void twoNotOdd (SSOdd Z OneOdd) impossible twoNotOdd (SSOdd Z (SSOdd x y)) impossible nOddSnEven : (n: Nat) -> IsOdd n -> IsEven (S n) nOddSnEven (S Z) OneOdd = (SSEven Z ZEven) nOddSnEven (S (S k)) (SSOdd k x) = SSEven (S k) (nOddSnEven k x) nEvenSnOdd : (n: Nat) -> IsEven n -> IsOdd (S n) nEvenSnOdd Z ZEven = OneOdd nEvenSnOdd (S (S k)) (SSEven k x) = SSOdd (S k) (nEvenSnOdd k x) nEvenOrOdd : (n: Nat) -> Either (IsEven n) (IsOdd n) nEvenOrOdd Z = Left ZEven nEvenOrOdd (S k) = case (nEvenOrOdd k) of (Left l) => Right (nEvenSnOdd k l) (Right r) => Left (nOddSnEven k r) nNotEvenAndOdd : (n: Nat) -> (IsEven n) -> (IsOdd n) -> Void nNotEvenAndOdd Z ZEven OneOdd impossible nNotEvenAndOdd Z ZEven (SSOdd p q) impossible nNotEvenAndOdd (S (S k)) (SSEven k x) (SSOdd k y) = nNotEvenAndOdd k x y mOddnOddmplusnEven : (m: Nat) -> IsOdd m -> (n: Nat) -> IsOdd n -> IsEven (add m n) mOddnOddmplusnEven (S Z) OneOdd (S Z) OneOdd = SSEven 0 ZEven mOddnOddmplusnEven (S Z) OneOdd (S (S k)) (SSOdd k x) = SSEven (S k) (mOddnOddmplusnEven (S Z) OneOdd k x) mOddnOddmplusnEven (S (S k)) (SSOdd k x) n y = SSEven (add k n) (mOddnOddmplusnEven k x n y) apNat : (f: Nat -> Nat) -> (n: Nat) -> (m: Nat) -> n = m -> f n = f m apNat f m m Refl = Refl oddIsSDouble : (n: Nat) -> IsOdd n -> (k: Nat ** (S (double k)) = n) oddIsSDouble (S Z) OneOdd = (0 ** Refl) oddIsSDouble (S (S k)) (SSOdd k x) = case (oddIsSDouble k x) of (m ** y) => ((S m) ** apNat (\l => S (S l)) (S (double m)) k y)
function currentVal=getImageRotate(view) % % currentVal=getImageRotate(view) % % Returns the value of the image rotate slider in radians if isequal(view.name, 'hidden') % instead of a handle to the slider, the ImageRotate field will % directly store the rotations for hidden views: currentVal = view.ui.ImageRotate; else % non-hidden view: view.ui.ImageRotate should be a slider struct currentVal = get(view.ui.ImageRotate.sliderHandle, 'Value'); end return
module Verified.Algebra.Bool import Classes.Verified import Prelude.Algebra %default total instance Semigroup Bool where -- Laziness intereferes with the types (<+>) = \b1, b2 => b1 || b2 instance VerifiedSemigroup Bool where semigroupOpIsAssociative True _ _ = Refl semigroupOpIsAssociative False True _ = Refl semigroupOpIsAssociative False False True = Refl semigroupOpIsAssociative False False False = Refl instance Monoid Bool where neutral = False instance VerifiedMonoid Bool where monoidNeutralIsNeutralL True = Refl monoidNeutralIsNeutralL False = Refl monoidNeutralIsNeutralR r = Refl
export PIBasis # ---------------------- Implementation of the PIBasisSpec """ `struct PIBasisSpec` """ struct PIBasisSpec orders::Vector{Int} # order (length) of ith basis function iAA2iA::Matrix{Int} # where in A can we find the ith basis function end ==(B1::PIBasisSpec, B2::PIBasisSpec) = _allfieldsequal(B1, B2) Base.length(spec::PIBasisSpec) = length(spec.orders) maxcorrorder(spec::PIBasisSpec) = size(spec.iAA2iA, 2) function _get_pibfcn(spec0, Aspec, vv) vv1 = vv[2:end] vvnz = vv1[findall(vv1 .!= 0)] return (spec0[vv[1]], Aspec[vvnz]) end function _get_pibfcn(Aspec, vv) vvnz = vv[findall(vv .!= 0)] return Aspec[vvnz] end # TODO: maybe instead of property == nothing, there should be a # generic property with no symmetry attached to it. function PIBasisSpec( basis1p::OneParticleBasis, symgrp::SymmetryGroup, Bsel::DownsetBasisSelector; property = nothing, filterfun = _->true, init1pbasis = true ) # we initialize the 1p-basis here; to prevent this it must be manually # avoided by passing in init1pbasis = false if init1pbasis init1pspec!(basis1p, Bsel) end # get the basis spec of the one-particle basis # Aspec[i] described the basis function that will get written into A[i] Aspec = get_spec(basis1p) # we assume that `Aspec` is sorted by degree, but best to double-check this # since the notion of degree used to construct `Aspec` might be different # from the one used to construct AAspec. if !issorted(Aspec; by = b -> level(b, Bsel, basis1p)) error("""PIBasisSpec : AAspec construction failed because Aspec is not sorted by degree. This could e.g. happen if an incompatible notion of degree was used to construct the 1-p basis spec.""") end # An AA basis function is given by a tuple 𝒗 = vv. Each index 𝒗ᵢ = vv[i] # corresponds to the basis function Aspec[𝒗ᵢ] and the tuple # 𝒗 = (𝒗₁, ...) to a product basis function # ∏ A_{vₐ} tup2b = vv -> _get_pibfcn(Aspec, vv) # degree or level of a basis function ↦ is it admissible? admissible = bb -> (level(bb, Bsel, basis1p) <= maxlevel(bb, Bsel, basis1p)) if property != nothing filter1 = bb -> filterfun(bb) && filter(bb, Bsel, basis1p) && filter(property, symgrp, bb) else filter1 = bb -> filterfun(bb) && filter(bb, Bsel, basis1p) end # we can now construct the basis specification; the `ordered = true` # keyword signifies that this is a permutation-invariant basis maxord = maxorder(Bsel) AAspec = gensparse(; NU = maxorder(Bsel), tup2b = tup2b, admissible = admissible, ordered = true, maxvv = [length(Aspec) for _=1:maxord], filter = filter1) return PIBasisSpec(AAspec) end function PIBasisSpec(AAspec) orders = zeros(Int, length(AAspec)) iAA2iA = zeros(Int, (length(AAspec), length(AAspec[1]))) for (iAA, vv) in enumerate(AAspec) # we use reverse because gensparse constructs the indices in # ascending order, but we want descending here. # (I don't remember why though) iAA2iA[iAA, :] .= reverse(vv) orders[iAA] = length( findall( vv .!= 0 ) ) end return PIBasisSpec(orders, iAA2iA) end get_spec(AAspec::PIBasisSpec, i::Integer) = AAspec.iAA2iA[i, 1:AAspec.orders[i]] # ------------------ PISpec sparsification """ returns a new `PIBasisSpec` constructed from the old one, but keeping only the basis indices `Ikeep`. This maintains the order of the basis functions. """ sparsify(spec::PIBasisSpec, Ikeep::AbstractVector{<: Integer}) = PIBasisSpec(spec.orders[Ikeep], spec.iAA2iA[Ikeep, :]) function _fix_A_indices!(spec::PIBasisSpec, new_inds::AbstractVector{<: Integer}) for iAA = 1:size(spec.iAA2iA, 1) for α = 1:spec.orders[iAA] vα = spec.iAA2iA[iAA, α] new_vα = new_inds[vα] @assert new_vα > 0 spec.iAA2iA[iAA, α] = new_vα end end return nothing end # --------------------------------- PIBasis implementation """ `mutable struct PIBasis:` implementation of a permutation-invariant basis based on the density projection trick. The standard constructor is ``` PIBasis(basis1p, N, D, maxdeg) ``` * `basis1p` : a one-particle basis * `N` : maximum interaction order * `D` : an abstract degee specification, e.g., SparsePSHDegree * `maxdeg` : the maximum polynomial degree as measured by `D` """ mutable struct PIBasis{BOP, REAL, TB, TA} <: ACEBasis basis1p::BOP # a one-particle basis spec::PIBasisSpec real::REAL # could be `real` or `identity` to keep AA complex # evaluator # classic vs graph B_pool::VectorPool{TB} dAA_pool::VectorPool{TA} end cutoff(basis::PIBasis) = cutoff(basis.basis1p) ==(B1::PIBasis, B2::PIBasis) = ( (B1.basis1p == B2.basis1p) && (B1.spec == B2.spec) && (B1.real == B2.real) ) valtype(basis::PIBasis) = basis.real( valtype(basis.basis1p) ) valtype(basis::PIBasis, cfg::AbstractConfiguration) = basis.real( valtype(basis.basis1p, cfg) ) gradtype(basis::PIBasis, cfgorX) = basis.real( gradtype(basis.basis1p, cfgorX) ) Base.length(basis::PIBasis) = length(basis.spec) # default symmetry group PIBasis(basis1p, Bsel::AbstractBasisSelector; kwargs...) = PIBasis(basis1p, O3(), Bsel; kwargs...) PIBasis(basis1p, symgrp, Bsel::AbstractBasisSelector; isreal = false, kwargs...) = PIBasis(basis1p, PIBasisSpec(basis1p, symgrp, Bsel; kwargs...), isreal ? Base.real : Base.identity ) function PIBasis(basis1p::OneParticleBasis, spec::PIBasisSpec, real) VT1 = valtype(basis1p) VT = real(VT1) # default valtype B_pool = VectorPool{VT}() dAA_pool = VectorPool{VT1}() return PIBasis(basis1p, spec, real, B_pool, dAA_pool) end get_spec(pibasis::PIBasis) = [ get_spec(pibasis, i) for i = 1:length(pibasis) ] get_spec(pibasis::PIBasis, i::Integer) = get_spec.( Ref(pibasis.basis1p), get_spec(pibasis.spec, i) ) setreal(basis::PIBasis, isreal::Bool) = PIBasis(basis.basis1p, basis.spec, isreal) maxcorrorder(basis::PIBasis) = maxcorrorder(basis.spec) # ------------------ sparsification function sparsify!(basis::PIBasis, Ikeep::AbstractVector{<: Integer}) basis.spec = sparsify(basis.spec, Ikeep) return basis end """ This should allow the 1p basis to sparsify itself, then feed back to the pibasis what the correct indices are. """ function clean_1pbasis!(basis::PIBasis) spec = get_spec(basis) B1p = basis.basis1p spec1p = NamedTuple[] for bb in spec append!(spec1p, bb) end identity.(unique!(spec1p)) # sparsify the product 1p basis _, new_inds = sparsify!(basis.basis1p, spec1p) # now fix the indexing of the PIBasis specification _fix_A_indices!(basis.spec, new_inds) return basis end # syms = symbols(B1p) # rgs = Dict{Symbol, Any}([sym => [] for sym in syms]...) # for bb in spec, b in bb, sym in keys(b) # push!(rgs[sym], getproperty(b, sym)) # end # for sym in syms # rgs[sym] = identity.(unique(rgs[sym])) # end # ------------------- _scaling_absvalue(x::Number) = abs(x) _scaling_absvalue(x::Symbol) = 0 # TODO: this is a hack; cf. #68 function scaling(pibasis::PIBasis, p) ww = zeros(Float64, length(pibasis)) bspec = get_spec(pibasis) for i = 1:length(pibasis) for b in bspec[i] # TODO: revisit how this should be implemented for a general basis ww[i] += sum(x -> _scaling_absvalue(x)^p, b) # abs.(values(b)).^p end end return ww end # function scaling(pibasis::PIBasis, p) # ww = zeros(Float64, length(pibasis)) # for iz0 = 1:numz(pibasis) # wwin = @view ww[pibasis.inner[iz0].AAindices] # for i = 1:length(pibasis.inner[iz0]) # bspec = get_basis_spec(pibasis, iz0, i) # wwin[i] = scaling(bspec, p) # end # end # return ww # end # graphevaluator(basis::PIBasis) = # PIBasis(basis.basis1p, zlist(basis), basis.inner, DAGEvaluator()) # # standardevaluator(basis::PIBasis) = # PIBasis(basis.basis1p, zlist(basis), basis.inner, StandardEvaluator()) # ------------------------------------------------- # FIO codes write_dict(basis::PIBasis) = Dict( "__id__" => "ACE_PIBasis", "basis1p" => write_dict(basis.basis1p), "spec" => write_dict(basis.spec), "real" => basis.real == Base.real ? true : false ) read_dict(::Val{:ACE_PIBasis}, D::Dict) = PIBasis( read_dict(D["basis1p"]), read_dict(D["spec"]), D["real"] ? Base.real : Base.identity ) write_dict(spec::PIBasisSpec) = Dict( "__id__" => "ACE_PIBasisSpec", "orders" => spec.orders, "iAA2iA" => write_dict(spec.iAA2iA) ) read_dict(::Val{:ACE_PIBasisSpec}, D::Dict) = PIBasisSpec( D["orders"], read_dict(D["iAA2iA"]) ) # ------------------------------------------------- # Evaluation codes function evaluate!(AA, basis::PIBasis, config::AbstractConfiguration) A = acquire_B!(basis.basis1p, config) # THIS ALLOCATES!!!! evaluate!(A, basis.basis1p, config) fill!(AA, 1) for iAA = 1:length(basis) aa = one(eltype(A)) for t = 1:basis.spec.orders[iAA] aa *= A[ basis.spec.iAA2iA[ iAA, t ] ] end AA[iAA] = basis.real(aa) end release_B!(basis.basis1p, A) return AA end # ------------------------------------------------- # gradients ACE.evaluate_d(basis::PIBasis, cfg::AbstractConfiguration, args...) = ACE.evaluate_ed(basis::PIBasis, cfg::AbstractConfiguration, args...)[2] function evaluate_ed!(AA, dAA, basis::PIBasis, cfg::AbstractConfiguration, args...) A = acquire_B!(basis.basis1p, cfg) dA = acquire_dB!(basis.basis1p, cfg) # TODO: THIS WILL ALLOCATE!!!!! evaluate_ed!(A, dA, basis.basis1p, cfg, args...) evaluate_ed!(AA, dAA, basis, A, dA) release_dB!(basis.basis1p, dA) release_B!(basis.basis1p, A) return AA, dAA end function _AA_local_adjoints!(dAAdA, A, iAA2iA, iAA, ord, _real) if ord == 1 return _AA_local_adjoints_1!(dAAdA, A, iAA2iA, iAA, ord, _real) elseif ord == 2 return _AA_local_adjoints_2!(dAAdA, A, iAA2iA, iAA, ord, _real) # elseif ord == 3 # return _AA_local_adjoints_3!(dAAdA, A, iAA2iA, iAA, ord, _real) # elseif ord == 4 # return _AA_local_adjoints_4!(dAAdA, A, iAA2iA, iAA, ord, _real) else return _AA_local_adjoints_x!(dAAdA, A, iAA2iA, iAA, ord, _real) end end function _AA_local_adjoints_1!(dAAdA, A, iAA2iA, iAA, ord, _real) @inbounds dAAdA[1] = 1 @inbounds A1 = A[iAA2iA[iAA, 1]] return _real(A1) end function _AA_local_adjoints_2!(dAAdA, A, iAA2iA, iAA, ord, _real) @inbounds A1 = A[iAA2iA[iAA, 1]] @inbounds A2 = A[iAA2iA[iAA, 2]] @inbounds dAAdA[1] = A2 @inbounds dAAdA[2] = A1 return _real(A1 * A2) end # function _AA_local_adjoints_3!(dAAdA, A, iAA2iA, iAA, ord, _real) # A1 = A[iAA2iA[iAA, 1]] # A2 = A[iAA2iA[iAA, 2]] # A3 = A[iAA2iA[iAA, 3]] # A12 = A1 * A2 # dAAdA[1] = A2 * A3 # dAAdA[2] = A1 * A3 # dAAdA[3] = A12 # return _real(A12 * A3) # end # function _AA_local_adjoints_4!(dAAdA, A, iAA2iA, iAA, ord, _real) # @inbounds A1 = A[iAA2iA[iAA, 1]] # @inbounds A2 = A[iAA2iA[iAA, 2]] # @inbounds A3 = A[iAA2iA[iAA, 3]] # @inbounds A4 = A[iAA2iA[iAA, 4]] # A12 = A1 * A2 # A34 = A3 * A4 # @inbounds dAAdA[1] = A2 * A34 # @inbounds dAAdA[2] = A1 * A34 # @inbounds dAAdA[3] = A12 * A4 # @inbounds dAAdA[4] = A12 * A3 # return _real(A12 * A34) # end function _AA_local_adjoints_x!(dAAdA, A, iAA2iA, iAA, ord, _real) @assert length(dAAdA) >= ord @assert ord >= 2 # TODO - optimize a bit more? can move one operation out of the loop # Forward pass: @inbounds A1 = A[iAA2iA[iAA, 1]] @inbounds A2 = A[iAA2iA[iAA, 2]] @inbounds dAAdA[1] = 1 @inbounds dAAdA[2] = A1 @inbounds AAfwd = A1 * A2 @inbounds for a = 3:ord-1 dAAdA[a] = AAfwd AAfwd *= A[iAA2iA[iAA, a]] end @inbounds dAAdA[ord] = AAfwd @inbounds Aend = A[iAA2iA[iAA, ord]] aa = _real(AAfwd * Aend) # backward pass @inbounds AAbwd = Aend @inbounds for a = ord-1:-1:3 dAAdA[a] *= AAbwd AAbwd *= A[iAA2iA[iAA, a]] end dAAdA[2] *= AAbwd AAbwd *= A2 dAAdA[1] *= AAbwd return aa end _acquire_dAAdA!(basis::PIBasis) = acquire!(basis.dAA_pool, maxcorrorder(basis)) function evaluate_ed!(AA, dAA, basis::PIBasis, A::AbstractVector, dA::AbstractMatrix) orders = basis.spec.orders iAA2iA = basis.spec.iAA2iA dAAdA = _acquire_dAAdA!(basis) # Must treat the constants separately. This is not so elegant and could # maybe be improved? if orders[1] == 0 # SHOULD BE THE ONLY ONE with ord=0!! iAAinit = 2 AA[1] = 1.0 dAA[1, :] .= Ref(zero(eltype(dAA))) else iAAinit = 1 end for iAA = iAAinit:length(basis) ord = orders[iAA] # ----- compute the local adjoints dAA / dA # dAAdA[a] ← ∏_{t ≂̸ a} A_{v_t} AA[iAA] = _AA_local_adjoints!(dAAdA, A, iAA2iA, iAA, orders[iAA], basis.real) # ----- now convert them into dAA / dX for j = 1:size(dA, 2) dAA[iAA, j] = sum(dAAdA[a] * dA[iAA2iA[iAA, a], j] for a = 1:ord) |> basis.real end end return AA, dAA end
context("ipairwise iterator") test_that("ipairwise functions properly with an iterator", { it <- iterators::iter(letters[1:4]) it_ipairwise <- ipairwise(it) expect_equal(iterators::nextElem(it_ipairwise), list("a", "b")) expect_equal(iterators::nextElem(it_ipairwise), list("b", "c")) expect_equal(iterators::nextElem(it_ipairwise), list("c", "d")) expect_error(iterators::nextElem(it_ipairwise), "StopIteration") }) test_that("ipairwise functions properly with a vector", { it_ipairwise <- ipairwise(letters[1:5]) expect_equal(iterators::nextElem(it_ipairwise), list("a", "b")) expect_equal(iterators::nextElem(it_ipairwise), list("b", "c")) expect_equal(iterators::nextElem(it_ipairwise), list("c", "d")) expect_equal(iterators::nextElem(it_ipairwise), list("d", "e")) expect_error(iterators::nextElem(it_ipairwise), "StopIteration") })
function [ a, b ] = p53_lim ( ) %*****************************************************************************80 % %% P53_LIM returns the integration limits for problem 53. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 04 November 2009 % % Author: % % John Burkardt % % Parameters: % % Output, real A, B, the limits of integration. % a = 0.0; b = 1.0; return end
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <math.h> #include <gsl/gsl_integration.h> double f1(double x, void *params) { (void) (params); /* avoid unused parameter warning */ return pow(x, 2); } double fi1(double x) { return pow(x, 3) / 3; } double f2(double x, void *params) { (void) (params); /* avoid unused parameter warning */ if (0 == x) { return 0; } return 1 / sqrt(x); } double fi2(double x) { return 2 * sqrt(x); } double pi(double (*fi)(double), double x1, double x2) { return fi(x2) - fi(x1); } double e(double p1, double p2) { return fabs(p1 - p2); } int main(int argc, char *argv[]) { double a, b, pg1, e1, pi1, pg2, e2, pi2; if (argc < 2) { errno = EINVAL; perror(""); return errno; } a = strtod(argv[1], NULL); b = strtod(argv[2], NULL); if (0 != errno) { perror(""); return errno; } gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(1000); gsl_function F1; F1.function = &f1; gsl_integration_qags(&F1, a, b, 0, 1e-7, 1000, w1, &pg1, &e1); pi1 = pi(fi1, a, b); gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(1000); gsl_function F2; F2.function = &f2; gsl_integration_qags(&F2, a, b, 0, 1e-7, 1000, w2, &pg2, &e2); pi2 = pi(fi2, a, b); printf("%f\t%f\n", pg1, pg2); printf("%f\t%f\n", pi1, pi2); printf("%e\t%e\n", e(pg1, pi1), e(pg2, pi2)); printf("%zu\t%zu\n", w1->size, w2->size); gsl_integration_workspace_free(w1); gsl_integration_workspace_free(w2); return EXIT_SUCCESS; }
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca ! This file was ported from Lean 3 source module algebra.gcd_monoid.div ! leanprover-community/mathlib commit b537794f8409bc9598febb79cd510b1df5f4539d ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.GcdMonoid.Finset import Mathbin.Algebra.GcdMonoid.Basic import Mathbin.RingTheory.Int.Basic import Mathbin.RingTheory.Polynomial.Content /-! # Basic results about setwise gcds on normalized gcd monoid with a division. ## Main results * `finset.nat.gcd_div_eq_one`: given a nonempty finset `s` and a function `f` from `s` to `ℕ`, if `d = s.gcd`, then the `gcd` of `(f i) / d` equals `1`. * `finset.int.gcd_div_eq_one`: given a nonempty finset `s` and a function `f` from `s` to `ℤ`, if `d = s.gcd`, then the `gcd` of `(f i) / d` equals `1`. * `finset.polynomial.gcd_div_eq_one`: given a nonempty finset `s` and a function `f` from `s` to `K[X]`, if `d = s.gcd`, then the `gcd` of `(f i) / d` equals `1`. ## TODO Add a typeclass to state these results uniformly. -/ namespace Finset namespace Nat /- warning: finset.nat.gcd_div_eq_one -> Finset.Nat.gcd_div_eq_one is a dubious translation: lean 3 declaration is forall {β : Type.{u1}} {f : β -> Nat} (s : Finset.{u1} β) {x : β}, (Membership.Mem.{u1, u1} β (Finset.{u1} β) (Finset.hasMem.{u1} β) x s) -> (Ne.{1} Nat (f x) (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) -> (Eq.{1} Nat (Finset.gcd.{0, u1} Nat β Nat.cancelCommMonoidWithZero Nat.normalizedGcdMonoid s (fun (b : β) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) (f b) (Finset.gcd.{0, u1} Nat β Nat.cancelCommMonoidWithZero Nat.normalizedGcdMonoid s f))) (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) but is expected to have type forall {β : Type.{u1}} {f : β -> Nat} (s : Finset.{u1} β) {x : β}, (Membership.mem.{u1, u1} β (Finset.{u1} β) (Finset.instMembershipFinset.{u1} β) x s) -> (Ne.{1} Nat (f x) (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) -> (Eq.{1} Nat (Finset.gcd.{0, u1} Nat β Nat.cancelCommMonoidWithZero instNormalizedGCDMonoidNatCancelCommMonoidWithZero s (fun (b : β) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (f b) (Finset.gcd.{0, u1} Nat β Nat.cancelCommMonoidWithZero instNormalizedGCDMonoidNatCancelCommMonoidWithZero s f))) (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) Case conversion may be inaccurate. Consider using '#align finset.nat.gcd_div_eq_one Finset.Nat.gcd_div_eq_oneₓ'. -/ /-- Given a nonempty finset `s` and a function `f` from `s` to `ℕ`, if `d = s.gcd`, then the `gcd` of `(f i) / d` is equal to `1`. -/ theorem gcd_div_eq_one {β : Type _} {f : β → ℕ} (s : Finset β) {x : β} (hx : x ∈ s) (hfz : f x ≠ 0) : (s.gcd fun b => f b / s.gcd f) = 1 := by obtain ⟨g, he, hg⟩ := Finset.extract_gcd f ⟨x, hx⟩ refine' (Finset.gcd_congr rfl fun a ha => _).trans hg rw [he a ha, Nat.mul_div_cancel_left] exact Nat.pos_of_ne_zero (mt Finset.gcd_eq_zero_iff.1 fun h => hfz <| h x hx) #align finset.nat.gcd_div_eq_one Finset.Nat.gcd_div_eq_one /- warning: finset.nat.gcd_div_id_eq_one -> Finset.Nat.gcd_div_id_eq_one is a dubious translation: lean 3 declaration is forall {s : Finset.{0} Nat} {x : Nat}, (Membership.Mem.{0, 0} Nat (Finset.{0} Nat) (Finset.hasMem.{0} Nat) x s) -> (Ne.{1} Nat x (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero)))) -> (Eq.{1} Nat (Finset.gcd.{0, 0} Nat Nat Nat.cancelCommMonoidWithZero Nat.normalizedGcdMonoid s (fun (b : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) b (Finset.gcd.{0, 0} Nat Nat Nat.cancelCommMonoidWithZero Nat.normalizedGcdMonoid s (id.{1} Nat)))) (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) but is expected to have type forall {s : Finset.{0} Nat} {x : Nat}, (Membership.mem.{0, 0} Nat (Finset.{0} Nat) (Finset.instMembershipFinset.{0} Nat) x s) -> (Ne.{1} Nat x (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))) -> (Eq.{1} Nat (Finset.gcd.{0, 0} Nat Nat Nat.cancelCommMonoidWithZero instNormalizedGCDMonoidNatCancelCommMonoidWithZero s (fun (b : Nat) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) b (Finset.gcd.{0, 0} Nat Nat Nat.cancelCommMonoidWithZero instNormalizedGCDMonoidNatCancelCommMonoidWithZero s (id.{1} Nat)))) (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) Case conversion may be inaccurate. Consider using '#align finset.nat.gcd_div_id_eq_one Finset.Nat.gcd_div_id_eq_oneₓ'. -/ theorem gcd_div_id_eq_one {s : Finset ℕ} {x : ℕ} (hx : x ∈ s) (hnz : x ≠ 0) : (s.gcd fun b => b / s.gcd id) = 1 := gcd_div_eq_one s hx hnz #align finset.nat.gcd_div_id_eq_one Finset.Nat.gcd_div_id_eq_one end Nat namespace Int /- warning: finset.int.gcd_div_eq_one -> Finset.Int.gcd_div_eq_one is a dubious translation: lean 3 declaration is forall {β : Type.{u1}} {f : β -> Int} (s : Finset.{u1} β) {x : β}, (Membership.Mem.{u1, u1} β (Finset.{u1} β) (Finset.hasMem.{u1} β) x s) -> (Ne.{1} Int (f x) (OfNat.ofNat.{0} Int 0 (OfNat.mk.{0} Int 0 (Zero.zero.{0} Int Int.hasZero)))) -> (Eq.{1} Int (Finset.gcd.{0, u1} Int β (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.commSemiring (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.normalizedGcdMonoid s (fun (b : β) => HDiv.hDiv.{0, 0, 0} Int Int Int (instHDiv.{0} Int Int.hasDiv) (f b) (Finset.gcd.{0, u1} Int β (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.commSemiring (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.normalizedGcdMonoid s f))) (OfNat.ofNat.{0} Int 1 (OfNat.mk.{0} Int 1 (One.one.{0} Int Int.hasOne)))) but is expected to have type forall {β : Type.{u1}} {f : β -> Int} (s : Finset.{u1} β) {x : β}, (Membership.mem.{u1, u1} β (Finset.{u1} β) (Finset.instMembershipFinset.{u1} β) x s) -> (Ne.{1} Int (f x) (OfNat.ofNat.{0} Int 0 (instOfNatInt 0))) -> (Eq.{1} Int (Finset.gcd.{0, u1} Int β (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.instCommSemiringInt (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.instNormalizedGCDMonoidIntToCancelCommMonoidWithZeroInstCommSemiringIntIsDomainToLinearOrderedRingLinearOrderedCommRing s (fun (b : β) => HDiv.hDiv.{0, 0, 0} Int Int Int (instHDiv.{0} Int Int.instDivInt_1) (f b) (Finset.gcd.{0, u1} Int β (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.instCommSemiringInt (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.instNormalizedGCDMonoidIntToCancelCommMonoidWithZeroInstCommSemiringIntIsDomainToLinearOrderedRingLinearOrderedCommRing s f))) (OfNat.ofNat.{0} Int 1 (instOfNatInt 1))) Case conversion may be inaccurate. Consider using '#align finset.int.gcd_div_eq_one Finset.Int.gcd_div_eq_oneₓ'. -/ /-- Given a nonempty finset `s` and a function `f` from `s` to `ℤ`, if `d = s.gcd`, then the `gcd` of `(f i) / d` is equal to `1`. -/ theorem gcd_div_eq_one {β : Type _} {f : β → ℤ} (s : Finset β) {x : β} (hx : x ∈ s) (hfz : f x ≠ 0) : (s.gcd fun b => f b / s.gcd f) = 1 := by obtain ⟨g, he, hg⟩ := Finset.extract_gcd f ⟨x, hx⟩ refine' (Finset.gcd_congr rfl fun a ha => _).trans hg rw [he a ha, Int.mul_ediv_cancel_left] exact mt Finset.gcd_eq_zero_iff.1 fun h => hfz <| h x hx #align finset.int.gcd_div_eq_one Finset.Int.gcd_div_eq_one /- warning: finset.int.gcd_div_id_eq_one -> Finset.Int.gcd_div_id_eq_one is a dubious translation: lean 3 declaration is forall {s : Finset.{0} Int} {x : Int}, (Membership.Mem.{0, 0} Int (Finset.{0} Int) (Finset.hasMem.{0} Int) x s) -> (Ne.{1} Int x (OfNat.ofNat.{0} Int 0 (OfNat.mk.{0} Int 0 (Zero.zero.{0} Int Int.hasZero)))) -> (Eq.{1} Int (Finset.gcd.{0, 0} Int Int (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.commSemiring (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.normalizedGcdMonoid s (fun (b : Int) => HDiv.hDiv.{0, 0, 0} Int Int Int (instHDiv.{0} Int Int.hasDiv) b (Finset.gcd.{0, 0} Int Int (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.commSemiring (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.normalizedGcdMonoid s (id.{1} Int)))) (OfNat.ofNat.{0} Int 1 (OfNat.mk.{0} Int 1 (One.one.{0} Int Int.hasOne)))) but is expected to have type forall {s : Finset.{0} Int} {x : Int}, (Membership.mem.{0, 0} Int (Finset.{0} Int) (Finset.instMembershipFinset.{0} Int) x s) -> (Ne.{1} Int x (OfNat.ofNat.{0} Int 0 (instOfNatInt 0))) -> (Eq.{1} Int (Finset.gcd.{0, 0} Int Int (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.instCommSemiringInt (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.instNormalizedGCDMonoidIntToCancelCommMonoidWithZeroInstCommSemiringIntIsDomainToLinearOrderedRingLinearOrderedCommRing s (fun (b : Int) => HDiv.hDiv.{0, 0, 0} Int Int Int (instHDiv.{0} Int Int.instDivInt_1) b (Finset.gcd.{0, 0} Int Int (IsDomain.toCancelCommMonoidWithZero.{0} Int Int.instCommSemiringInt (LinearOrderedRing.isDomain.{0} Int (LinearOrderedCommRing.toLinearOrderedRing.{0} Int Int.linearOrderedCommRing))) Int.instNormalizedGCDMonoidIntToCancelCommMonoidWithZeroInstCommSemiringIntIsDomainToLinearOrderedRingLinearOrderedCommRing s (id.{1} Int)))) (OfNat.ofNat.{0} Int 1 (instOfNatInt 1))) Case conversion may be inaccurate. Consider using '#align finset.int.gcd_div_id_eq_one Finset.Int.gcd_div_id_eq_oneₓ'. -/ theorem gcd_div_id_eq_one {s : Finset ℤ} {x : ℤ} (hx : x ∈ s) (hnz : x ≠ 0) : (s.gcd fun b => b / s.gcd id) = 1 := gcd_div_eq_one s hx hnz #align finset.int.gcd_div_id_eq_one Finset.Int.gcd_div_id_eq_one end Int namespace Polynomial open Polynomial Classical noncomputable section variable {K : Type _} [Field K] #print Finset.Polynomial.gcd_div_eq_one /- /-- Given a nonempty finset `s` and a function `f` from `s` to `K[X]`, if `d = s.gcd f`, then the `gcd` of `(f i) / d` is equal to `1`. -/ theorem gcd_div_eq_one {β : Type _} {f : β → K[X]} (s : Finset β) {x : β} (hx : x ∈ s) (hfz : f x ≠ 0) : (s.gcd fun b => f b / s.gcd f) = 1 := by obtain ⟨g, he, hg⟩ := Finset.extract_gcd f ⟨x, hx⟩ refine' (Finset.gcd_congr rfl fun a ha => _).trans hg rw [he a ha, EuclideanDomain.mul_div_cancel_left] exact mt Finset.gcd_eq_zero_iff.1 fun h => hfz <| h x hx #align finset.polynomial.gcd_div_eq_one Finset.Polynomial.gcd_div_eq_one -/ #print Finset.Polynomial.gcd_div_id_eq_one /- theorem gcd_div_id_eq_one {s : Finset K[X]} {x : K[X]} (hx : x ∈ s) (hnz : x ≠ 0) : (s.gcd fun b => b / s.gcd id) = 1 := gcd_div_eq_one s hx hnz #align finset.polynomial.gcd_div_id_eq_one Finset.Polynomial.gcd_div_id_eq_one -/ end Polynomial end Finset
Formal statement is: lemma (in t0_space) separation_t0: "x \<noteq> y \<longleftrightarrow> (\<exists>U. open U \<and> \<not> (x \<in> U \<longleftrightarrow> y \<in> U))" Informal statement is: In a $T_0$ space, two points are distinct if and only if there is an open set that contains one of them but not the other.
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn ! This file was ported from Lean 3 source module logic.encodable.lattice ! leanprover-community/mathlib commit f2f413b9d4be3a02840d0663dace76e8fe3da053 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Logic.Encodable.Basic import Mathbin.Logic.Pairwise /-! # Lattice operations on encodable types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ open Set namespace Encodable variable {α : Type _} {β : Type _} [Encodable β] /- warning: encodable.supr_decode₂ -> Encodable.supᵢ_decode₂ is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Encodable.{u2} β] [_inst_2 : CompleteLattice.{u1} α] (f : β -> α), Eq.{succ u1} α (supᵢ.{u1, 1} α (CompleteSemilatticeSup.toHasSup.{u1} α (CompleteLattice.toCompleteSemilatticeSup.{u1} α _inst_2)) Nat (fun (i : Nat) => supᵢ.{u1, succ u2} α (CompleteSemilatticeSup.toHasSup.{u1} α (CompleteLattice.toCompleteSemilatticeSup.{u1} α _inst_2)) β (fun (b : β) => supᵢ.{u1, 0} α (CompleteSemilatticeSup.toHasSup.{u1} α (CompleteLattice.toCompleteSemilatticeSup.{u1} α _inst_2)) (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) (fun (H : Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) => f b)))) (supᵢ.{u1, succ u2} α (CompleteSemilatticeSup.toHasSup.{u1} α (CompleteLattice.toCompleteSemilatticeSup.{u1} α _inst_2)) β (fun (b : β) => f b)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Encodable.{u1} β] [_inst_2 : CompleteLattice.{u2} α] (f : β -> α), Eq.{succ u2} α (supᵢ.{u2, 1} α (CompleteLattice.toSupSet.{u2} α _inst_2) Nat (fun (i : Nat) => supᵢ.{u2, succ u1} α (CompleteLattice.toSupSet.{u2} α _inst_2) β (fun (b : β) => supᵢ.{u2, 0} α (CompleteLattice.toSupSet.{u2} α _inst_2) (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) (fun (H : Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) => f b)))) (supᵢ.{u2, succ u1} α (CompleteLattice.toSupSet.{u2} α _inst_2) β (fun (b : β) => f b)) Case conversion may be inaccurate. Consider using '#align encodable.supr_decode₂ Encodable.supᵢ_decode₂ₓ'. -/ theorem supᵢ_decode₂ [CompleteLattice α] (f : β → α) : (⨆ (i : ℕ) (b ∈ decode₂ β i), f b) = ⨆ b, f b := by rw [supᵢ_comm] simp [mem_decode₂] #align encodable.supr_decode₂ Encodable.supᵢ_decode₂ /- warning: encodable.Union_decode₂ -> Encodable.unionᵢ_decode₂ is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Encodable.{u2} β] (f : β -> (Set.{u1} α)), Eq.{succ u1} (Set.{u1} α) (Set.unionᵢ.{u1, 1} α Nat (fun (i : Nat) => Set.unionᵢ.{u1, succ u2} α β (fun (b : β) => Set.unionᵢ.{u1, 0} α (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) (fun (H : Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) => f b)))) (Set.unionᵢ.{u1, succ u2} α β (fun (b : β) => f b)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Encodable.{u1} β] (f : β -> (Set.{u2} α)), Eq.{succ u2} (Set.{u2} α) (Set.unionᵢ.{u2, 1} α Nat (fun (i : Nat) => Set.unionᵢ.{u2, succ u1} α β (fun (b : β) => Set.unionᵢ.{u2, 0} α (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) (fun (H : Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) => f b)))) (Set.unionᵢ.{u2, succ u1} α β (fun (b : β) => f b)) Case conversion may be inaccurate. Consider using '#align encodable.Union_decode₂ Encodable.unionᵢ_decode₂ₓ'. -/ theorem unionᵢ_decode₂ (f : β → Set α) : (⋃ (i : ℕ) (b ∈ decode₂ β i), f b) = ⋃ b, f b := supᵢ_decode₂ f #align encodable.Union_decode₂ Encodable.unionᵢ_decode₂ /- warning: encodable.Union_decode₂_cases -> Encodable.unionᵢ_decode₂_cases is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Encodable.{u2} β] {f : β -> (Set.{u1} α)} {C : (Set.{u1} α) -> Prop}, (C (EmptyCollection.emptyCollection.{u1} (Set.{u1} α) (Set.hasEmptyc.{u1} α))) -> (forall (b : β), C (f b)) -> (forall {n : Nat}, C (Set.unionᵢ.{u1, succ u2} α β (fun (b : β) => Set.unionᵢ.{u1, 0} α (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 n)) (fun (H : Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 n)) => f b)))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Encodable.{u1} β] {f : β -> (Set.{u2} α)} {C : (Set.{u2} α) -> Prop}, (C (EmptyCollection.emptyCollection.{u2} (Set.{u2} α) (Set.instEmptyCollectionSet.{u2} α))) -> (forall (b : β), C (f b)) -> (forall {n : Nat}, C (Set.unionᵢ.{u2, succ u1} α β (fun (b : β) => Set.unionᵢ.{u2, 0} α (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 n)) (fun (H : Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 n)) => f b)))) Case conversion may be inaccurate. Consider using '#align encodable.Union_decode₂_cases Encodable.unionᵢ_decode₂_casesₓ'. -/ @[elab_as_elim] theorem unionᵢ_decode₂_cases {f : β → Set α} {C : Set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode₂ β n, f b) := match decode₂ β n with | none => by simp apply H0 | some b => by convert H1 b simp [ext_iff] #align encodable.Union_decode₂_cases Encodable.unionᵢ_decode₂_cases /- warning: encodable.Union_decode₂_disjoint_on -> Encodable.unionᵢ_decode₂_disjoint_on is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : Encodable.{u2} β] {f : β -> (Set.{u1} α)}, (Pairwise.{u2} β (Function.onFun.{succ u2, succ u1, 1} β (Set.{u1} α) Prop (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))) f)) -> (Pairwise.{0} Nat (Function.onFun.{1, succ u1, 1} Nat (Set.{u1} α) Prop (Disjoint.{u1} (Set.{u1} α) (CompleteSemilatticeInf.toPartialOrder.{u1} (Set.{u1} α) (CompleteLattice.toCompleteSemilatticeInf.{u1} (Set.{u1} α) (Order.Coframe.toCompleteLattice.{u1} (Set.{u1} α) (CompleteDistribLattice.toCoframe.{u1} (Set.{u1} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u1} (Set.{u1} α) (Set.completeBooleanAlgebra.{u1} α)))))) (GeneralizedBooleanAlgebra.toOrderBot.{u1} (Set.{u1} α) (BooleanAlgebra.toGeneralizedBooleanAlgebra.{u1} (Set.{u1} α) (Set.booleanAlgebra.{u1} α)))) (fun (i : Nat) => Set.unionᵢ.{u1, succ u2} α β (fun (b : β) => Set.unionᵢ.{u1, 0} α (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) (fun (H : Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Encodable.decode₂.{u2} β _inst_1 i)) => f b))))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Encodable.{u1} β] {f : β -> (Set.{u2} α)}, (Pairwise.{u1} β (Function.onFun.{succ u1, succ u2, 1} β (Set.{u2} α) Prop (Disjoint.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))) (BoundedOrder.toOrderBot.{u2} (Set.{u2} α) (Preorder.toLE.{u2} (Set.{u2} α) (PartialOrder.toPreorder.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))))) (CompleteLattice.toBoundedOrder.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α))))))) f)) -> (Pairwise.{0} Nat (Function.onFun.{1, succ u2, 1} Nat (Set.{u2} α) Prop (Disjoint.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))) (BoundedOrder.toOrderBot.{u2} (Set.{u2} α) (Preorder.toLE.{u2} (Set.{u2} α) (PartialOrder.toPreorder.{u2} (Set.{u2} α) (CompleteSemilatticeInf.toPartialOrder.{u2} (Set.{u2} α) (CompleteLattice.toCompleteSemilatticeInf.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α)))))))) (CompleteLattice.toBoundedOrder.{u2} (Set.{u2} α) (Order.Coframe.toCompleteLattice.{u2} (Set.{u2} α) (CompleteDistribLattice.toCoframe.{u2} (Set.{u2} α) (CompleteBooleanAlgebra.toCompleteDistribLattice.{u2} (Set.{u2} α) (Set.instCompleteBooleanAlgebraSet.{u2} α))))))) (fun (i : Nat) => Set.unionᵢ.{u2, succ u1} α β (fun (b : β) => Set.unionᵢ.{u2, 0} α (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) (fun (H : Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Encodable.decode₂.{u1} β _inst_1 i)) => f b))))) Case conversion may be inaccurate. Consider using '#align encodable.Union_decode₂_disjoint_on Encodable.unionᵢ_decode₂_disjoint_onₓ'. -/ theorem unionᵢ_decode₂_disjoint_on {f : β → Set α} (hd : Pairwise (Disjoint on f)) : Pairwise (Disjoint on fun i => ⋃ b ∈ decode₂ β i, f b) := by rintro i j ij refine' disjoint_left.mpr fun x => _ suffices ∀ a, encode a = i → x ∈ f a → ∀ b, encode b = j → x ∉ f b by simpa [decode₂_eq_some] rintro a rfl ha b rfl hb exact (hd (mt (congr_arg encode) ij)).le_bot ⟨ha, hb⟩ #align encodable.Union_decode₂_disjoint_on Encodable.unionᵢ_decode₂_disjoint_on end Encodable
[STATEMENT] lemma rel_interior_scaleR: fixes S :: "'n::euclidean_space set" assumes "c \<noteq> 0" shows "((*\<^sub>R) c) ` (rel_interior S) = rel_interior (((*\<^sub>R) c) ` S)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (*\<^sub>R) c ` rel_interior S = rel_interior ((*\<^sub>R) c ` S) [PROOF STEP] using rel_interior_injective_linear_image[of "((*\<^sub>R) c)" S] linear_conv_bounded_linear[of "(*\<^sub>R) c"] linear_scaleR injective_scaleR[of c] assms [PROOF STATE] proof (prove) using this: \<lbrakk>bounded_linear ((*\<^sub>R) c); inj ((*\<^sub>R) c)\<rbrakk> \<Longrightarrow> rel_interior ((*\<^sub>R) c ` S) = (*\<^sub>R) c ` rel_interior S linear ((*\<^sub>R) c) = bounded_linear ((*\<^sub>R) c) linear ((*\<^sub>R) ?c) c \<noteq> 0 \<Longrightarrow> inj ((*\<^sub>R) c) c \<noteq> 0 goal (1 subgoal): 1. (*\<^sub>R) c ` rel_interior S = rel_interior ((*\<^sub>R) c ` S) [PROOF STEP] by auto
lemma bij_betw_nth_root_unity: fixes c :: complex and n :: nat assumes c: "c \<noteq> 0" and n: "n > 0" defines "c' \<equiv> root n (norm c) * cis (arg c / n)" shows "bij_betw (\<lambda>z. c' * z) {z. z ^ n = 1} {z. z ^ n = c}"
import Data.Vect append_nil : Vect m elem -> Vect (plus m 0) elem append_nil {m} xs = rewrite plusZeroRightNeutral m in xs append_xs : Vect (S (m + k)) elem -> Vect (plus m (S k)) elem append_xs {m} {k} xs = rewrite sym (plusSuccRightSucc m k) in xs append : Vect n elem -> Vect m elem -> Vect (m + n) elem append [] ys = append_nil ys append (x :: xs) ys = append_xs (x :: append xs ys)
Require Import Crypto.Specific.Framework.RawCurveParameters. Require Import Crypto.Util.LetIn. (*** Modulus : 2^384 - 2^128 - 2^96 + 2^32 - 1 Base: 38.4 ***) Definition curve : CurveParameters := {| sz := 10%nat; base := 38 + 2/5; bitwidth := 64; s := 2^384; c := [(1, 1); (2^32, -1); (2^96, 1); (2^128, 1)]; carry_chains := Some [[2; 1; 9; 9]; [3; 2; 0; 4; 1; 5; 6; 7; 8; 9]; [3; 2; 0; 0]]%nat; a24 := None; coef_div_modulus := Some 2%nat; goldilocks := None; karatsuba := None; montgomery := false; freeze := Some true; ladderstep := false; mul_code := None; square_code := None; upper_bound_of_exponent_loose := None; upper_bound_of_exponent_tight := None; allowable_bit_widths := None; freeze_extra_allowable_bit_widths := None; modinv_fuel := None |}. Ltac extra_prove_mul_eq _ := idtac. Ltac extra_prove_square_eq _ := idtac.
here some maps we find super nice and inspirational! > how people live: spanish source, but international visuals! > 14 literary maps to explore: when words become drawings, that’s magic! > stop-motion made using paper maps by piers faccini: so cool! > geological maps, planets and our solar system: colorful! > hand drawn map association: a lot of drawers for a lot of maps! > radicalcartography: a huge collection! if you want discover more you can check our own repository of maps on pinterest with a lot of nice and amazing maps! Comments Off on maps, maps and maps! here, a list of some image sources we found for you. if you know any other good ones, please share them with us in the arena “tagging” Miri Esther, our responsible for keeping this list up-to-date! > the commons (on flickr): from the world’s public photography archives. > retronaut’s time capsules: see the past like you wouldn’t believe. > the new york public library: digitalized original images from books, magazines and newspapers, mostly created before 1923. > medieval and renaissance material culture: occupations, clothing, animals, tools, utensils, games, pastimes, crime, punishment… from the middle ages + renaissance! > google art project: artworks, high-res + walk-through museums feature! > world wonders project: explore historic sites as if you were there. > historic moments: stories behind significant moments in human history. > pixabay.com: free high res images, free videos as well! > morguefile.com: high res stock photos by creatives for creatives! > foter.com: free for non commercial use. “buildings” section is great. > everystockphoto.com: a serch engine for free images or wirth a specific licence. > im creator: some free, some not, but worth it! #arc1o1exhibition goes to ural industrial biennial of contemporary art! curator yana novoslugina for welcoming our matchboxes in such a beautifully curated way. another very special thank you to our crew member dina neri for organizing the collaboration with okno gallery. Comments Off on #arc1o1exhibition goes to ural industrial biennial of contemporary art! we publish some as well! in collages we really trust! you like to write ?
\section{Conclusion} This paper presents the design and implementation of a distributed broker that implements continuous query-based syndication over richly-defined streams. The CQBS broker, which is implemented in Go, offers more expressive power while remaining tractable to implement on embedded, constrained clients typical of the Internet of Things. CQBS strikes a middle ground between the fast but restricted descriptive power of topic-based pub-sub systems and the rich descriptive power but heavyweight nature of content-based pub-sub. On top of this, we demonstrate how the system can be made highly available using a logically-centralized replicated coordinator to maintain consistency between distributed brokers.
\chapter*{Abstract} \label{abstract} The ability to learn and remember many different tasks is crucial for artificial intelligence. Neural networks are not capable of this. They suffer from catastrophic forgetting. Prior research in the domain of incremental or continual learning shows different approaches, such as Elastic Weight Consolidation \cite{elastic-weight-consolidation} or Incremental Moment Matching \cite{incremental-moment-matching}. Some approaches rely on the computation of a so called Fisher information matrix. The Fisher information matrix shows rather promising results, but relies on a diagonal assumption and the context of Bayesian neural networks. Furthermore, the implementation of the Fisher information matrix in the machine learning framework Tensorflow requires a workaround that greatly increases memory consumtion. \newline This article proposes a new way of calculating a matrix that replaces the Fisher information matrix. It is computed similar as the Fisher information matrix, but does not requirde additional assumptions. Moreover, this matrix enables an easy computation in the Tensorflow framework. The article documents several benchmarks of an own reimplementation of the Elastic Weight Consolidation \cite{elastic-weight-consolidation} algorithm and the adoption of the new matrix.
这 7人 中包括 来自 法国 的 宇航 员 .
Set Implicit Arguments. Require Import Common.Types. Require Import Coq.Lists.List. Require Import Network.NetworkPacket. Require Import Word.WordInterface. Require Import Pattern.Pattern. Local Open Scope list_scope. Definition Classifier (A : Type) := list (pattern * A) %type. Fixpoint scan {A : Type} (default : A) (classifier : Classifier A) (pt : portId) (pk : packet) := match classifier with | nil => default | (pat,a) :: rest => match Pattern.match_packet pt pk pat with | true => a | false => scan default rest pt pk end end. Definition inter_entry {A : Type} {B : Type} (f : A -> A -> B) (cl : Classifier A) (v : pattern * A) := let (pat, act) := v in fold_right (fun (v' : pattern * A) acc => let (pat', act') := v' in (Pattern.inter pat pat', f act act') :: acc) nil cl. Definition inter {A : Type} {B : Type} (f : A -> A -> B) (cl1 cl2 : Classifier A) := fold_right (fun v acc => inter_entry f cl2 v ++ acc) nil cl1. Definition union {A : Type} (f : A -> A -> A) (cl1 cl2 : Classifier A) := inter f cl1 cl2 ++ cl1 ++ cl2. (** Why so baroque? Filtering the tail of the list is not structurally recursive. *) Fixpoint elim_shadowed_helper {A : Type} (prefix : Classifier A) (cf : Classifier A) := match cf with | nil => prefix | (pat,act) :: cf' => match existsb (fun (entry : pattern * A) => let (pat', act) := entry in if Pattern.beq pat pat' then true else false) prefix with | true => elim_shadowed_helper prefix cf' | false => elim_shadowed_helper (prefix ++ [(pat,act)]) cf' end end. Definition elim_shadowed {A : Type} (cf : Classifier A) := elim_shadowed_helper nil cf. Fixpoint prioritize {A : Type} (prio : nat) (lst : Classifier A) : list (nat * pattern *A) := match lst with | nil => nil | (pat, act) :: lst' => (prio, pat, act) :: (prioritize (pred prio) lst') end.
Formal statement is: lemma contour_integral_primitive: assumes "\<And>x. x \<in> S \<Longrightarrow> (f has_field_derivative f' x) (at x within S)" and "valid_path g" "path_image g \<subseteq> S" shows "(f' has_contour_integral (f(pathfinish g) - f(pathstart g))) g" Informal statement is: If $f$ is differentiable on a set $S$ and $g$ is a path in $S$, then $\int_g f' = f(b) - f(a)$, where $a$ and $b$ are the endpoints of $g$.
module Props.Char import Data.List import public Props.Util %access public export digits : List Char digits = ['0'..'9'] lowerCase : List Char lowerCase = ['a'..'z'] upperCase : List Char upperCase = ['A'..'Z'] letters : List Char letters = lowerCase ++ upperCase whiteSpace : List Char whiteSpace = ['\n','\t',' '] Digit : Char -> Type Digit c = Elem c digits LowerCase : Char -> Type LowerCase c = Elem c lowerCase UpperCase : Char -> Type UpperCase c = Elem c upperCase Whitespace : Char -> Type Whitespace c = Elem c whiteSpace Letter : (c:Char) -> Type Letter = EitherK LowerCase UpperCase AlphaNumeric : Char -> Type AlphaNumeric = EitherK Letter Digit
""" $(SIGNATURES) returns the genotype data. Will skip every other column because genotype probability is duplicated. """ function get_geno_data(file, datatype) geno_prob = convert(Array{datatype,2},readdlm(file, ','; skipstart=1)) return geno_prob[:,1:2:end] end # function try_string2num(num) # return tryparse(Float64,num) != nothing # end """ $(SIGNATURES) returns the phenotype data. If transposed=true, then the data will be transposed. """ function get_pheno_data(file, datatype; transposed=true) #first column is individual ID such as : BXD1 , need to be removed. pheno = readdlm(file, ','; skipstart=1)[:, 2:end] if pheno[1,end] == "f" || pheno[1,end] == "m" @info "Removing sex column of phenotype. " pheno = pheno[:, 1:end-1] end pheno = convert(Array{datatype,2}, pheno) if transposed return transpose(pheno) |> collect else return pheno end end """ $(SIGNATURES) Filter genotype data with a minor allele frequency threshold. # Arguments - `genotype` : genotype matrix - `maf_threshold` : default value is 0.05. # Output: returns filtered genotype matrix. """ function filter_maf(genotype::Array{<:Real, 2}; maf_threshold=0.05) alleles = 2 af = sum(genotype, dims=1) ./ (alleles * size(genotype, 1)) maf = replace(x -> x > 0.5 ? 1-x : x, af) if maf_threshold > 0 mask = vec(maf .>= maf_threshold) if size(mask,1) != size(genotype, 2) error("Mask dimention does not match original matrix. Mask size: $(size(mask)), Matrix size: $(size(genotype))") end newgenotype = genotype[:, mask] end return newgenotype end
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: GPL-2.0-only *) theory ExampleSystem imports ArchAccess_AC begin context begin interpretation Arch . (*FIXME: arch_split*) definition nat_to_bl :: "nat \<Rightarrow> nat \<Rightarrow> bool list option" where "nat_to_bl bits n \<equiv> if n \<ge> 2^bits then None else Some $ bin_to_bl bits (of_nat n)" lemma nat_to_bl_id [simp]: "nat_to_bl (size (x :: (('a::len) word))) (unat x) = Some (to_bl x)" apply (clarsimp simp: nat_to_bl_def to_bl_def) apply (auto simp: le_def word_size) done (*---------------------------------------------------------*) subsection \<open>Purpose\<close> text \<open> This file defines some example systems using the access control definitions. The aim is a sanity check of the AC definitions, to ensure they enable to reason about reasonable systems. In particular, we want to make sure that . the function state_objs_to_policy does not connect everything to everything (Example 1) . we can talk about components sharing cnodes . we can talk about components sharing frames . we can have more than 1 untrusted component . we can have an EP between two untrusted components \<close> (*---------------------------------------------------------*) subsection \<open>Generic functions / lemmas\<close> text \<open>Defining the authority between labels. In addition to the intuitive authority we want, we need to add all the authority required to have a wellformed graph. So we define complete_AgentAuthGraph to add these 'extra' authorities (at least all the ones not depending on the current label). These are: . self-authority (each label needs all the authorities to itself). . if Control edge is present between 2 labels then we add all authorities between them. . Control authority is transitive: we add an Control edge between 2 labels if we can connect them via Control edges. Actually we add all authorities because of the second clause. \<close> definition complete_AuthGraph :: "'a auth_graph \<Rightarrow> 'a set \<Rightarrow> 'a auth_graph" where "complete_AuthGraph g ls \<equiv> g \<union> {(l,a,l) | a l. l \<in> ls}" text \<open>converting a nat to a bool list of size 10 - for the cnodes\<close> definition the_nat_to_bl :: "nat \<Rightarrow> nat \<Rightarrow> bool list" where "the_nat_to_bl sz n \<equiv> the (nat_to_bl sz n)" definition the_nat_to_bl_10 :: "nat \<Rightarrow> bool list" where "the_nat_to_bl_10 n \<equiv> the_nat_to_bl 10 n" lemma tcb_cnode_index_nat_to_bl: "n<10 \<Longrightarrow> the_nat_to_bl_10 n \<noteq> tcb_cnode_index n" by (clarsimp simp: the_nat_to_bl_10_def the_nat_to_bl_def tcb_cnode_index_def nat_to_bl_def to_bl_def bin_to_bl_aux_def) (*---------------------------------------------------------*) subsection \<open>Example 1\<close> text \<open> This example aims at checking that we can extract a reasonable policy from the state, i.e. that the function state_objs_to_policy does not connect everything to everything. This example is a system Sys1 made of 2 main components UT1 and T1, connected through and endpoint EP1. EP1 is made of one single kernel object: obj1_0x9, the endpoint. Both UT1 and T1 contains: . one TCB (obj1_0xC07 and obj1_0xC08 resp.) . one vspace made up of one top-level page table (obj1_BF7 and obj1_0xBF9 resp.) . each top-level pt contains a single page table (obj1_0xC00000 and obj1_0xC05000 resp.) . one cspace made up of one cnode (obj1_0x6 and obj1_0x7 resp.) . each cspace contains 4 caps: one to the tcb one to the cnode itself one to the vspace one to the ep UT1 can send to the ep while T1 can receive from it. Attempt to ASCII art: -------- ---- ---- -------- | | | | | | | | V | | V S R | V | V obj1_0xC07(tcb)-->obj1_0x6(cnode)--->obj1_0x9(ep)<---obj1_0x7(cnode)<--obj1_0xC08(tcb) | | | | V | | V obj1_0xBF7(pt)<----- -------> obj1_0xBF9(pt) | | V V obj1_0xC00000(pt) obj1_0xC05000(pt) (the references are derived from the dump of the SAC system) The aim is to be able to prove pas_refined Sys1PAS s1 where Sys1PAS is the label graph defining the AC policy for Sys1 and s1 is the state of Sys1 described above. This shows that the aag extracted from s1 (by state_objs_to_policy) is included in the policy graph Sys1PAS. \<close> subsubsection \<open>Defining the State\<close> text \<open>We need to define the asids of each pt to ensure that the object is included in the right ASID-label\<close> text \<open>UT1's ASID\<close> definition asid1_0xBF7 :: asid where "asid1_0xBF7 \<equiv> 1<<asid_low_bits" text \<open>T1's ASID\<close> definition asid1_0xBF9 :: asid where "asid1_0xBF9 \<equiv> 2<<asid_low_bits" lemma "asid_high_bits_of asid1_0xBF9 \<noteq> asid_high_bits_of asid1_0xBF7" by (simp add: asid1_0xBF7_def asid_high_bits_of_def asid1_0xBF9_def asid_low_bits_def) text \<open>UT1's CSpace\<close> definition caps1_0x6 :: cnode_contents where "caps1_0x6 \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap 0xC07, (the_nat_to_bl_10 2) \<mapsto> CNodeCap 6 undefined undefined, (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageTableCap 0xBF7 (Some (asid1_0xBF7,0))), (the_nat_to_bl_10 318) \<mapsto> EndpointCap 9 0 {AllowSend} )" definition obj1_0x6 :: kernel_object where "obj1_0x6 \<equiv> CNode 10 caps1_0x6" text \<open>T1's Cspace\<close> definition caps1_0x7 :: cnode_contents where "caps1_0x7 \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap 0xC08, (the_nat_to_bl_10 2) \<mapsto> CNodeCap 7 undefined undefined, (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageTableCap 0xBF9 (Some (asid1_0xBF9,0))), (the_nat_to_bl_10 318) \<mapsto> EndpointCap 9 0 {AllowRecv}) " definition obj1_0x7 :: kernel_object where "obj1_0x7 \<equiv> CNode 10 caps1_0x7" text \<open>endpoint between UT1 and T1\<close> definition obj1_0x9 :: kernel_object where "obj1_0x9 \<equiv> Endpoint IdleEP" text \<open>UT1's VSpace\<close> definition pt1_0xC00000 :: pt where "pt1_0xC00000 \<equiv> (\<lambda>_. InvalidPTE)" definition obj1_0xC00000 :: kernel_object where "obj1_0xC00000 \<equiv> ArchObj (PageTable pt1_0xC00000)" definition pt1_0xBF7 :: pt where "pt1_0xBF7 \<equiv> (\<lambda>_. InvalidPTE) (0 := PageTablePTE (ucast (addrFromPPtr 0xC00000 >> pageBits)) undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition obj1_0xBF7 :: kernel_object where "obj1_0xBF7 \<equiv> ArchObj (PageTable pt1_0xBF7)" text \<open>T1's VSpace\<close> definition pt1_0xC05000 :: pt where "pt1_0xC05000 \<equiv> (\<lambda>_. InvalidPTE)" definition obj1_0xC05000 :: kernel_object where "obj1_0xC05000 \<equiv> ArchObj (PageTable pt1_0xC05000)" definition pt1_0xBF9 :: pt where "pt1_0xBF9 \<equiv> (\<lambda>_. InvalidPTE) (0 := PageTablePTE (ucast (addrFromPPtr 0xC05000 >> pageBits)) undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition obj1_0xBF9 :: kernel_object where "obj1_0xBF9 \<equiv> ArchObj (PageTable pt1_0xBF9)" text \<open>UT1's tcb\<close> definition obj1_0xC07 :: kernel_object where "obj1_0xC07 \<equiv> TCB \<lparr> tcb_ctable = CNodeCap 6 undefined undefined, tcb_vtable = ArchObjectCap (PageTableCap 0xBF7 (Some (asid1_0xBF7, 0))), tcb_reply = ReplyCap 0xC07 True {AllowGrant,AllowWrite}, \<comment> \<open>master reply cap to itself\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = Running, tcb_fault_handler = undefined, tcb_ipc_buffer = undefined, tcb_fault = undefined, tcb_bound_notification = None, tcb_mcpriority = undefined, tcb_arch = \<lparr>tcb_context = undefined\<rparr> \<rparr>" text \<open>T1's tcb\<close> definition obj1_0xC08 :: kernel_object where "obj1_0xC08 \<equiv> TCB \<lparr> tcb_ctable = CNodeCap 7 undefined undefined, tcb_vtable = ArchObjectCap (PageTableCap 0xBF9 (Some (asid1_0xBF9, 0))), tcb_reply = ReplyCap 0xC08 True {AllowGrant,AllowWrite}, \<comment> \<open>master reply cap to itself\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = BlockedOnReceive 9 \<lparr> receiver_can_grant = False \<rparr>, tcb_fault_handler = undefined, tcb_ipc_buffer = undefined, tcb_fault = undefined, tcb_bound_notification = None, tcb_mcpriority = undefined, tcb_arch = \<lparr>tcb_context = undefined\<rparr>\<rparr>" definition "obj1_10 \<equiv> CNode 10 (Map.empty([] \<mapsto> cap.NullCap))" (* the boolean in BlockedOnReceive is True if the object can receive but not send. but Tom says it only matters if the sender can grant - which is not the case of the UT1 - I think *) definition kh1 :: kheap where "kh1 \<equiv> [0x6 \<mapsto> obj1_0x6, 0x7 \<mapsto> obj1_0x7, 0x9 \<mapsto> obj1_0x9, 0xA \<mapsto> obj1_10, 0xBF7 \<mapsto> obj1_0xBF7, 0xBF9 \<mapsto> obj1_0xBF9, 0xC07 \<mapsto> obj1_0xC07, 0xC08 \<mapsto> obj1_0xC08, 0xC00000 \<mapsto> obj1_0xC00000, 0xC05000 \<mapsto> obj1_0xC05000]" lemmas kh1_obj_def = obj1_0x6_def obj1_0x7_def obj1_0x9_def obj1_10_def obj1_0xBF7_def obj1_0xBF9_def obj1_0xC00000_def obj1_0xC05000_def obj1_0xC07_def obj1_0xC08_def definition exst1 :: "det_ext" where "exst1 \<equiv> \<lparr>work_units_completed_internal = undefined, scheduler_action_internal = undefined, ekheap_internal = \<lambda>x. None, domain_list_internal = undefined, domain_index_internal = undefined, cur_domain_internal = undefined, domain_time_internal = undefined, ready_queues_internal = undefined, cdt_list_internal = undefined\<rparr>" definition s1 :: "det_ext state" where "s1 \<equiv> \<lparr> kheap = kh1, cdt = Map.empty, is_original_cap = undefined, cur_thread = undefined, idle_thread = undefined, machine_state = undefined, interrupt_irq_node = (\<lambda>_. 10), interrupt_states = undefined, arch_state = \<lparr> riscv_asid_table = (\<lambda>_. None), riscv_global_pts = undefined, riscv_kernel_vspace = undefined \<rparr>, exst = exst1 \<rparr>" subsubsection \<open>Defining the policy graph\<close> datatype Sys1Labels = UT1 | T1 | EP1 | IRQ1 definition Sys1AgentMap :: "Sys1Labels agent_map" where "Sys1AgentMap \<equiv> (\<lambda>_. undefined) (0x6 := UT1, 0x7 := T1, 0x9 := EP1, 0xA := IRQ1, 0xBF7 := UT1, 0xBF9 := T1, 0xC00000 := UT1, 0xC05000 := T1, 0xC07 := UT1, 0xC08 := T1 )" lemma Sys1AgentMap_simps: "Sys1AgentMap 0x6 = UT1" "Sys1AgentMap 0x7 = T1" "Sys1AgentMap 0x9 = EP1" "Sys1AgentMap 0xA = IRQ1" "Sys1AgentMap 0xBF7 = UT1" "Sys1AgentMap 0xBF9 = T1" "Sys1AgentMap 0xC00000 = UT1" "Sys1AgentMap 0xC05000 = T1" "Sys1AgentMap 0xC07 = UT1" "Sys1AgentMap 0xC08 = T1" unfolding Sys1AgentMap_def by simp_all definition Sys1AuthGraph_aux :: "Sys1Labels auth_graph" where "Sys1AuthGraph_aux \<equiv> { (UT1, auth.SyncSend, EP1), (UT1, auth.Reset, EP1), (T1, auth.Receive, EP1), (T1, auth.Reset, EP1) }" definition Sys1AuthGraph:: "Sys1Labels auth_graph" where "Sys1AuthGraph \<equiv> complete_AuthGraph Sys1AuthGraph_aux {T1, UT1}" definition Sys1ASIDMap :: "Sys1Labels agent_asid_map" where "Sys1ASIDMap \<equiv> (\<lambda>x. if (asid_high_bits_of x = asid_high_bits_of asid1_0xBF7) then UT1 else if (asid_high_bits_of x = asid_high_bits_of asid1_0xBF9) then T1 else undefined)" definition Sys1PAS :: "Sys1Labels PAS" where "Sys1PAS \<equiv> \<lparr> pasObjectAbs = Sys1AgentMap, pasASIDAbs = Sys1ASIDMap, pasIRQAbs = (\<lambda>_. IRQ1), pasPolicy = Sys1AuthGraph, pasSubject = UT1, pasMayActivate = True, pasMayEditReadyQueues = True, pasMaySendIrqs = True, pasDomainAbs = undefined \<rparr>" subsubsection \<open>Proof of pas_refined for Sys1\<close> lemma caps1_0x7_well_formed: "well_formed_cnode_n 10 caps1_0x7" apply (clarsimp simp: caps1_0x7_def well_formed_cnode_n_def) apply (clarsimp simp: the_nat_to_bl_10_def the_nat_to_bl_def nat_to_bl_def) apply (clarsimp simp: empty_cnode_def dom_def) apply (rule set_eqI, clarsimp) apply (rule iffI) apply (elim disjE, insert len_bin_to_bl, simp_all)[1] apply clarsimp done lemma caps1_0x6_well_formed: "well_formed_cnode_n 10 caps1_0x6" apply (clarsimp simp: caps1_0x6_def well_formed_cnode_n_def) apply (clarsimp simp: the_nat_to_bl_10_def the_nat_to_bl_def nat_to_bl_def) apply (clarsimp simp: empty_cnode_def dom_def) apply (rule set_eqI, clarsimp) apply (rule iffI) apply (elim disjE, insert len_bin_to_bl, simp_all)[1] apply clarsimp done (* clagged from KernelInit_R *) lemma empty_cnode_apply[simp]: "(empty_cnode n xs = Some cap) = (length xs = n \<and> cap = NullCap)" by (auto simp add: empty_cnode_def) lemma s1_caps_of_state : "caps_of_state s1 p = Some cap \<Longrightarrow> cap = NullCap \<or> (p,cap) \<in> { ((6::obj_ref,(the_nat_to_bl_10 1)), ThreadCap 0xC07), ((6::obj_ref,(the_nat_to_bl_10 2)), CNodeCap 6 undefined undefined), ((6::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageTableCap 0xBF7 (Some (asid1_0xBF7, 0)))), ((6::obj_ref,(the_nat_to_bl_10 318)),EndpointCap 9 0 {AllowSend}), ((7::obj_ref,(the_nat_to_bl_10 1)), ThreadCap 0xC08), ((7::obj_ref,(the_nat_to_bl_10 2)), CNodeCap 7 undefined undefined), ((7::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageTableCap 0xBF9 (Some (asid1_0xBF9, 0)))), ((7::obj_ref,(the_nat_to_bl_10 318)),EndpointCap 9 0 {AllowRecv}) , ((0xC07::obj_ref, (tcb_cnode_index 0)), CNodeCap 6 undefined undefined ), ((0xC07::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageTableCap 0xBF7 (Some (asid1_0xBF7, 0)))), ((0xC07::obj_ref, (tcb_cnode_index 2)), ReplyCap 0xC07 True {AllowGrant,AllowWrite}), ((0xC07::obj_ref, (tcb_cnode_index 3)), NullCap), ((0xC07::obj_ref, (tcb_cnode_index 4)), NullCap), ((0xC08::obj_ref, (tcb_cnode_index 0)), CNodeCap 7 undefined undefined ), ((0xC08::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageTableCap 0xBF9 (Some (asid1_0xBF9, 0)))), ((0xC08::obj_ref, (tcb_cnode_index 2)), ReplyCap 0xC08 True {AllowGrant,AllowWrite}), ((0xC08::obj_ref, (tcb_cnode_index 3)), NullCap), ((0xC08::obj_ref, (tcb_cnode_index 4)), NullCap)} " apply (insert caps1_0x7_well_formed) apply (insert caps1_0x6_well_formed) apply (simp add: caps_of_state_cte_wp_at cte_wp_at_cases s1_def kh1_def kh1_obj_def) apply (case_tac p, clarsimp) apply (clarsimp split: if_splits) apply (clarsimp simp: cte_wp_at_cases tcb_cap_cases_def split: if_split_asm)+ apply (clarsimp simp: caps1_0x7_def split: if_splits) apply (clarsimp simp: caps1_0x6_def cte_wp_at_cases split: if_splits) done lemma Sys1_wellformed: "pas_wellformed Sys1PAS" apply (clarsimp simp: Sys1PAS_def policy_wellformed_def Sys1AuthGraph_def Sys1AuthGraph_aux_def complete_AuthGraph_def) apply blast done lemma tcb_states_of_state_1: "tcb_states_of_state s1 = [0xC08 \<mapsto> thread_state.BlockedOnReceive 9 \<lparr> receiver_can_grant = False \<rparr>, 0xC07 \<mapsto> thread_state.Running ]" unfolding s1_def tcb_states_of_state_def apply (rule ext) apply (simp add: get_tcb_def) apply (simp add: kh1_def kh1_obj_def ) done lemma thread_bound_ntfns_1: "thread_bound_ntfns s1 = Map.empty" unfolding s1_def thread_bound_ntfns_def apply (rule ext) apply (simp add: get_tcb_def) apply (simp add: kh1_def kh1_obj_def ) done declare AllowSend_def[simp] AllowRecv_def[simp] lemma domains_of_state_s1[simp]: "domains_of_state s1 = {}" apply (rule equalityI) apply (rule subsetI) apply clarsimp apply (erule domains_of_state_aux.induct) apply (simp add: s1_def exst1_def) apply simp done lemma vs_refs_aux_empty_pt[simp]: "vs_refs_aux lvl (PageTable empty_pt) = {}" by (clarsimp simp: vs_refs_aux_def graph_of_def pte_ref2_def) lemma is_aligned_0xC00000[simp]: "ptrFromPAddr (addr_from_ppn (UCAST(64 \<rightarrow> 52) (addrFromPPtr 0xC00000 >> pageBits))) = 0xC00000" by (subst ptrFromPAddr_addr_from_ppn; fastforce simp: bit_simps is_aligned_mask mask_def) lemma is_aligned_0xC05000[simp]: "ptrFromPAddr (addr_from_ppn (UCAST(64 \<rightarrow> 52) (addrFromPPtr 0xC05000 >> pageBits))) = 0xC05000" by (subst ptrFromPAddr_addr_from_ppn; fastforce simp: bit_simps is_aligned_mask mask_def) lemma "pas_refined Sys1PAS s1" apply (clarsimp simp: pas_refined_def) apply (intro conjI) subgoal by (simp add: Sys1_wellformed) subgoal by (simp add: irq_map_wellformed_aux_def s1_def Sys1AgentMap_simps Sys1PAS_def) subgoal by (simp add: tcb_domain_map_wellformed_aux_def) apply (clarsimp simp: auth_graph_map_def Sys1PAS_def state_objs_to_policy_def)+ apply (erule state_bits_to_policy.cases, simp_all, clarsimp) apply (drule s1_caps_of_state, clarsimp) apply (simp add: Sys1AuthGraph_def complete_AuthGraph_def Sys1AuthGraph_aux_def) apply (elim disjE conjE; solves\<open>clarsimp simp: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def\<close>) apply (drule s1_caps_of_state, clarsimp) apply (elim disjE; solves \<open>simp add: thread_bound_ntfns_def\<close>) apply (clarsimp simp: state_refs_of_def thread_st_auth_def tcb_states_of_state_1 Sys1AuthGraph_def Sys1AgentMap_simps complete_AuthGraph_def Sys1AuthGraph_aux_def split: if_splits) apply (simp add: thread_bound_ntfns_1) apply (simp add: s1_def) (* this is OK because cdt is empty..*) apply (simp add: s1_def) (* this is OK because cdt is empty..*) apply (fastforce simp: state_vrefs_def vs_refs_aux_def s1_def kh1_def kh1_obj_def pt1_0xC00000_def pt1_0xC05000_def pt1_0xBF9_def pt1_0xBF7_def Sys1AuthGraph_def Sys1AuthGraph_aux_def Sys1AgentMap_simps complete_AuthGraph_def ptr_range_def pte_ref2_def opt_map_def dest!: graph_ofD split: if_splits) apply (rule subsetI, clarsimp) apply (erule state_asids_to_policy_aux.cases) apply (drule s1_caps_of_state, clarsimp) apply (fastforce simp: Sys1AgentMap_simps Sys1PAS_def Sys1ASIDMap_def Sys1AuthGraph_def Sys1AuthGraph_aux_def complete_AuthGraph_def cap_auth_conferred_def asid1_0xBF9_def asid1_0xBF7_def asid_low_bits_def asid_high_bits_of_def) apply (fastforce simp: state_vrefs_def vs_refs_aux_def s1_def kh1_def kh1_obj_def pt1_0xC00000_def pt1_0xC05000_def pt1_0xBF9_def pt1_0xBF7_def Sys1AuthGraph_def Sys1AuthGraph_aux_def Sys1AgentMap_simps complete_AuthGraph_def ptr_range_def pte_ref2_def opt_map_def dest!: graph_ofD split: if_splits) apply (clarsimp simp: s1_def) apply (rule subsetI, clarsimp) apply (erule state_irqs_to_policy_aux.cases) apply (simp add: Sys1AuthGraph_def complete_AuthGraph_def Sys1AuthGraph_aux_def Sys1PAS_def Sys1ASIDMap_def) apply (drule s1_caps_of_state) apply (fastforce simp: Sys1AgentMap_simps Sys1PAS_def Sys1ASIDMap_def Sys1AuthGraph_def Sys1AuthGraph_aux_def complete_AuthGraph_def cap_auth_conferred_def asid1_0xBF9_def asid1_0xBF7_def asid_low_bits_def asid_high_bits_of_def) done (*---------------------------------------------------------*) subsection \<open>Example 2\<close> text \<open> This example systems Sys2 aims at checking that we can have 2 components, one untrusted UT2 and one truted T1, sharing a cnode obj2_5. Both UT2 and T2 contains: . one TCB (obj2_0xC07 and obj2_0xC08 resp.) . one vspace made up of one top-level page table (obj2_0xBF7 and obj2_0xBF9 resp.) . each top-level pt contains a single page table (obj2_0xC00000 and obj2_0xC05000 resp.) . one cspace made up of one cnode (obj2_0x6 and obj2_0x7 resp.) . each cspace contains 4 caps: one to the tcb one to the cnode itself one to the vspace one to obj2_5 Attempt to ASCII art: -------- ---- ---- -------- | | | | | | | | V | | V S R | V | V obj2_0xC07(tcb)-->obj2_0x6(cnode)--->obj2_5(cnode)<---obj2_0x7(cnode)<--obj2_0xC08(tcb) | | | | V | | V obj2_0xBF7(pt)<----- -------> obj2_0xBF9(pt) | | V V obj2_0xC00000(pt) obj2_0xC05000(pt) (the references are derived from the dump of the SAC system) The aim is to be able to prove pas_refined Sys2PAS s2 where Sys2PAS is the label graph defining the AC policy for Sys2 and s2 is the state of Sys2 described above. This shows that the aag extracted from s2 (by state_objs_to_policy) is included in the policy graph Sys2PAS. \<close> subsubsection \<open>Defining the State\<close> text \<open>We need to define the asids of each pt to ensure that the object is included in the right ASID-label\<close> text \<open>UT2's ASID\<close> definition asid2_0xBF7 :: asid where "asid2_0xBF7 \<equiv> 1<<asid_low_bits" text \<open>T2's ASID\<close> definition asid2_0xBF9 :: asid where "asid2_0xBF9 \<equiv> 2<<asid_low_bits" lemma "asid_high_bits_of asid2_0xBF9 \<noteq> asid_high_bits_of asid2_0xBF7" by (simp add: asid2_0xBF7_def asid_high_bits_of_def asid2_0xBF9_def asid_low_bits_def) text \<open>the intermediaite CSpace\<close> definition caps2_5 :: cnode_contents where "caps2_5 \<equiv> (empty_cnode 10)" definition obj2_5 :: kernel_object where "obj2_5 \<equiv> CNode 10 caps2_5" text \<open>UT2's CSpace\<close> definition caps2_0x6 :: cnode_contents where "caps2_0x6 \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap 0xC07, (the_nat_to_bl_10 2) \<mapsto> CNodeCap 6 undefined undefined, (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageTableCap 0xBF7 (Some (asid2_0xBF7, 0))), (the_nat_to_bl_10 4) \<mapsto> CNodeCap 5 undefined undefined )" definition obj2_0x6 :: kernel_object where "obj2_0x6 \<equiv> CNode 10 caps2_0x6" text \<open>T2's Cspace\<close> definition caps2_0x7 :: cnode_contents where "caps2_0x7 \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap 0xC08, (the_nat_to_bl_10 2) \<mapsto> CNodeCap 7 undefined undefined, (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageTableCap 0xBF9 (Some (asid2_0xBF9, 0))), (the_nat_to_bl_10 4) \<mapsto> CNodeCap 5 undefined undefined) " definition obj2_0x7 :: kernel_object where "obj2_0x7 \<equiv> CNode 10 caps2_0x7" text \<open>endpoint between UT2 and T2\<close> definition obj2_0x9 :: kernel_object where "obj2_0x9 \<equiv> Endpoint IdleEP" text \<open>UT2's VSpace\<close> definition pt2_0xC00000 :: pt where "pt2_0xC00000 \<equiv> (\<lambda>_. InvalidPTE)" definition obj2_0xC00000 :: kernel_object where "obj2_0xC00000 \<equiv> ArchObj (PageTable pt2_0xC00000)" definition pt2_0xBF7 :: pt where "pt2_0xBF7 \<equiv> (\<lambda>_. InvalidPTE) (0 := PageTablePTE (ucast (addrFromPPtr 0xC00000 >> pageBits)) undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition obj2_0xBF7 :: kernel_object where "obj2_0xBF7 \<equiv> ArchObj (PageTable pt2_0xBF7)" text \<open>T1's VSpace\<close> definition pt2_0xC05000 :: pt where "pt2_0xC05000 \<equiv> (\<lambda>_. InvalidPTE)" definition obj2_0xC05000 :: kernel_object where "obj2_0xC05000 \<equiv> ArchObj (PageTable pt2_0xC05000)" definition pt2_0xBF9 :: pt where "pt2_0xBF9 \<equiv> (\<lambda>_. InvalidPTE) (0 := PageTablePTE (ucast (addrFromPPtr 0xC05000 >> pageBits)) undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition obj2_0xBF9 :: kernel_object where "obj2_0xBF9 \<equiv> ArchObj (PageTable pt2_0xBF9)" text \<open>UT1's tcb\<close> definition obj2_0xC07 :: kernel_object where "obj2_0xC07 \<equiv> TCB \<lparr> tcb_ctable = CNodeCap 6 undefined undefined , tcb_vtable = ArchObjectCap (PageTableCap 0xBF7 (Some (asid2_0xBF7, 0))), tcb_reply = ReplyCap 0xC07 True {AllowGrant,AllowWrite}, \<comment> \<open>master reply cap to itself\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = Running, tcb_fault_handler = undefined, tcb_ipc_buffer = undefined, tcb_fault = undefined, tcb_bound_notification = None, tcb_mcpriority = undefined, tcb_arch = \<lparr>tcb_context = undefined\<rparr>\<rparr>" text \<open>T1's tcb\<close> definition obj2_0xC08 :: kernel_object where "obj2_0xC08 \<equiv> TCB \<lparr> tcb_ctable = CNodeCap 7 undefined undefined , tcb_vtable = ArchObjectCap (PageTableCap 0xBF9 (Some (asid2_0xBF9,0))), tcb_reply = ReplyCap 0xC08 True {AllowGrant,AllowWrite}, \<comment> \<open>master reply cap to itself\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = BlockedOnReceive 9 \<lparr> receiver_can_grant = False \<rparr>, tcb_fault_handler = undefined, tcb_ipc_buffer = undefined, tcb_fault = undefined, tcb_bound_notification = None, tcb_mcpriority = undefined, tcb_arch = \<lparr>tcb_context = undefined\<rparr>\<rparr>" (* the boolean in BlockedOnReceive is True if the object can receive but not send. but Tom says it only matters if the sender can grant - which is not the case of the UT1 - I think *) definition kh2 :: kheap where "kh2 \<equiv> [0x6 \<mapsto> obj2_0x6, 0x7 \<mapsto> obj2_0x7, 0x9 \<mapsto> obj2_0x9, 0xBF7 \<mapsto> obj2_0xBF7, 0xBF9 \<mapsto> obj2_0xBF9, 0xC00000 \<mapsto> obj2_0xC00000, 0xC05000 \<mapsto> obj2_0xC05000, 0xC07 \<mapsto> obj2_0xC07, 0xC08 \<mapsto> obj2_0xC08 ]" lemmas kh2_obj_def = obj2_0x6_def obj2_0x7_def obj2_0x9_def obj2_0xBF7_def obj2_0xBF9_def obj2_0xC00000_def obj2_0xC05000_def obj2_0xC07_def obj2_0xC08_def definition s2 :: "det_ext state" where "s2 \<equiv> \<lparr> kheap = kh2, cdt = Map.empty, is_original_cap = undefined, cur_thread = undefined, idle_thread = undefined, machine_state = undefined, interrupt_irq_node = (\<lambda>_. 9001), interrupt_states = undefined, arch_state = \<lparr> riscv_asid_table = (\<lambda>_. None), riscv_global_pts = undefined, riscv_kernel_vspace = undefined \<rparr>, exst = exst1 \<rparr>" subsubsection \<open>Defining the policy graph\<close> datatype Sys2Labels = UT2 | T2 | IRQ2 definition Sys2AgentMap :: "Sys2Labels agent_map" where "Sys2AgentMap \<equiv> (\<lambda>_. undefined) (0x5 := UT2, 0x6 := UT2, 0x7 := T2, 0x9 := T2, 0xBF7 := UT2, 0xBF9 := T2, 0xC00000 := UT2, 0xC05000 := T2, 0xC07 := UT2, 0xC08 := T2, 9001 := IRQ2 )" definition Sys2AuthGraph_aux :: "Sys2Labels auth_graph" where "Sys2AuthGraph_aux \<equiv> { (T2, Control, UT2) }" definition Sys2AuthGraph:: "Sys2Labels auth_graph" where "Sys2AuthGraph \<equiv> complete_AuthGraph Sys2AuthGraph_aux {T2, UT2}" definition Sys2ASIDMap :: "Sys2Labels agent_asid_map" where "Sys2ASIDMap \<equiv> (\<lambda>_. undefined) (asid2_0xBF7 := UT2, asid2_0xBF9 := T2 )" definition Sys2PAS :: "Sys2Labels PAS" where "Sys2PAS \<equiv> \<lparr> pasObjectAbs = Sys2AgentMap, pasASIDAbs = Sys2ASIDMap, pasIRQAbs = (\<lambda>_. IRQ2), pasPolicy = Sys2AuthGraph, pasSubject = UT2, pasMayActivate = True, pasMayEditReadyQueues = True, pasMaySendIrqs = True, pasDomainAbs = undefined \<rparr>" subsubsection \<open>Proof of pas_refined for Sys2\<close> lemma caps2_0x7_well_formed: "well_formed_cnode_n 10 caps2_0x7" apply (clarsimp simp: caps2_0x7_def well_formed_cnode_n_def) apply (clarsimp simp: the_nat_to_bl_10_def the_nat_to_bl_def nat_to_bl_def) apply (clarsimp simp: empty_cnode_def dom_def) apply (rule set_eqI, clarsimp) apply (rule iffI) apply (elim disjE, insert len_bin_to_bl, simp_all)[1] apply clarsimp done lemma caps2_0x6_well_formed: "well_formed_cnode_n 10 caps2_0x6" apply (clarsimp simp: caps2_0x6_def well_formed_cnode_n_def) apply (clarsimp simp: the_nat_to_bl_10_def the_nat_to_bl_def nat_to_bl_def) apply (clarsimp simp: empty_cnode_def dom_def) apply (rule set_eqI, clarsimp) apply (rule iffI) apply (elim disjE, insert len_bin_to_bl, simp_all)[1] apply clarsimp done lemma s2_caps_of_state : "caps_of_state s2 p = Some cap \<Longrightarrow> cap = NullCap \<or> (p,cap) \<in> { ((6::obj_ref,(the_nat_to_bl_10 1)), ThreadCap 0xC07), ((6::obj_ref,(the_nat_to_bl_10 2)), CNodeCap 6 undefined undefined), ((6::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageTableCap 0xBF7 (Some (asid2_0xBF7, 0)))), ((6::obj_ref,(the_nat_to_bl_10 4)), CNodeCap 5 undefined undefined), ((7::obj_ref,(the_nat_to_bl_10 1)), ThreadCap 0xC08), ((7::obj_ref,(the_nat_to_bl_10 2)), CNodeCap 7 undefined undefined), ((7::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageTableCap 0xBF9 (Some (asid2_0xBF9, 0)))), ((7::obj_ref,(the_nat_to_bl_10 4)), CNodeCap 5 undefined undefined), ((0xC07::obj_ref, (tcb_cnode_index 0)), CNodeCap 6 undefined undefined ), ((0xC07::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageTableCap 0xBF7 (Some (asid2_0xBF7, 0)))), ((0xC07::obj_ref, (tcb_cnode_index 2)), ReplyCap 0xC07 True {AllowGrant,AllowWrite}), ((0xC07::obj_ref, (tcb_cnode_index 3)), NullCap), ((0xC07::obj_ref, (tcb_cnode_index 4)), NullCap), ((0xC08::obj_ref, (tcb_cnode_index 0)), CNodeCap 7 undefined undefined ), ((0xC08::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageTableCap 0xBF9 (Some (asid2_0xBF9, 0)))), ((0xC08::obj_ref, (tcb_cnode_index 2)), ReplyCap 0xC08 True {AllowGrant,AllowWrite}), ((0xC08::obj_ref, (tcb_cnode_index 3)), NullCap), ((0xC08::obj_ref, (tcb_cnode_index 4)), NullCap)} " apply (insert caps2_0x7_well_formed) apply (insert caps2_0x6_well_formed) apply (simp add: caps_of_state_cte_wp_at cte_wp_at_cases s2_def kh2_def kh2_obj_def) apply (case_tac p, clarsimp) apply (clarsimp simp: cte_wp_at_cases split: if_splits) apply (clarsimp simp: tcb_cap_cases_def split: if_splits)+ apply (clarsimp simp: caps2_0x7_def split: if_splits) apply (clarsimp simp: caps2_0x6_def cte_wp_at_cases split: if_splits) done lemma Sys2_wellformed: "pas_wellformed Sys2PAS" apply (clarsimp simp: Sys2PAS_def policy_wellformed_def) apply (intro conjI) apply (simp_all add: Sys2AuthGraph_def complete_AuthGraph_def Sys2AuthGraph_aux_def) done lemma Sys2AgentMap_simps: "Sys2AgentMap 5 = UT2" "Sys2AgentMap 6 = UT2" "Sys2AgentMap 7 = T2" "Sys2AgentMap 9 = T2" "Sys2AgentMap 0xBF7 = UT2" "Sys2AgentMap 0xBF9 = T2" "Sys2AgentMap 0xC00000 = UT2" "Sys2AgentMap 0xC05000 = T2" "Sys2AgentMap 0xC07 = UT2" "Sys2AgentMap 0xC08 = T2" "Sys2AgentMap 9001 = IRQ2" by (simp_all add: Sys2AgentMap_def) lemma domains_of_state_s2[simp]: "domains_of_state s2 = {}" apply (rule equalityI) apply (rule subsetI) apply clarsimp apply (erule domains_of_state_aux.induct) apply (simp add: s2_def exst1_def) apply simp done lemma thread_bound_ntfns_2[simp]: "thread_bound_ntfns s2 = Map.empty" unfolding s2_def thread_bound_ntfns_def apply (rule ext) apply (simp add: get_tcb_def) apply (simp add: kh2_def kh2_obj_def) done lemma "pas_refined Sys2PAS s2" apply (clarsimp simp: pas_refined_def) apply (intro conjI) apply (simp add: Sys2_wellformed) apply (simp add: Sys2PAS_def s2_def Sys2AgentMap_def irq_map_wellformed_aux_def) apply (clarsimp simp: auth_graph_map_def Sys2PAS_def state_objs_to_policy_def state_bits_to_policy_def tcb_domain_map_wellformed_aux_def)+ apply (erule state_bits_to_policyp.cases, simp_all) apply (drule s2_caps_of_state, clarsimp) apply (elim disjE, simp_all add: cap_auth_conferred_def Sys2AgentMap_simps Sys2AuthGraph_def Sys2AuthGraph_aux_def complete_AuthGraph_def split: if_split_asm)[1] apply (drule s2_caps_of_state, clarsimp) apply (elim disjE, simp_all)[1] apply (clarsimp simp: state_refs_of_def s2_def kh2_def kh2_obj_def split: if_splits) apply (clarsimp split:if_splits option.splits simp: thread_st_auth_def tcb_states_of_state_def Sys2AgentMap_simps Sys2AuthGraph_def complete_AuthGraph_def Sys2AuthGraph_aux_def dest!: get_tcb_SomeD) apply (simp add: s2_def) (* this is OK because cdt is empty..*) apply (simp add: s2_def) (* this is OK because cdt is empty..*) apply (fastforce simp: state_vrefs_def vs_refs_aux_def s2_def kh2_def kh2_obj_def pt2_0xBF9_def pt2_0xBF7_def pt2_0xC05000_def pt2_0xC00000_def Sys2AgentMap_simps Sys2AuthGraph_def Sys2AuthGraph_aux_def complete_AuthGraph_def pte_ref2_def graph_of_def opt_map_def ptr_range_def split: if_splits) apply clarsimp apply (erule state_asids_to_policy_aux.cases) apply clarsimp apply (fastforce simp: Sys2PAS_def Sys2AuthGraph_def Sys2AuthGraph_aux_def complete_AuthGraph_def Sys2AgentMap_simps asid_low_bits_def Sys2ASIDMap_def asid2_0xBF7_def asid2_0xBF9_def dest!: s2_caps_of_state) apply (clarsimp simp: state_vrefs_def vs_refs_aux_def s2_def kh2_def kh2_obj_def split: if_splits) apply (clarsimp simp: s2_def) apply (clarsimp) apply (erule state_irqs_to_policy_aux.cases) apply (fastforce simp: Sys2PAS_def Sys2AuthGraph_def Sys2AuthGraph_aux_def complete_AuthGraph_def Sys2AgentMap_simps Sys2ASIDMap_def asid2_0xBF7_def asid2_0xBF9_def dest!: s2_caps_of_state) done end end
If $x \neq 0$, then the polynomial $p$ reflected about the $y$-axis is equal to $x^{n}p(1/x)$, where $n$ is the degree of $p$.
import numpy as np import os def show_all_files_in_directory(input_path,extension): 'This function reads the path of all files in directory input_path' files_list=[] for path, subdirs, files in os.walk(input_path): for file in files: if file.endswith(extension): files_list.append(os.path.join(path, file)) return files_list path = '/home/batool/FL/data' all_npz_files = show_all_files_in_directory(path,'.npz') ##all files have the same length all_gps_npz_files = [a for a in all_npz_files if 'gps.npz' in a.split('/')] for npz_file in all_gps_npz_files: print(npz_file) gps_npz = np.load(npz_file)['gps'] randperm = np.random.permutation(len(gps_npz)) # 'data/a.npy' save_directory = '/'.join(npz_file.split('/')[:-1]) print('save directory',save_directory) np.save(save_directory+'/ranperm.npy',randperm)
(*-------------------------------------------------* | (a part of) ep2 | | September 2004 | | December 2004 (modified) | | November 2005 (modified) | | April 2006 (modified) | | March 2007 (modified) | | | | CSP-Prover on Isabelle2009 | | June 2009 (modified) | | | | CSP-Prover on Isabelle2016 | | May 2016 (modified) | | | | Markus Roggenbach (Univ of Wales Swansea, UK) | | Yoshinao Isobe (AIST, Japan) | *-------------------------------------------------*) theory ep2_nucleus imports CSP_F begin (*** To automatically unfold syntactic sugar ***) declare csp_prefix_ss_def [simp] declare inj_on_def [simp] (********************************************************* data type passed on channels *********************************************************) typedecl init_d typedecl request_d typedecl response_d typedecl exit_d datatype Data = Init init_d | Exit exit_d | Request request_d | Response response_d (********************************************************* event (channel) *********************************************************) datatype Event = c Data (********************************************************* abstract component description level *********************************************************) datatype ACName = Acquirer | AcConfigManagement | Terminal | TerminalConfigManagement primrec ACfun :: "ACName => (ACName, Event) proc" where "ACfun Acquirer = c ? x:(range Init) -> $AcConfigManagement" |"ACfun AcConfigManagement = c !? exit:(range Exit) -> SKIP |~| c !? request:(range Request) -> c ? response:(range Response) -> $AcConfigManagement" |"ACfun Terminal = c !? init:(range Init) -> $TerminalConfigManagement" |"ACfun TerminalConfigManagement = c ? x -> IF (x:range Request) THEN (c !? response:(range Response) -> $TerminalConfigManagement) ELSE IF (x:range Exit) THEN SKIP ELSE STOP" (* defs (overloaded) Set_ACfun_def [simp]: "PNfun == ACfun" *) overloading Set_ACfun == "PNfun :: (ACName, Event) pnfun" begin definition "PNfun == ACfun" end declare Set_ACfun_def [simp] definition AC :: "(ACName, Event) proc" where AC_def: "AC == ($Acquirer |[range c]| $Terminal)" (*---------------------------------------------------------------* | NOTE | | | | c ! v -> P : sends a value v to c, then behaves like P. | | | | c ? x:X -> P(x) : receives a value v from c if c in X, | | then behaves like P(v). | | | | c !? x:X -> P(x) : sends a value v selected from X to c, | | then behaves like P(v). | | | *---------------------------------------------------------------*) (********************************************************* equivalent sequential behavior *********************************************************) datatype SeqName = SeqInit | Loop primrec Seqfun :: "SeqName => (SeqName, Event) proc" where "Seqfun SeqInit = c !? init:(range Init) -> $Loop" |"Seqfun Loop = c !? exit:(range Exit) -> SKIP |~| c !? request:(range Request) -> c !? response:(range Response) -> $Loop" (* defs (overloaded) Set_Seqfun_def [simp]: "PNfun == Seqfun" *) overloading Set_Seqfun == "PNfun :: (SeqName, Event) pnfun" begin definition "PNfun == Seqfun" end declare Set_Seqfun_def [simp] definition Seq :: "(SeqName, Event) proc" where Seq_def: "Seq == $SeqInit" (********************************************************* relating function between ACName and SeqName *********************************************************) primrec Seq_to_AC :: "SeqName => (ACName, Event) proc" where "Seq_to_AC (SeqInit) = ($Acquirer |[range c]| $Terminal)" |"Seq_to_AC (Loop) = ($AcConfigManagement |[range c]| $TerminalConfigManagement)" (********************************************************* gProc lemmas (routine work) *********************************************************) lemma guardedfun_AC_Seq[simp]: "guardedfun ACfun" "guardedfun Seqfun" by (simp add: guardedfun_def, rule allI, induct_tac p, simp_all)+ (********************************************************* a theorem for verifying Seq <=F AC *********************************************************) (* defs FPmode_def [simp]: "FPmode == CMSmode" *) overloading FPmode == "FPmode :: fpmode" begin definition "FPmode == CMSmode" end declare FPmode_def [simp] theorem ep2: "Seq =F AC" apply (unfold Seq_def AC_def) apply (rule cspF_fp_induct_left[of _ "Seq_to_AC"]) apply (simp_all) apply (simp) apply (induct_tac p) apply (simp_all) (* 1st subgoal *) apply (cspF_unwind) apply (cspF_hsf)+ apply (rule cspF_decompo, auto) apply (cspF_hsf)+ apply (rule cspF_decompo, auto) apply (cspF_hsf)+ (* 2nd subgoal *) apply (cspF_auto | rule cspF_decompo | rule cspF_decompo_ref | auto simp add: image_iff)+ done end
If $x$ is an element of a measurable set $A$, then the measure of the set $\{x\} \cup A$ is the sum of the measures of $\{x\}$ and $A$.
module Props.Util import public Data.List %access public export private mkNo : {xs' : List a} -> ((x' = y') -> Void) -> (Elem x' xs' -> Void) -> Elem x' (y' :: xs') -> Void mkNo f g Here = f Refl mkNo f g (There x) = g x -- Use this until https://github.com/idris-lang/Idris-dev/issues/4161 fastIsElem : DecEq a => (x : a) -> (xs : List a) -> Dec (Elem x xs) fastIsElem x [] = No absurd fastIsElem x (y :: xs) with (decEq x y) fastIsElem x (x :: xs) | (Yes Refl) = Yes Here fastIsElem x (y :: xs) | (No contra) with (fastIsElem x xs) fastIsElem x (y :: xs) | (No contra) | (Yes prf) = Yes (There prf) fastIsElem x (y :: xs) | (No contra) | (No f) = No (mkNo contra f) using (a: Type, P : a -> Type, Q: a -> Type) data EitherK : { a : Type } -> ( P : a -> Type ) -> ( Q : a -> Type) -> a -> Type where LeftK : ( prf : P c ) -> EitherK P Q c RightK : ( prf : Q c ) -> EitherK P Q c -- Add these to not depend on contrib data Given : Dec x -> Type where Always : Given (Yes prf) data Denied : Dec x -> Type where Never : Denied (No contra)
Formal statement is: lemma norm_diff_triangle_ineq: "norm ((a + b) - (c + d)) \<le> norm (a - c) + norm (b - d)" Informal statement is: The norm of the difference of two sums is less than or equal to the sum of the norms of the differences.
{- 1 -} printLonger : IO () printLonger = do putStr "First string: " str1 <- getLine putStr "Second string: " str2 <- getLine if length str1 > length str2 then putStrLn (show (length str1)) else putStrLn (show (length str2)) {- 2 -} printLonger' : IO () printLonger' = putStr "First string: " >>= \_ => getLine >>= \str1 => putStr "Second string: " >>= \_ => getLine >>= \str2 => if length str1 > length str2 then putStrLn (show (length str1)) else putStrLn (show (length str2))
module Screen import Data.Bits import Data.Vect import Effects import Effect.SDL import Constants import Utilities %default total -- a bit represents a monochrome pixel data Pixel = On | Off Show Pixel where show On = "▓" show Off = "░" xorOnePixel : (p1 : Pixel) -> (p2 : Pixel) -> Pixel xorOnePixel On Off = On xorOnePixel Off On = On xorOnePixel _ _ = Off -- track if any pixel was erased (so we can set VF in the CPU) pixelWasErased : (p1 : Pixel) -> (p2 : Pixel) -> Bool pixelWasErased On Off = True pixelWasErased _ _ = False -- for convenience ScreenWidth : Nat ScreenWidth = 64 ScreenHeight : Nat ScreenHeight = 32 -- 64x32 monochrome pixel display export record Screen where constructor MkScreen Picture : Vect ScreenHeight (Vect ScreenWidth Pixel) WasErased : Bool -- track for VF data Coord = MkCoord Int Int Pixel export wasErased : (screen : Screen) -> Bool wasErased = WasErased export renderScreen : (screen : Screen) -> { [SDL_ON] } Eff () renderScreen screen = let (coords, _) = foldl pixelCoordsForRow ([], 0) (Picture screen) in do mapE renderPixel coords pure () where pixelCoords : (accum : (List Coord, (Int, Int))) -> (pixel : Pixel) -> (List Coord, (Int, Int)) pixelCoords (rects, (x, y)) pixel = MkPair (MkCoord x y pixel :: rects) (x + 1, y) pixelCoordsForRow : (accum : (List Coord, Int)) -> Vect ScreenWidth Pixel -> (List Coord, Int) pixelCoordsForRow (coords, y) row = let (newCoords, _) = foldl pixelCoords ([], (MkPair 0 y)) row in MkPair (coords ++ newCoords) (y + 1) renderPixel : Coord -> EffM m () [SDL_ON] (\_ => [SDL_ON]) renderPixel (MkCoord x y pixel) = let color = case pixel of On => white; Off => black in rectangle color (x * Scale) (y * Scale) Scale Scale export Show Screen where show s = foldl drawRow "" (Picture s) where concatenate : (accum : String) -> (p : Pixel) -> String concatenate accum val = accum ++ show val drawRow : (accum : String) -> (row : Vect ScreenWidth Pixel) -> String drawRow accum row = accum ++ (foldl concatenate "" row) ++ "\n" export newScreen : Screen newScreen = let picture = Vect.replicate ScreenHeight $ Vect.replicate ScreenWidth Off in MkScreen picture False readPixelFromPicture : (s : Screen) -> (x : Fin ScreenWidth) -> (y : Fin ScreenHeight) -> Pixel readPixelFromPicture s x y = let picture = Picture s in let row = Vect.index y picture in Vect.index x row writePixelToPicture : (s : Screen) -> (p : Pixel) -> (x : Fin ScreenWidth) -> (y : Fin ScreenHeight) -> Screen writePixelToPicture s p x y = let picture = Picture s in let row = Vect.index y picture in let newRow = replaceAt x p row in let newPicture = replaceAt y newRow picture in record { Picture = newPicture } s writePixelToScreen : (s : Screen) -> (p : Pixel) -> (x : Int) -> (y : Int) -> Screen writePixelToScreen s p x y = let realX = restrict (pred ScreenWidth) $ cast x in let realY = restrict (pred ScreenHeight) $ cast y in let pixel = readPixelFromPicture s realX realY in let newPixel = xorOnePixel pixel p in let newScreen = writePixelToPicture s newPixel realX realY in let wasErased = pixelWasErased pixel p || WasErased s in record { WasErased = wasErased } newScreen explodeByte : (val : Bits8) -> Vect 8 Pixel explodeByte val = let bits : Bits 8 = cast val in let booleans = map (flip getBit bits) [7, 6, 5, 4, 3, 2, 1, 0] in map convertPixel booleans where convertPixel : Bool -> Pixel convertPixel True = On convertPixel False = Off writeSpriteLineToScreen : (screen : Screen) -> (val : Bits8) -> (x : Int) -> (y : Int) -> Screen writeSpriteLineToScreen screen val x y = let pixels = explodeByte val in fst $ foldl (drawPixel y) (MkPair screen x) pixels where drawPixel : (y : Int) -> (accum : (Screen, Int)) -> (pixel : Pixel) -> (Screen, Int) drawPixel y (screen, x) p = let drawnScreen = writePixelToScreen screen p x y in let wasErased = wasErased screen || wasErased drawnScreen in let newScreen = record { WasErased = wasErased } drawnScreen in MkPair newScreen (x + 1) export writeSpriteToScreen : (screen : Screen) -> (sprite : Vect len Bits8) -> (x : Int) -> (y : Int) -> Screen writeSpriteToScreen screen sprite x y = let resetScreen = record { WasErased = False } screen in fst $ foldl (drawLine x) (MkPair resetScreen y) sprite where drawLine : (x : Int) -> (accum : (Screen, Int)) -> (val : Bits8) -> (Screen, Int) drawLine x (screen, y) val = let drawnScreen = writeSpriteLineToScreen screen val x y in let wasErased = wasErased screen || wasErased drawnScreen in let newScreen = record { WasErased = wasErased } drawnScreen in MkPair newScreen (y + 1) export defaultSpriteStartingAddress : Fin 16 -> Bits16 defaultSpriteStartingAddress x = let spriteOffset = cast $ finToNat x in let offsetAddress = DefaultSpriteDataLength * spriteOffset in cast $ DefaultSpriteDataAddress + offsetAddress -- 16 8x5 sprites for hexadecimal values export defaultSpriteData : List Bits8 defaultSpriteData = [ 0xf0, 0x90, 0x90, 0x90, 0xf0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xf0, 0x10, 0xf0, 0x80, 0xf0, 0xf0, 0x10, 0xf0, 0x10, 0xf0, 0x90, 0x90, 0xf0, 0x10, 0x10, 0xf0, 0x80, 0xf0, 0x10, 0xf0, 0xf0, 0x80, 0xf0, 0x90, 0xf0, 0xf0, 0x10, 0x20, 0x40, 0x40, 0xf0, 0x90, 0xf0, 0x90, 0xf0, 0xf0, 0x90, 0xf0, 0x10, 0xf0, 0xf0, 0x90, 0xf0, 0x90, 0x90, 0xe0, 0x90, 0xe0, 0x90, 0xe0, 0xf0, 0x80, 0x80, 0x80, 0xf0, 0xe0, 0x90, 0x90, 0x90, 0xe0, 0xf0, 0x80, 0xf0, 0x80, 0xf0, 0xf0, 0x80, 0xf0, 0x80, 0x80 ]
SUBROUTINE GG_ARC ( sys, xcent, ycent, xcrm, ycrm, npts, + ang1, ang2, iaccf, xout, yout, iret ) C************************************************************************ C* GG_ARC * C* * C* This routine computes the points around an arc. The center and the * C* point on the radius can be any coordinate system. The output points * C* will be in the same coordinates. If the points are in Map * C* coordinates, then the angles are degrees from North. For all other * C* coordinates, the angles are oriented with 0 degrees along the * C* X axis. The accuracy factor controls the amount of "course * C* correction" that is applied to the lat/lon point calculation. A * C* value of 0 means that the true great arc calculation is performed. * C* A value larger than 0 is the number of intermediary points to * C* compute along the radial distance. * C* * C* GG_ARC ( SYS, XCENT, YCENT, XCRM, YCRM, NPTS, ANG1, ANG2, IACCF, * C* XOUT, YOUT, IRET ) * C* * C* Input parameters: * C* SYS CHAR* Coordinate system * C* 'S' = screen coordinates * C* 'D' = device coordinates * C* 'N' = normalized coordinates * C* 'V' = view coordinates * C* 'P' = plot coordinates * C* 'M' = map coordinates * C* 'G' = grid coordinates * C* XCENT REAL X / Lat of center point * C* YCENT REAL Y / Lon of center point * C* XCRM REAL X / Lat of radius point * C* YCRM REAL Y / Lon of radius point * C* NPTS INTEGER Number of points on arc * C* ANG1 REAL Start angle * C* North relative for M coord * C* ANG2 REAL End angle * C* North relative for M coord * C* IACCF INTEGER Accuracy factor for M coord * C* * C* Output parameters: * C* XOUT(*) REAL X / Lat of output points * C* YOUT(*) REAL Y / Lon of output points * C* IRET INTEGER Return code * C** * C* Log: * C* S. Jacobs/NCEP 5/01 Created * C************************************************************************ INCLUDE 'GEMPRM.PRM' C* CHARACTER*(*) sys REAL xout (*), yout (*) C* CHARACTER sysuc*1 C------------------------------------------------------------------------ iret = 0 C* np = npts IF ( np .lt. 2 ) np = 2 C C* Compute the arc in Map coordinates. C CALL ST_LCUC ( sys, sysuc, ier ) IF ( sysuc .eq. 'M' ) THEN dtheta = ang2 - ang1 IF ( ABS (dtheta) .gt. 360. ) dtheta = 360. C thta = dtheta / FLOAT ( np - 1 ) C nn = 1 CALL CLO_DIST ( xcent, ycent, nn, xcrm, ycrm, dist, ier ) C IF ( iaccf .gt. 100 ) THEN jaccf = 100 ELSE IF ( iaccf .lt. 0 ) THEN jaccf = 1 ELSE jaccf = iaccf + 1 END IF C DO i = 1, np dir = ang1 + thta * (i-1) xx = xcent yy = ycent dst = dist / FLOAT (jaccf) DO j = 1, jaccf CALL CLO_DLTLN ( xx, yy, dst, dir, + xout(i), yout(i), ier ) xx = xout(i) yy = yout(i) END DO END DO ELSE C C* Compute the arc in all other coordinates, by tranforming C* to Normal coordinates. C CALL GTRANS ( sysuc, 'N', 1, xcent, ycent, xc, yc, ier ) CALL GTRANS ( sysuc, 'N', 1, xcrm, ycrm, xr, yr, ier ) C theta1 = ang1 * DTR theta2 = ang2 * DTR dtheta = theta2 - theta1 IF ( ABS (dtheta) .gt. TWOPI ) dtheta = TWOPI C thta = dtheta / FLOAT ( np - 1 ) C dist = SQRT ( (xc-xr)**2 + (yc-yr)**2 ) C DO i = 1, np dir = theta1 + thta * (i-1) xout (i) = xc + dist * COS ( theta1 + dir ) yout (i) = yc + dist * SIN ( theta1 + dir ) END DO C CALL GTRANS ( 'N', sysuc, np, xout, yout, xout, yout, ier ) END IF C* RETURN END
module HTLogger using SerialPorts using Dates struct TimeoutError <: Exception end """ run(;path="log", baudrate=9600, port="", interval=5, lines_per_file=135_000, debug=false) Starts logging the temperature and humidity data from the connected device. # Keyword Arguments * `path`: the path where the `.log` files are stored. If the path does not exist, it is created. * `baudrate`: the baudrate the device is configured to * `port`: the serial port the device is connected to. If `port` is an empty string, the program will try to find the device automatically. * `interval`: the time between the individual measurements in seconds. It is implemented in such a way that the main measurement loop is idle for the `interval` time. This means that the individual measurements are more than `interval` seconds apart because additional time is spent reading the data from the device and writing to the file. * `lines_per_file=135_000`: number of lines in a log file until a new file is created. 1MB roughly corresponds to 28,000 entries. * `debug`: prints messages that help to debug in case there are problems """ function run(;path="log", baudrate=57600, port="",interval=5,lines_per_file = 135_000,debug=false) # In case an error occurs we will rerun the program recursively indefinetly # until the program is interrupted. Collect the keyword arguments that get # passed to the run function recursively. Do not specify the port in the # rerun because the logger port could have been changed. kwargs = ( path=path, baudrate=baudrate, interval=interval, lines_per_file=lines_per_file, debug=debug ) # define the serial port as a constant reference so it is visible in all # try-catch blocks local s = Ref{SerialPort}() try # if no port is supplied search automatically if port == "" port = find_port(; debug, baudrate) end # connect to the device s[] = SerialPort(port, baudrate) # wait for board to be ready sleep(3) catch err if err isa InterruptException # in case the user interrupts the program println("Terminated by user while trying to connect to logging device.") return nothing else # if no port can be found or any other error occurs we will try running again @warn "Could not find the device on any port. Make sure it is connected.\nTrying again..." sleep(5) run(; kwargs...) end end # create a file / get the file to write to filepath, nlines = logfile_handling(path, lines_per_file) try while true t = string(Dates.now()) H, T = get_data(s[]) # round these values H = round(H, digits=3) T = round(T, digits=2) open(filepath, "a") do io newline = "$t\t$T\t$H\n" write(io, newline) end nlines += 1 if nlines >= lines_per_file filepath, nlines = logfile_handling(path, lines_per_file) end sleep(interval) end catch err if err isa InterruptException println("Logging terminated by user") else @warn "A $err occured. Trying to start over..." close(s[]) # do not specify the port! If the device is disconnected run(; kwargs...) end finally # close the serial port close(s[]) end nothing end function logfile_handling(path, lines_per_file) if !isdir(path) mkpath(path) println(""" Did not find the specified path at $path, so I created that for you!\n """) end filepath = get_logfile_for_writing(path, lines_per_file) end function get_logfile_for_writing(path, lines_per_file)::Tuple{String,Int} # lines_per_file has to be greater than 0. Otherwise we'll be # stuck generating empty files lines_per_file > 0 || error("Number of lines per file has to be > 0.") files = readdir(path) filter!(x -> occursin(".log", x), files) sort!(files) if length(files) > 0 println("Did find $(length(files)) logfiles") file = last(files) filepath = joinpath(path, file) nlines = get_num_lines(filepath) if nlines < lines_per_file println("Found logfile $file with $nlines lines. Writing to that.") return (filepath, nlines) else # Found a logfile but it already has more than the maximum # allowed number of lines println("""Found logfile $file but it already has $nlines lines. The maximum number of lines is set to $lines_per_file.\n""") end else println("Did not find a log file at $path.") end filename = generate_logfile_name() filepath = joinpath(path, filename) touch(filepath) filepath, 0 end function generate_logfile_name(prefix="hty939", ext=".log") datestring = splitext( string(now()) )[1] datestring = replace(datestring, ':' => '_') prefix * "_" * datestring * ext end function get_num_lines(filepath)::Int # open file / read as byte array / close file f = open(filepath, "r") str = read(f) close(f) nrows = 0 for byte in str # check for newline (\n) byte == 0x0a && (nrows += 1) end nrows end function read_line(s; timeout=10) readbuffer = IOBuffer() t_start = time() byte = "" while byte ≠ "\n" t = time() if bytesavailable(s) > 0 byte = read(s, 1) write(readbuffer, byte) end if t - t_start > timeout throw(TimeoutError) end end str = String(take!(readbuffer)) end function query(s, msg; timeout=2) write(s, msg) read_line(s; timeout=timeout) end function read_raw_data(s) # clear what ever may be there readavailable(s) readbuffer = query(s, "m") parse.(UInt16, strip.(split(readbuffer, ','))) end """ convert_temperature(T_raw) -> Float64 Convert the raw temperature data from the sensor to the actual temperature in degree Celsius. """ function convert_temperature(T_raw) (165 / 16383) * T_raw - 40 end """ convert_humidity(H_raw) -> Float64 Convert the raw humidity data from the sensor to the actual percent relative humidity. """ function convert_humidity(H_raw) 100 / 16383 * H_raw end function get_data(s) H_raw, T_raw = read_raw_data(s) H = convert_humidity(H_raw) T = convert_temperature(T_raw) H, T end function find_port(;debug=false, baudrate=57600) # get a list with all available serial ports ports = SerialPorts.list_serialports() print("Searching for logger...") for p in ports print(".") try # try to connect to each port in the list s = SerialPort(p, baudrate) debug && println("$p is open") # wait for the device to initialize sleep(2.0) try # try to write and read from the port # clear everything that is in the buffer readavailable(s) readbuffer = query(s, "i") debug && println("Got '$readbuffer' from $p") # If we successfully identified the logger close the connection # and return the port. Otherwise continue with the next port in # the list. if readbuffer == "htlogger\n" println("Found the logger on port $p") close(s) return p else debug && println("Could read from $p but got wrong identifier.") end catch # write / read failed debug && println("Could not write to port $p") finally close(s) end catch # connection failed debug && println("Could not open port $p") end end # make a new line println() error("Could not find logger.") end end
module Replica.Command.Version import Data.List1 import Replica.Help import Replica.Option.Types import Replica.Version public export data Version = MkVersion String export parseVersion : List1 String -> ParseResult Version parseVersion ("version" ::: xs) = Done $ MkVersion "replica version \{version}" parseVersion xs = InvalidOption xs export helpVersion : Help helpVersion = MkHelp "version" (Just "replica version") "Show replica version" [] Nothing
\section{Lua} \label{sec:lua} \subsection{General} \label{sec:general} TODO \subsection{Modules} \label{sec:modules} \subsubsection{Filesystem} \label{sec:filesystem} abs\_path:string = absolute(path:string) can\_path:string = canonical(path:string) copy(from:string, to:string) success:bool = mkdir(dir:string) link(to:string, new\_link:string) symlink(to:string, new\_link:string) to:string = symlink(link:string) cd(path:string) path:string = cd() found:bool = exists(path:string) are\_equal:bool = equal(path1:string, path2:string) bytes:int = size(path:string) time:int = lastmod(path:string) perm(path:string, p:string, ...) p, ... = perm(path:string) num:bool|int = remove(path:string[, all:bool]) rename(old\_path:string, new\_path:string) capacity:int, free:int, available:int = space(path:string) t:string = type(path:string) abs\_path:string = sysabsolute(path:string) path:string = tmpdir() uni\_path:string = unique(path:string) list:table = dir(path:string) TODO \subsubsection{Font} \label{sec:font} fonts\_list:table = list() font:userdata = create(family:string[, size:float][, bold:bool][, italic:bool][, underline:bool][, strikeout:bool][, spacing:float][, rtl:bool]) family:string, size:float, bold:bool, italic:bool, underline:bool, strikeout:bool, spacing:float, rtl:bool = font:data() height:float, ascent:float, descent:float, internal\_leading:float, external\_leading:float = font:metrics() width:float = font:textwidth(text:string) path:table = font:textpath(text:string) TODO \subsubsection{Geometry} \label{sec:geometry} new\_x:float, new\_y:float = stretch(x:float, y:float, len:float) [x:float, y:float] = lineintersect(l1p1x:float, l1p1y:float, l1p2x:float, l1p2y:float, l2p1x:float, l2p1y:float, l2p2x:float, l2p2y:float) on:bool = online(px:float, py:float, lp1x:float, lp1y:float, lp2x:float, lp2y:float) inside:bool = intriangle(px:float, py:float, tp1x:float, tp1y:float, tp2x:float, tp2y:float, tp3x:float, tp3y:float) dir:int = direction(p1x:float, p1y:float, p2x:float, p2y:float, p3x:float, p3y:float) dir:int = direction(v1x:float, v1y:float, v2x:float, v2y:float) minx:float, miny:float, maxx:float, maxy:float = bound(points:table) curves:table = arccurve(px:float, py:float, cpx:float, cpy:float, angle:float) line\_points:table = curveflatten(p0x:float, p0y:float, p1x:float, p1y:float, p2x:float, p2y:float, p3x:float, p3y:float[, tolerance:float]) triangles:table = tesselate(contours:table) mat:userdata = matrix([x11:float, x12:float, x13:float, x14:float, x21:float, x22:float, x23:float, x24:float, x31:float, x32:float, x33:float, x34:float, x41:float, x42:float, x43:float, x44:float]) new\_mat:userdata = mat:\_\_mul(other\_mat:userdata) mat:userdata = mat:multiply(other\_mat:userdata) mat:userdata = mat:translate(x:float, y:float, z:float) mat:userdata = mat:scale(x:float, y:float, z:float) mat:userdata = mat:rotate(axis:string, angle:float) mat:userdata = mat:identity() success:bool = mat:invert() new\_x:float, new\_y:float, new\_z:float, new\_w:float = mat:transform(x:float, y:float[, z:float][, w:float]) mat:userdata = mat:data(x11:float, x12:float, x13:float, x14:float, x21:float, x22:float, x23:float, x24:float, x31:float, x32:float, x33:float, x34:float, x41:float, x42:float, x43:float, x44:float) x11:float, x12:float, x13:float, x14:float, x21:float, x22:float, x23:float, x24:float, x31:float, x32:float, x33:float, x34:float, x41:float, x42:float, x43:float, x44:float = mat:data() TODO \subsubsection{Math} \label{sec:math} truncated\_x:int = trunc(x:float) rounded\_x:int = round(x:float) trimmed\_x:float = trim(x:float, limit1:float, limit2:float) sign\_num:float = sign(x:float) c:float = hypot(a:float, b:float) x:float = asinh(angle:float) x:float = acosh(angle:float) x:float = atanh(angle:float) error:float = erf(x:float) gamma:float = tgamma(x:float) rest:float, exponent:int = frexp(x:float) class:string = classify(num:float) cx:userdata = complex([r:float][i:float]) cx:userdata = polar(magn:float[, phase:float]) cx:\_\_call([r:float][i:float]) r:float, i:float = cx:\_\_call() desc:string = cx:\_\_tostring() new\_cx:userdata = cx:\_\_add(other\_cx:userdata) new\_cx:userdata = cx:\_\_sub(other\_cx:userdata) new\_cx:userdata = cx:\_\_mul(other\_cx:userdata) new\_cx:userdata = cx:\_\_div(other\_cx:userdata) new\_cx:userdata = cx:\_\_eq(other\_cx:userdata) new\_cx:userdata = cx:\_\_pow(other\_cx:userdata) magn:float = cx:abs() phase:float = cx:arg() sqrmagn:float = cx:norm() conjugate\_cx:userdata = cx:conj() ebase\_cx:userdata = cx:exp() natlog\_cx:userdata = cx:log() sqrt\_cx:userdata = cx:sqrt() sin\_cx:userdata = cx:sin() cos\_cx:userdata = cx:cos() tan\_cx:userdata = cx:tan() asin\_cx:userdata = cx:asin() acos\_cx:userdata = cx:acos() atan\_cx:userdata = cx:atan() sinh\_cx:userdata = cx:sinh() cosh\_cx:userdata = cx:cosh() tanh\_cx:userdata = cx:tanh() asinh\_cx:userdata = cx:asinh() acosh\_cx:userdata = cx:acosh() atanh\_cx:userdata = cx:atanh() new\_x:float = gauss(x:float, sigma:float) x:float = fac(n:float) x:float = bezier(t:float, i1, ...) TODO \subsubsection{PNG} \label{sec:png} img\_data:table = read(data:string) img\_data:tablereadfile(path:string) data:string = write(img\_data:table) writefile(path:string, img\_data:table) TODO \subsubsection{Regex} \label{sec:regex} rx:userdata = \_\_call(expr:string[, flags:table]) new\_data:string = rx:replace(data:string, format:string) matches:table = rx:match(data:string) TODO \subsubsection{Table} \label{sec:table} new\_tab:table = copy(tab:table[, depth:int]) desc:string = tostring(tab:table) new\_tab = alloc(arr:int, hash:int) equal:bool = compare(tab1:table, tab2:table[, comparator:function]) n:int = count(tab:table, value:\^nil) [pos:int] = find(tab:table, value:\^nil) fill(tab:table, value:\^nil, n:int[, pos:int]) reverse(tab:table) rotate(tab:table, axis:int) result:any = accumulate(tab:table, init:\^nil, processor:function) insertn(tab:table, pos:int, value:any, ...) removen(tab:table, pos:int, n:int) move(a1:table, f:int, e:int, t:int[, a2:table]) TODO \subsubsection{TGL} \label{sec:tgl} ctx:userdata = \_\_call() ctx:activate() ctx.activate() ctx.clear(buffer:string, ...) ctx.viewport(x:int, y:int, width:int, height:int) ctx.size(type:string, size:string) ctx.mode(mode:string) ctx.scissor(x:int, y:int, width:int, height:int) ctx.scissor() ctx.logic(op:string) ctx.logic() ctx.mask(...) ctx.mask() ctx.depth(func:string) ctx.depth() ctx.stencil(config:table) ctx.stencil() ctx.blend(config:table) ctx.blend() data:table|string = ctx.info(type:string) shader:userdata = ctx.createshader(type:string, source:string) program:userdata = ctx.createprogram(vshader:userdata, fshader:userdata) program:uniform(location:string, type:string, ...) program:use() vao:userdata = ctx.createvao(meta:table, data:table) vao:draw(mode:string, first:int, count:int) tex:userdata = ctx.createtexture(width:int, height:int, format:string[, data:string]) tex:bind([target:int]) tex:param(param:string, value:string) width:int, height:int, format:string[, data:string] = tex:data([request\_format:string]) fbo:userdata = ctx.createfbo(width:int, height:int[, samples:int]) fbo:bind() fbo:info(width:int, height:int, samples:int) tex:userdata = fbo:blit(tex:userdata) TODO \subsubsection{UTF-8} \label{sec:utf8} [bytes:int] = charrange(data:string[, pos:int]) iter:function = chars(data:string) char\_num:int = len(data:string) charpattern = "[\textbackslash{}0-\textbackslash{}x7F\textbackslash{}xC2-\textbackslash{}xF4][\textbackslash{}x80-\textbackslash{}xBF]*" TODO \subsection{Extensions} \label{sec:extensions} TODO
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Thomas Browning ! This file was ported from Lean 3 source module group_theory.group_action.quotient ! leanprover-community/mathlib commit 34ee86e6a59d911a8e4f89b68793ee7577ae79c7 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.Hom.GroupAction import Mathbin.Data.Fintype.BigOperators import Mathbin.Dynamics.PeriodicPts import Mathbin.GroupTheory.GroupAction.ConjAct import Mathbin.GroupTheory.Commutator import Mathbin.GroupTheory.Coset /-! # Properties of group actions involving quotient groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves properties of group actions which use the quotient group construction, notably * the orbit-stabilizer theorem `card_orbit_mul_card_stabilizer_eq_card_group` * the class formula `card_eq_sum_card_group_div_card_stabilizer'` * Burnside's lemma `sum_card_fixed_by_eq_card_orbits_mul_card_group` -/ universe u v w variable {α : Type u} {β : Type v} {γ : Type w} open Function open BigOperators namespace MulAction variable [Group α] section QuotientAction open Subgroup MulOpposite QuotientGroup variable (β) [Monoid β] [MulAction β α] (H : Subgroup α) #print MulAction.QuotientAction /- /-- A typeclass for when a `mul_action β α` descends to the quotient `α ⧸ H`. -/ class QuotientAction : Prop where inv_mul_mem : ∀ (b : β) {a a' : α}, a⁻¹ * a' ∈ H → (b • a)⁻¹ * b • a' ∈ H #align mul_action.quotient_action MulAction.QuotientAction -/ #print AddAction.QuotientAction /- /-- A typeclass for when an `add_action β α` descends to the quotient `α ⧸ H`. -/ class AddAction.QuotientAction {α : Type _} (β : Type _) [AddGroup α] [AddMonoid β] [AddAction β α] (H : AddSubgroup α) : Prop where inv_mul_mem : ∀ (b : β) {a a' : α}, -a + a' ∈ H → -(b +ᵥ a) + (b +ᵥ a') ∈ H #align add_action.quotient_action AddAction.QuotientAction -/ attribute [to_additive AddAction.QuotientAction] MulAction.QuotientAction #print MulAction.left_quotientAction /- @[to_additive] instance left_quotientAction : QuotientAction α H := ⟨fun _ _ _ _ => by rwa [smul_eq_mul, smul_eq_mul, mul_inv_rev, mul_assoc, inv_mul_cancel_left]⟩ #align mul_action.left_quotient_action MulAction.left_quotientAction #align add_action.left_quotient_action AddAction.left_quotientAction -/ /- warning: mul_action.right_quotient_action -> MulAction.right_quotientAction is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1), MulAction.QuotientAction.{u1, u1} α (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) (MulOpposite.{u1} α) (Subgroup.setLike.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (fun (_x : Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) => (Subgroup.{u1} α _inst_1) -> (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Equiv.hasCoeToFun.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))) _inst_1 (DivInvMonoid.toMonoid.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) (MulOpposite.{u1} α) (Subgroup.setLike.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (fun (_x : Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) => (Subgroup.{u1} α _inst_1) -> (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Equiv.hasCoeToFun.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))) (Group.toDivInvMonoid.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) (MulOpposite.{u1} α) (Subgroup.setLike.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (fun (_x : Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) => (Subgroup.{u1} α _inst_1) -> (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Equiv.hasCoeToFun.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))) (Subgroup.toGroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (fun (_x : Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) => (Subgroup.{u1} α _inst_1) -> (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Equiv.hasCoeToFun.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))))) (Subgroup.mulAction.{u1, u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1) α (Monoid.toOppositeMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) (coeFn.{succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (fun (_x : Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) => (Subgroup.{u1} α _inst_1) -> (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Equiv.hasCoeToFun.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))) H but is expected to have type forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1), MulAction.QuotientAction.{u1, u1} α (Subtype.{succ u1} (MulOpposite.{u1} α) (fun (x : MulOpposite.{u1} α) => Membership.mem.{u1, u1} (MulOpposite.{u1} α) ((fun ([email protected]._hyg.808 : Subgroup.{u1} α _inst_1) => Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) (Subgroup.normalizer.{u1} α _inst_1 H)) (SetLike.instMembership.{u1, u1} ((fun ([email protected]._hyg.808 : Subgroup.{u1} α _inst_1) => Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) (Subgroup.normalizer.{u1} α _inst_1 H)) (MulOpposite.{u1} α) (Subgroup.instSetLikeSubgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) x (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.{u1} α _inst_1) (fun (a : Subgroup.{u1} α _inst_1) => (fun ([email protected]._hyg.808 : Subgroup.{u1} α _inst_1) => Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) a) (Equiv.instFunLikeEquiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H)))) _inst_1 (Submonoid.toMonoid.{u1} (MulOpposite.{u1} α) (DivInvMonoid.toMonoid.{u1} (MulOpposite.{u1} α) (Group.toDivInvMonoid.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.toSubmonoid.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1) (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.{u1} α _inst_1) (fun (a : Subgroup.{u1} α _inst_1) => (fun ([email protected]._hyg.808 : Subgroup.{u1} α _inst_1) => Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) a) (Equiv.instFunLikeEquiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H)))) (Subgroup.instMulActionSubtypeMemSubgroupInstMembershipInstSetLikeSubgroupToMonoidToMonoidToDivInvMonoidToSubmonoid.{u1, u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1) α (Monoid.toOppositeMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) (FunLike.coe.{succ u1, succ u1, succ u1} (Equiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.{u1} α _inst_1) (fun (_x : Subgroup.{u1} α _inst_1) => (fun ([email protected]._hyg.808 : Subgroup.{u1} α _inst_1) => Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1)) _x) (Equiv.instFunLikeEquiv.{succ u1, succ u1} (Subgroup.{u1} α _inst_1) (Subgroup.{u1} (MulOpposite.{u1} α) (MulOpposite.group.{u1} α _inst_1))) (Subgroup.opposite.{u1} α _inst_1) (Subgroup.normalizer.{u1} α _inst_1 H))) H Case conversion may be inaccurate. Consider using '#align mul_action.right_quotient_action MulAction.right_quotientActionₓ'. -/ @[to_additive] instance right_quotientAction : QuotientAction H.normalizer.opposite H := ⟨fun b c _ _ => by rwa [smul_def, smul_def, smul_eq_mul_unop, smul_eq_mul_unop, mul_inv_rev, ← mul_assoc, mem_normalizer_iff'.mp b.prop, mul_assoc, mul_inv_cancel_left]⟩ #align mul_action.right_quotient_action MulAction.right_quotientAction #align add_action.right_quotient_action AddAction.right_quotientAction #print MulAction.right_quotientAction' /- @[to_additive] instance right_quotientAction' [hH : H.Normal] : QuotientAction αᵐᵒᵖ H := ⟨fun _ _ _ _ => by rwa [smul_eq_mul_unop, smul_eq_mul_unop, mul_inv_rev, mul_assoc, hH.mem_comm_iff, mul_assoc, mul_inv_cancel_right]⟩ #align mul_action.right_quotient_action' MulAction.right_quotientAction' #align add_action.right_quotient_action' AddAction.right_quotientAction' -/ #print MulAction.quotient /- @[to_additive] instance quotient [QuotientAction β H] : MulAction β (α ⧸ H) where smul b := Quotient.map' ((· • ·) b) fun a a' h => leftRel_apply.mpr <| QuotientAction.inv_mul_mem b <| leftRel_apply.mp h one_smul q := Quotient.inductionOn' q fun a => congr_arg Quotient.mk'' (one_smul β a) mul_smul b b' q := Quotient.inductionOn' q fun a => congr_arg Quotient.mk'' (mul_smul b b' a) #align mul_action.quotient MulAction.quotient #align add_action.quotient AddAction.quotient -/ variable {β} #print MulAction.Quotient.smul_mk /- @[simp, to_additive] theorem Quotient.smul_mk [QuotientAction β H] (b : β) (a : α) : (b • QuotientGroup.mk a : α ⧸ H) = QuotientGroup.mk (b • a) := rfl #align mul_action.quotient.smul_mk MulAction.Quotient.smul_mk #align add_action.quotient.vadd_mk AddAction.Quotient.vadd_mk -/ #print MulAction.Quotient.smul_coe /- @[simp, to_additive] theorem Quotient.smul_coe [QuotientAction β H] (b : β) (a : α) : (b • a : α ⧸ H) = ↑(b • a) := rfl #align mul_action.quotient.smul_coe MulAction.Quotient.smul_coe #align add_action.quotient.vadd_coe AddAction.Quotient.vadd_coe -/ #print MulAction.Quotient.mk_smul_out' /- @[simp, to_additive] theorem Quotient.mk_smul_out' [QuotientAction β H] (b : β) (q : α ⧸ H) : QuotientGroup.mk (b • q.out') = b • q := by rw [← quotient.smul_mk, QuotientGroup.out_eq'] #align mul_action.quotient.mk_smul_out' MulAction.Quotient.mk_smul_out' #align add_action.quotient.mk_vadd_out' AddAction.Quotient.mk_vadd_out' -/ #print MulAction.Quotient.coe_smul_out' /- @[simp, to_additive] theorem Quotient.coe_smul_out' [QuotientAction β H] (b : β) (q : α ⧸ H) : ↑(b • q.out') = b • q := Quotient.mk_smul_out' H b q #align mul_action.quotient.coe_smul_out' MulAction.Quotient.coe_smul_out' #align add_action.quotient.coe_vadd_out' AddAction.Quotient.coe_vadd_out' -/ /- warning: quotient_group.out'_conj_pow_minimal_period_mem -> QuotientGroup.out'_conj_pow_minimalPeriod_mem is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1) (a : α) (q : HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H), Membership.Mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.hasMem.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))))) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))))) (Inv.inv.{u1} α (DivInvMonoid.toHasInv.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Quotient.out'.{succ u1} α (QuotientGroup.leftRel.{u1} α _inst_1 H) q)) (HPow.hPow.{u1, 0, u1} α Nat α (instHPow.{u1, 0} α Nat (Monoid.Pow.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)))) a (Function.minimalPeriod.{u1} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (SMul.smul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (MulAction.toHasSmul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (MulAction.quotient.{u1, u1} α α _inst_1 (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Monoid.toMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) H (MulAction.left_quotientAction.{u1} α _inst_1 H))) a) q))) (Quotient.out'.{succ u1} α (QuotientGroup.leftRel.{u1} α _inst_1 H) q)) H but is expected to have type forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1) (a : α) (q : HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H), Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))))) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))))) (Inv.inv.{u1} α (InvOneClass.toInv.{u1} α (DivInvOneMonoid.toInvOneClass.{u1} α (DivisionMonoid.toDivInvOneMonoid.{u1} α (Group.toDivisionMonoid.{u1} α _inst_1)))) (Quotient.out'.{succ u1} α (QuotientGroup.leftRel.{u1} α _inst_1 H) q)) (HPow.hPow.{u1, 0, u1} α Nat α (instHPow.{u1, 0} α Nat (Monoid.Pow.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)))) a (Function.minimalPeriod.{u1} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) ((fun ([email protected]._hyg.853 : α) ([email protected]._hyg.855 : HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) => HSMul.hSMul.{u1, u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (instHSMul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (MulAction.toSMul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (MulAction.quotient.{u1, u1} α α _inst_1 (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Monoid.toMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) H (MulAction.left_quotientAction.{u1} α _inst_1 H)))) [email protected]._hyg.853 [email protected]._hyg.855) a) q))) (Quotient.out'.{succ u1} α (QuotientGroup.leftRel.{u1} α _inst_1 H) q)) H Case conversion may be inaccurate. Consider using '#align quotient_group.out'_conj_pow_minimal_period_mem QuotientGroup.out'_conj_pow_minimalPeriod_memₓ'. -/ theorem QuotientGroup.out'_conj_pow_minimalPeriod_mem (a : α) (q : α ⧸ H) : q.out'⁻¹ * a ^ Function.minimalPeriod ((· • ·) a) q * q.out' ∈ H := by rw [mul_assoc, ← QuotientGroup.eq', QuotientGroup.out_eq', ← smul_eq_mul, quotient.mk_smul_out', eq_comm, pow_smul_eq_iff_minimal_period_dvd] #align quotient_group.out'_conj_pow_minimal_period_mem QuotientGroup.out'_conj_pow_minimalPeriod_mem end QuotientAction open QuotientGroup /- warning: mul_action_hom.to_quotient -> MulActionHom.toQuotient is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1), MulActionHom.{u1, u1, u1} α α (Mul.toSMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))))) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (MulAction.toHasSmul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (MulAction.quotient.{u1, u1} α α _inst_1 (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Monoid.toMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) H (MulAction.left_quotientAction.{u1} α _inst_1 H))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1), MulActionHom.{u1, u1, u1} α α (MulAction.toSMul.{u1, u1} α α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Monoid.toMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)))) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (MulAction.toSMul.{u1, u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (MulAction.quotient.{u1, u1} α α _inst_1 (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Monoid.toMulAction.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))) H (MulAction.left_quotientAction.{u1} α _inst_1 H))) Case conversion may be inaccurate. Consider using '#align mul_action_hom.to_quotient MulActionHom.toQuotientₓ'. -/ /-- The canonical map to the left cosets. -/ def MulActionHom.toQuotient (H : Subgroup α) : α →[α] α ⧸ H := ⟨coe, Quotient.smul_coe H⟩ #align mul_action_hom.to_quotient MulActionHom.toQuotient #print MulActionHom.toQuotient_apply /- @[simp] theorem MulActionHom.toQuotient_apply (H : Subgroup α) (g : α) : MulActionHom.toQuotient H g = g := rfl #align mul_action_hom.to_quotient_apply MulActionHom.toQuotient_apply -/ /- warning: mul_action.mul_left_cosets_comp_subtype_val -> MulAction.mulLeftCosetsCompSubtypeVal is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1) (I : Subgroup.{u1} α _inst_1), MulAction.{u1, u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) I) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) H) (DivInvMonoid.toMonoid.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) I) (Group.toDivInvMonoid.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) I) (Subgroup.toGroup.{u1} α _inst_1 I))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : Group.{u1} α] (H : Subgroup.{u1} α _inst_1) (I : Subgroup.{u1} α _inst_1), MulAction.{u1, u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x I)) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) H) (Submonoid.toMonoid.{u1} α (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) (Subgroup.toSubmonoid.{u1} α _inst_1 I)) Case conversion may be inaccurate. Consider using '#align mul_action.mul_left_cosets_comp_subtype_val MulAction.mulLeftCosetsCompSubtypeValₓ'. -/ @[to_additive] instance mulLeftCosetsCompSubtypeVal (H I : Subgroup α) : MulAction I (α ⧸ H) := MulAction.compHom (α ⧸ H) (Subgroup.subtype I) #align mul_action.mul_left_cosets_comp_subtype_val MulAction.mulLeftCosetsCompSubtypeVal #align add_action.add_left_cosets_comp_subtype_val AddAction.addLeftCosetsCompSubtypeVal variable (α) {β} [MulAction α β] (x : β) #print MulAction.ofQuotientStabilizer /- /-- The canonical map from the quotient of the stabilizer to the set. -/ @[to_additive "The canonical map from the quotient of the stabilizer to the set. "] def ofQuotientStabilizer (g : α ⧸ MulAction.stabilizer α x) : β := Quotient.liftOn' g (· • x) fun g1 g2 H => calc g1 • x = g1 • (g1⁻¹ * g2) • x := congr_arg _ (leftRel_apply.mp H).symm _ = g2 • x := by rw [smul_smul, mul_inv_cancel_left] #align mul_action.of_quotient_stabilizer MulAction.ofQuotientStabilizer #align add_action.of_quotient_stabilizer AddAction.ofQuotientStabilizer -/ #print MulAction.ofQuotientStabilizer_mk /- @[simp, to_additive] theorem ofQuotientStabilizer_mk (g : α) : ofQuotientStabilizer α x (QuotientGroup.mk g) = g • x := rfl #align mul_action.of_quotient_stabilizer_mk MulAction.ofQuotientStabilizer_mk #align add_action.of_quotient_stabilizer_mk AddAction.ofQuotientStabilizer_mk -/ #print MulAction.ofQuotientStabilizer_mem_orbit /- @[to_additive] theorem ofQuotientStabilizer_mem_orbit (g) : ofQuotientStabilizer α x g ∈ orbit α x := Quotient.inductionOn' g fun g => ⟨g, rfl⟩ #align mul_action.of_quotient_stabilizer_mem_orbit MulAction.ofQuotientStabilizer_mem_orbit #align add_action.of_quotient_stabilizer_mem_orbit AddAction.ofQuotientStabilizer_mem_orbit -/ #print MulAction.ofQuotientStabilizer_smul /- @[to_additive] theorem ofQuotientStabilizer_smul (g : α) (g' : α ⧸ MulAction.stabilizer α x) : ofQuotientStabilizer α x (g • g') = g • ofQuotientStabilizer α x g' := Quotient.inductionOn' g' fun _ => mul_smul _ _ _ #align mul_action.of_quotient_stabilizer_smul MulAction.ofQuotientStabilizer_smul #align add_action.of_quotient_stabilizer_vadd AddAction.ofQuotientStabilizer_vadd -/ #print MulAction.injective_ofQuotientStabilizer /- @[to_additive] theorem injective_ofQuotientStabilizer : Function.Injective (ofQuotientStabilizer α x) := fun y₁ y₂ => Quotient.inductionOn₂' y₁ y₂ fun g₁ g₂ (H : g₁ • x = g₂ • x) => Quotient.sound' <| by rw [left_rel_apply] show (g₁⁻¹ * g₂) • x = x rw [mul_smul, ← H, inv_smul_smul] #align mul_action.injective_of_quotient_stabilizer MulAction.injective_ofQuotientStabilizer #align add_action.injective_of_quotient_stabilizer AddAction.injective_ofQuotientStabilizer -/ #print MulAction.orbitEquivQuotientStabilizer /- /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] noncomputable def orbitEquivQuotientStabilizer (b : β) : orbit α b ≃ α ⧸ stabilizer α b := Equiv.symm <| Equiv.ofBijective (fun g => ⟨ofQuotientStabilizer α b g, ofQuotientStabilizer_mem_orbit α b g⟩) ⟨fun x y hxy => injective_ofQuotientStabilizer α b (by convert congr_arg Subtype.val hxy), fun ⟨b, ⟨g, hgb⟩⟩ => ⟨g, Subtype.eq hgb⟩⟩ #align mul_action.orbit_equiv_quotient_stabilizer MulAction.orbitEquivQuotientStabilizer #align add_action.orbit_equiv_quotient_stabilizer AddAction.orbitEquivQuotientStabilizer -/ /- warning: mul_action.orbit_prod_stabilizer_equiv_group -> MulAction.orbitProdStabilizerEquivGroup is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β), Equiv.{max (succ u2) (succ u1), succ u1} (Prod.{u2, u1} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b))) α but is expected to have type forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β), Equiv.{max (succ u1) (succ u2), succ u1} (Prod.{u2, u1} (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)))) α Case conversion may be inaccurate. Consider using '#align mul_action.orbit_prod_stabilizer_equiv_group MulAction.orbitProdStabilizerEquivGroupₓ'. -/ /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] noncomputable def orbitProdStabilizerEquivGroup (b : β) : orbit α b × stabilizer α b ≃ α := (Equiv.prodCongr (orbitEquivQuotientStabilizer α _) (Equiv.refl _)).trans Subgroup.groupEquivQuotientProdSubgroup.symm #align mul_action.orbit_prod_stabilizer_equiv_group MulAction.orbitProdStabilizerEquivGroup #align add_action.orbit_sum_stabilizer_equiv_add_group AddAction.orbitSumStabilizerEquivAddGroup /- warning: mul_action.card_orbit_mul_card_stabilizer_eq_card_group -> MulAction.card_orbit_mul_card_stabilizer_eq_card_group is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β) [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))] [_inst_5 : Fintype.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b))], Eq.{1} Nat (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat Nat.hasMul) (Fintype.card.{u2} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) _inst_4) (Fintype.card.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) _inst_5)) (Fintype.card.{u1} α _inst_3) but is expected to have type forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β) [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))] [_inst_5 : Fintype.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)))], Eq.{1} Nat (HMul.hMul.{0, 0, 0} Nat Nat Nat (instHMul.{0} Nat instMulNat) (Fintype.card.{u2} (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) _inst_4) (Fintype.card.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b))) _inst_5)) (Fintype.card.{u1} α _inst_3) Case conversion may be inaccurate. Consider using '#align mul_action.card_orbit_mul_card_stabilizer_eq_card_group MulAction.card_orbit_mul_card_stabilizer_eq_card_groupₓ'. -/ /-- Orbit-stabilizer theorem. -/ @[to_additive "Orbit-stabilizer theorem."] theorem card_orbit_mul_card_stabilizer_eq_card_group (b : β) [Fintype α] [Fintype <| orbit α b] [Fintype <| stabilizer α b] : Fintype.card (orbit α b) * Fintype.card (stabilizer α b) = Fintype.card α := by rw [← Fintype.card_prod, Fintype.card_congr (orbit_prod_stabilizer_equiv_group α b)] #align mul_action.card_orbit_mul_card_stabilizer_eq_card_group MulAction.card_orbit_mul_card_stabilizer_eq_card_group #align add_action.card_orbit_add_card_stabilizer_eq_card_add_group AddAction.card_orbit_add_card_stabilizer_eq_card_addGroup /- warning: mul_action.orbit_equiv_quotient_stabilizer_symm_apply -> MulAction.orbitEquivQuotientStabilizer_symm_apply is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β) (a : α), Eq.{succ u2} β ((fun (a : Type.{u2}) (b : Type.{u2}) [self : HasLiftT.{succ u2, succ u2} a b] => self.0) (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) β (HasLiftT.mk.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) β (CoeTCₓ.coe.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) β (coeBase.{succ u2, succ u2} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) β (coeSubtype.{succ u2} β (fun (x : β) => Membership.Mem.{u2, u2} β (Set.{u2} β) (Set.hasMem.{u2} β) x (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)))))) (coeFn.{max 1 (max (succ u1) (succ u2)) (succ u2) (succ u1), max (succ u1) (succ u2)} (Equiv.{succ u1, succ u2} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) (fun (_x : Equiv.{succ u1, succ u2} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) => (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) -> (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) (Equiv.hasCoeToFun.{succ u1, succ u2} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) (Equiv.symm.{succ u2, succ u1} (coeSort.{succ u2, succ (succ u2)} (Set.{u2} β) Type.{u2} (Set.hasCoeToSort.{u2} β) (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (MulAction.orbitEquivQuotientStabilizer.{u1, u2} α β _inst_1 _inst_2 b)) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (HasLiftT.mk.{succ u1, succ u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (CoeTCₓ.coe.{succ u1, succ u1} α (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (QuotientGroup.HasQuotient.Quotient.hasCoeT.{u1} α _inst_1 (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)))) a))) (SMul.smul.{u1, u2} α β (MulAction.toHasSmul.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2) a b) but is expected to have type forall (α : Type.{u1}) {β : Type.{u2}} [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] (b : β) (a : α), Eq.{succ u2} β (Subtype.val.{succ u2} β (fun (x : β) => Membership.mem.{u2, u2} β (Set.{u2} β) (Set.instMembershipSet.{u2} β) x (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) (FunLike.coe.{max (succ u1) (succ u2), succ u1, succ u2} (Equiv.{succ u1, succ u2} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (fun (_x : HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) => (fun ([email protected]._hyg.808 : HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) => Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) _x) (Equiv.instFunLikeEquiv.{succ u1, succ u2} (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b))) (Equiv.symm.{succ u2, succ u1} (Set.Elem.{u2} β (MulAction.orbit.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2 b)) (HasQuotient.Quotient.{u1, u1} α (Subgroup.{u1} α _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} α _inst_1) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (MulAction.orbitEquivQuotientStabilizer.{u1, u2} α β _inst_1 _inst_2 b)) (QuotientGroup.mk.{u1} α _inst_1 (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b) a))) (HSMul.hSMul.{u1, u2, u2} α β β (instHSMul.{u1, u2} α β (MulAction.toSMul.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1)) _inst_2)) a b) Case conversion may be inaccurate. Consider using '#align mul_action.orbit_equiv_quotient_stabilizer_symm_apply MulAction.orbitEquivQuotientStabilizer_symm_applyₓ'. -/ @[simp, to_additive] theorem orbitEquivQuotientStabilizer_symm_apply (b : β) (a : α) : ((orbitEquivQuotientStabilizer α b).symm a : β) = a • b := rfl #align mul_action.orbit_equiv_quotient_stabilizer_symm_apply MulAction.orbitEquivQuotientStabilizer_symm_apply #align add_action.orbit_equiv_quotient_stabilizer_symm_apply AddAction.orbitEquivQuotientStabilizer_symm_apply /- warning: mul_action.stabilizer_quotient -> MulAction.stabilizer_quotient is a dubious translation: lean 3 declaration is forall {G : Type.{u1}} [_inst_3 : Group.{u1} G] (H : Subgroup.{u1} G _inst_3), Eq.{succ u1} (Subgroup.{u1} G _inst_3) (MulAction.stabilizer.{u1, u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_3) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_3) H) _inst_3 (MulAction.quotient.{u1, u1} G G _inst_3 (DivInvMonoid.toMonoid.{u1} G (Group.toDivInvMonoid.{u1} G _inst_3)) (Monoid.toMulAction.{u1} G (DivInvMonoid.toMonoid.{u1} G (Group.toDivInvMonoid.{u1} G _inst_3))) H (MulAction.left_quotientAction.{u1} G _inst_3 H)) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_3) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_3) H) (HasLiftT.mk.{succ u1, succ u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_3) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_3) H) (CoeTCₓ.coe.{succ u1, succ u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_3) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_3) H) (QuotientGroup.HasQuotient.Quotient.hasCoeT.{u1} G _inst_3 H))) (OfNat.ofNat.{u1} G 1 (OfNat.mk.{u1} G 1 (One.one.{u1} G (MulOneClass.toHasOne.{u1} G (Monoid.toMulOneClass.{u1} G (DivInvMonoid.toMonoid.{u1} G (Group.toDivInvMonoid.{u1} G _inst_3))))))))) H but is expected to have type forall {G : Type.{u1}} [_inst_3 : Group.{u1} G] (H : Subgroup.{u1} G _inst_3), Eq.{succ u1} (Subgroup.{u1} G _inst_3) (MulAction.stabilizer.{u1, u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_3) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_3) H) _inst_3 (MulAction.quotient.{u1, u1} G G _inst_3 (DivInvMonoid.toMonoid.{u1} G (Group.toDivInvMonoid.{u1} G _inst_3)) (Monoid.toMulAction.{u1} G (DivInvMonoid.toMonoid.{u1} G (Group.toDivInvMonoid.{u1} G _inst_3))) H (MulAction.left_quotientAction.{u1} G _inst_3 H)) (QuotientGroup.mk.{u1} G _inst_3 H (OfNat.ofNat.{u1} G 1 (One.toOfNat1.{u1} G (InvOneClass.toOne.{u1} G (DivInvOneMonoid.toInvOneClass.{u1} G (DivisionMonoid.toDivInvOneMonoid.{u1} G (Group.toDivisionMonoid.{u1} G _inst_3)))))))) H Case conversion may be inaccurate. Consider using '#align mul_action.stabilizer_quotient MulAction.stabilizer_quotientₓ'. -/ @[simp, to_additive] theorem stabilizer_quotient {G} [Group G] (H : Subgroup G) : MulAction.stabilizer G ((1 : G) : G ⧸ H) = H := by ext simp [QuotientGroup.eq] #align mul_action.stabilizer_quotient MulAction.stabilizer_quotient #align add_action.stabilizer_quotient AddAction.stabilizer_quotient variable (β) -- mathport name: exprΩ local notation "Ω" => Quotient <| orbitRel α β #print MulAction.selfEquivSigmaOrbitsQuotientStabilizer' /- /-- **Class formula** : given `G` a group acting on `X` and `φ` a function mapping each orbit of `X` under this action (that is, each element of the quotient of `X` by the relation `orbit_rel G X`) to an element in this orbit, this gives a (noncomputable) bijection between `X` and the disjoint union of `G/Stab(φ(ω))` over all orbits `ω`. In most cases you'll want `φ` to be `quotient.out'`, so we provide `mul_action.self_equiv_sigma_orbits_quotient_stabilizer` as a special case. -/ @[to_additive "**Class formula** : given `G` an additive group acting on `X` and `φ` a function\nmapping each orbit of `X` under this action (that is, each element of the quotient of `X` by the\nrelation `orbit_rel G X`) to an element in this orbit, this gives a (noncomputable) bijection\nbetween `X` and the disjoint union of `G/Stab(φ(ω))` over all orbits `ω`. In most cases you'll want\n`φ` to be `quotient.out'`, so we provide `add_action.self_equiv_sigma_orbits_quotient_stabilizer`\nas a special case. "] noncomputable def selfEquivSigmaOrbitsQuotientStabilizer' {φ : Ω → β} (hφ : LeftInverse Quotient.mk'' φ) : β ≃ Σω : Ω, α ⧸ stabilizer α (φ ω) := calc β ≃ Σω : Ω, orbitRel.Quotient.orbit ω := selfEquivSigmaOrbits' α β _ ≃ Σω : Ω, α ⧸ stabilizer α (φ ω) := Equiv.sigmaCongrRight fun ω => (Equiv.Set.ofEq <| orbitRel.Quotient.orbit_eq_orbit_out _ hφ).trans <| orbitEquivQuotientStabilizer α (φ ω) #align mul_action.self_equiv_sigma_orbits_quotient_stabilizer' MulAction.selfEquivSigmaOrbitsQuotientStabilizer' #align add_action.self_equiv_sigma_orbits_quotient_stabilizer' AddAction.selfEquivSigmaOrbitsQuotientStabilizer' -/ /- warning: mul_action.card_eq_sum_card_group_div_card_stabilizer' -> MulAction.card_eq_sum_card_group_div_card_stabilizer' is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) (β : Type.{u2}) [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} β] [_inst_5 : Fintype.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2))] [_inst_6 : forall (b : β), Fintype.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b))] {φ : (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) -> β}, (Function.LeftInverse.{succ u2, succ u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) β (Quotient.mk''.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) φ) -> (Eq.{1} Nat (Fintype.card.{u2} β _inst_4) (Finset.sum.{0, u2} Nat (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) Nat.addCommMonoid (Finset.univ.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) _inst_5) (fun (ω : Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) (Fintype.card.{u1} α _inst_3) (Fintype.card.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 (φ ω))) (_inst_6 (φ ω)))))) but is expected to have type forall (α : Type.{u1}) (β : Type.{u2}) [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} β] [_inst_5 : Fintype.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2))] [_inst_6 : forall (b : β), Fintype.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)))] {φ : (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) -> β}, (Function.LeftInverse.{succ u2, succ u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) β (Quotient.mk''.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) φ) -> (Eq.{1} Nat (Fintype.card.{u2} β _inst_4) (Finset.sum.{0, u2} Nat (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) Nat.addCommMonoid (Finset.univ.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) _inst_5) (fun (ω : Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (Fintype.card.{u1} α _inst_3) (Fintype.card.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 (φ ω)))) (_inst_6 (φ ω)))))) Case conversion may be inaccurate. Consider using '#align mul_action.card_eq_sum_card_group_div_card_stabilizer' MulAction.card_eq_sum_card_group_div_card_stabilizer'ₓ'. -/ /-- **Class formula** for a finite group acting on a finite type. See `mul_action.card_eq_sum_card_group_div_card_stabilizer` for a specialized version using `quotient.out'`. -/ @[to_additive "**Class formula** for a finite group acting on a finite type. See\n`add_action.card_eq_sum_card_add_group_div_card_stabilizer` for a specialized version using\n`quotient.out'`."] theorem card_eq_sum_card_group_div_card_stabilizer' [Fintype α] [Fintype β] [Fintype Ω] [∀ b : β, Fintype <| stabilizer α b] {φ : Ω → β} (hφ : LeftInverse Quotient.mk'' φ) : Fintype.card β = ∑ ω : Ω, Fintype.card α / Fintype.card (stabilizer α (φ ω)) := by classical have : ∀ ω : Ω, Fintype.card α / Fintype.card ↥(stabilizer α (φ ω)) = Fintype.card (α ⧸ stabilizer α (φ ω)) := by intro ω rw [Fintype.card_congr (@Subgroup.groupEquivQuotientProdSubgroup α _ (stabilizer α <| φ ω)), Fintype.card_prod, Nat.mul_div_cancel] exact fintype.card_pos_iff.mpr (by infer_instance) simp_rw [this, ← Fintype.card_sigma, Fintype.card_congr (self_equiv_sigma_orbits_quotient_stabilizer' α β hφ)] #align mul_action.card_eq_sum_card_group_div_card_stabilizer' MulAction.card_eq_sum_card_group_div_card_stabilizer' #align add_action.card_eq_sum_card_add_group_sub_card_stabilizer' AddAction.card_eq_sum_card_addGroup_sub_card_stabilizer' #print MulAction.selfEquivSigmaOrbitsQuotientStabilizer /- /-- **Class formula**. This is a special case of `mul_action.self_equiv_sigma_orbits_quotient_stabilizer'` with `φ = quotient.out'`. -/ @[to_additive "**Class formula**. This is a special case of\n`add_action.self_equiv_sigma_orbits_quotient_stabilizer'` with `φ = quotient.out'`. "] noncomputable def selfEquivSigmaOrbitsQuotientStabilizer : β ≃ Σω : Ω, α ⧸ stabilizer α ω.out' := selfEquivSigmaOrbitsQuotientStabilizer' α β Quotient.out_eq' #align mul_action.self_equiv_sigma_orbits_quotient_stabilizer MulAction.selfEquivSigmaOrbitsQuotientStabilizer #align add_action.self_equiv_sigma_orbits_quotient_stabilizer AddAction.selfEquivSigmaOrbitsQuotientStabilizer -/ /- warning: mul_action.card_eq_sum_card_group_div_card_stabilizer -> MulAction.card_eq_sum_card_group_div_card_stabilizer is a dubious translation: lean 3 declaration is forall (α : Type.{u1}) (β : Type.{u2}) [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} β] [_inst_5 : Fintype.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2))] [_inst_6 : forall (b : β), Fintype.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b))], Eq.{1} Nat (Fintype.card.{u2} β _inst_4) (Finset.sum.{0, u2} Nat (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) Nat.addCommMonoid (Finset.univ.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) _inst_5) (fun (ω : Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.hasDiv) (Fintype.card.{u1} α _inst_3) (Fintype.card.{u1} (coeSort.{succ u1, succ (succ u1)} (Subgroup.{u1} α _inst_1) Type.{u1} (SetLike.hasCoeToSort.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.setLike.{u1} α _inst_1)) (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 (Quotient.out'.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2) ω))) (_inst_6 (Quotient.out'.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2) ω))))) but is expected to have type forall (α : Type.{u1}) (β : Type.{u2}) [_inst_1 : Group.{u1} α] [_inst_2 : MulAction.{u1, u2} α β (DivInvMonoid.toMonoid.{u1} α (Group.toDivInvMonoid.{u1} α _inst_1))] [_inst_3 : Fintype.{u1} α] [_inst_4 : Fintype.{u2} β] [_inst_5 : Fintype.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2))] [_inst_6 : forall (b : β), Fintype.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 b)))], Eq.{1} Nat (Fintype.card.{u2} β _inst_4) (Finset.sum.{0, u2} Nat (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) Nat.addCommMonoid (Finset.univ.{u2} (Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) _inst_5) (fun (ω : Quotient.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2)) => HDiv.hDiv.{0, 0, 0} Nat Nat Nat (instHDiv.{0} Nat Nat.instDivNat) (Fintype.card.{u1} α _inst_3) (Fintype.card.{u1} (Subtype.{succ u1} α (fun (x : α) => Membership.mem.{u1, u1} α (Subgroup.{u1} α _inst_1) (SetLike.instMembership.{u1, u1} (Subgroup.{u1} α _inst_1) α (Subgroup.instSetLikeSubgroup.{u1} α _inst_1)) x (MulAction.stabilizer.{u1, u2} α β _inst_1 _inst_2 (Quotient.out'.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2) ω)))) (_inst_6 (Quotient.out'.{succ u2} β (MulAction.orbitRel.{u1, u2} α β _inst_1 _inst_2) ω))))) Case conversion may be inaccurate. Consider using '#align mul_action.card_eq_sum_card_group_div_card_stabilizer MulAction.card_eq_sum_card_group_div_card_stabilizerₓ'. -/ /-- **Class formula** for a finite group acting on a finite type. -/ @[to_additive "**Class formula** for a finite group acting on a finite type."] theorem card_eq_sum_card_group_div_card_stabilizer [Fintype α] [Fintype β] [Fintype Ω] [∀ b : β, Fintype <| stabilizer α b] : Fintype.card β = ∑ ω : Ω, Fintype.card α / Fintype.card (stabilizer α ω.out') := card_eq_sum_card_group_div_card_stabilizer' α β Quotient.out_eq' #align mul_action.card_eq_sum_card_group_div_card_stabilizer MulAction.card_eq_sum_card_group_div_card_stabilizer #align add_action.card_eq_sum_card_add_group_sub_card_stabilizer AddAction.card_eq_sum_card_addGroup_sub_card_stabilizer #print MulAction.sigmaFixedByEquivOrbitsProdGroup /- /-- **Burnside's lemma** : a (noncomputable) bijection between the disjoint union of all `{x ∈ X | g • x = x}` for `g ∈ G` and the product `G × X/G`, where `G` is a group acting on `X` and `X/G`denotes the quotient of `X` by the relation `orbit_rel G X`. -/ @[to_additive "**Burnside's lemma** : a (noncomputable) bijection between the disjoint union of all\n`{x ∈ X | g • x = x}` for `g ∈ G` and the product `G × X/G`, where `G` is an additive group acting\non `X` and `X/G`denotes the quotient of `X` by the relation `orbit_rel G X`. "] noncomputable def sigmaFixedByEquivOrbitsProdGroup : (Σa : α, fixedBy α β a) ≃ Ω × α := calc (Σa : α, fixedBy α β a) ≃ { ab : α × β // ab.1 • ab.2 = ab.2 } := (Equiv.subtypeProdEquivSigmaSubtype _).symm _ ≃ { ba : β × α // ba.2 • ba.1 = ba.1 } := ((Equiv.prodComm α β).subtypeEquiv fun ab => Iff.rfl) _ ≃ Σb : β, stabilizer α b := (Equiv.subtypeProdEquivSigmaSubtype fun (b : β) a => a ∈ stabilizer α b) _ ≃ Σωb : Σω : Ω, orbit α ω.out', stabilizer α (ωb.2 : β) := (selfEquivSigmaOrbits α β).sigmaCongrLeft' _ ≃ Σω : Ω, Σb : orbit α ω.out', stabilizer α (b : β) := (Equiv.sigmaAssoc fun (ω : Ω) (b : orbit α ω.out') => stabilizer α (b : β)) _ ≃ Σω : Ω, Σb : orbit α ω.out', stabilizer α ω.out' := (Equiv.sigmaCongrRight fun ω => Equiv.sigmaCongrRight fun ⟨b, hb⟩ => (stabilizerEquivStabilizerOfOrbitRel hb).toEquiv) _ ≃ Σω : Ω, orbit α ω.out' × stabilizer α ω.out' := (Equiv.sigmaCongrRight fun ω => Equiv.sigmaEquivProd _ _) _ ≃ Σω : Ω, α := (Equiv.sigmaCongrRight fun ω => orbitProdStabilizerEquivGroup α ω.out') _ ≃ Ω × α := Equiv.sigmaEquivProd Ω α #align mul_action.sigma_fixed_by_equiv_orbits_prod_group MulAction.sigmaFixedByEquivOrbitsProdGroup #align add_action.sigma_fixed_by_equiv_orbits_sum_add_group AddAction.sigmaFixedByEquivOrbitsSumAddGroup -/ #print MulAction.sum_card_fixedBy_eq_card_orbits_mul_card_group /- /-- **Burnside's lemma** : given a finite group `G` acting on a set `X`, the average number of elements fixed by each `g ∈ G` is the number of orbits. -/ @[to_additive "**Burnside's lemma** : given a finite additive group `G` acting on a set `X`,\nthe average number of elements fixed by each `g ∈ G` is the number of orbits. "] theorem sum_card_fixedBy_eq_card_orbits_mul_card_group [Fintype α] [∀ a, Fintype <| fixedBy α β a] [Fintype Ω] : (∑ a : α, Fintype.card (fixedBy α β a)) = Fintype.card Ω * Fintype.card α := by rw [← Fintype.card_prod, ← Fintype.card_sigma, Fintype.card_congr (sigma_fixed_by_equiv_orbits_prod_group α β)] #align mul_action.sum_card_fixed_by_eq_card_orbits_mul_card_group MulAction.sum_card_fixedBy_eq_card_orbits_mul_card_group #align add_action.sum_card_fixed_by_eq_card_orbits_add_card_add_group AddAction.sum_card_fixedBy_eq_card_orbits_add_card_addGroup -/ #print MulAction.isPretransitive_quotient /- @[to_additive] instance isPretransitive_quotient (G) [Group G] (H : Subgroup G) : IsPretransitive G (G ⧸ H) where exists_smul_eq := by rintro ⟨x⟩ ⟨y⟩ refine' ⟨y * x⁻¹, quotient_group.eq.mpr _⟩ simp only [smul_eq_mul, H.one_mem, mul_left_inv, inv_mul_cancel_right] #align mul_action.is_pretransitive_quotient MulAction.isPretransitive_quotient #align add_action.is_pretransitive_quotient AddAction.isPretransitive_quotient -/ end MulAction namespace Subgroup variable {G : Type _} [Group G] (H : Subgroup G) #print Subgroup.normalCore_eq_ker /- theorem normalCore_eq_ker : H.normalCore = (MulAction.toPermHom G (G ⧸ H)).ker := by refine' le_antisymm (fun g hg => Equiv.Perm.ext fun q => QuotientGroup.induction_on q fun g' => (MulAction.Quotient.smul_mk H g g').trans (quotient_group.eq.mpr _)) (subgroup.normal_le_normal_core.mpr fun g hg => _) · rw [smul_eq_mul, mul_inv_rev, ← inv_inv g', inv_inv] exact H.normal_core.inv_mem hg g'⁻¹ · rw [← H.inv_mem_iff, ← mul_one g⁻¹, ← QuotientGroup.eq, ← mul_one g] exact (MulAction.Quotient.smul_mk H g 1).symm.trans (equiv.perm.ext_iff.mp hg (1 : G)) #align subgroup.normal_core_eq_ker Subgroup.normalCore_eq_ker -/ open QuotientGroup #print Subgroup.quotientCentralizerEmbedding /- /-- Cosets of the centralizer of an element embed into the set of commutators. -/ noncomputable def quotientCentralizerEmbedding (g : G) : G ⧸ centralizer (zpowers (g : G)) ↪ commutatorSet G := ((MulAction.orbitEquivQuotientStabilizer (ConjAct G) g).trans (quotientEquivOfEq (ConjAct.stabilizer_eq_centralizer g))).symm.toEmbedding.trans ⟨fun x => ⟨x * g⁻¹, let ⟨_, x, rfl⟩ := x ⟨x, g, rfl⟩⟩, fun x y => Subtype.ext ∘ mul_right_cancel ∘ Subtype.ext_iff.mp⟩ #align subgroup.quotient_centralizer_embedding Subgroup.quotientCentralizerEmbedding -/ #print Subgroup.quotientCentralizerEmbedding_apply /- theorem quotientCentralizerEmbedding_apply (g : G) (x : G) : quotientCentralizerEmbedding g x = ⟨⁅x, g⁆, x, g, rfl⟩ := rfl #align subgroup.quotient_centralizer_embedding_apply Subgroup.quotientCentralizerEmbedding_apply -/ /- warning: subgroup.quotient_center_embedding -> Subgroup.quotientCenterEmbedding is a dubious translation: lean 3 declaration is forall {G : Type.{u1}} [_inst_1 : Group.{u1} G] {S : Set.{u1} G}, (Eq.{succ u1} (Subgroup.{u1} G _inst_1) (Subgroup.closure.{u1} G _inst_1 S) (Top.top.{u1} (Subgroup.{u1} G _inst_1) (Subgroup.hasTop.{u1} G _inst_1))) -> (Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1)))) but is expected to have type forall {G : Type.{u1}} [_inst_1 : Group.{u1} G] {S : Set.{u1} G}, (Eq.{succ u1} (Subgroup.{u1} G _inst_1) (Subgroup.closure.{u1} G _inst_1 S) (Top.top.{u1} (Subgroup.{u1} G _inst_1) (Subgroup.instTopSubgroup.{u1} G _inst_1))) -> (Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1)))) Case conversion may be inaccurate. Consider using '#align subgroup.quotient_center_embedding Subgroup.quotientCenterEmbeddingₓ'. -/ /-- If `G` is generated by `S`, then the quotient by the center embeds into `S`-indexed sequences of commutators. -/ noncomputable def quotientCenterEmbedding {S : Set G} (hS : closure S = ⊤) : G ⧸ center G ↪ S → commutatorSet G := (quotientEquivOfEq (center_eq_infi' S hS)).toEmbedding.trans ((quotientInfᵢEmbedding _).trans (Function.Embedding.piCongrRight fun g => quotientCentralizerEmbedding g)) #align subgroup.quotient_center_embedding Subgroup.quotientCenterEmbedding /- warning: subgroup.quotient_center_embedding_apply -> Subgroup.quotientCenterEmbedding_apply is a dubious translation: lean 3 declaration is forall {G : Type.{u1}} [_inst_1 : Group.{u1} G] {S : Set.{u1} G} (hS : Eq.{succ u1} (Subgroup.{u1} G _inst_1) (Subgroup.closure.{u1} G _inst_1 S) (Top.top.{u1} (Subgroup.{u1} G _inst_1) (Subgroup.hasTop.{u1} G _inst_1))) (g : G) (s : coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S), Eq.{succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1)) (coeFn.{succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1)))) (fun (_x : Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1)))) => (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1))) (Function.Embedding.hasCoeToFun.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) -> (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) (commutatorSet.{u1} G _inst_1)))) (Subgroup.quotientCenterEmbedding.{u1} G _inst_1 S hS) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) (HasLiftT.mk.{succ u1, succ u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) (CoeTCₓ.coe.{succ u1, succ u1} G (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.Subgroup.hasQuotient.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) (QuotientGroup.HasQuotient.Quotient.hasCoeT.{u1} G _inst_1 (Subgroup.center.{u1} G _inst_1)))) g) s) (Subtype.mk.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x (commutatorSet.{u1} G _inst_1)) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (HasLiftT.mk.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (CoeTCₓ.coe.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeBase.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeSubtype.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x S))))) s)) (Exists.intro.{succ u1} G (fun (g₁ : G) => Exists.{succ u1} G (fun (g₂ : G) => Eq.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g₁ g₂) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (HasLiftT.mk.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (CoeTCₓ.coe.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeBase.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeSubtype.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x S))))) s)))) g (Exists.intro.{succ u1} G (fun (g₂ : G) => Eq.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g g₂) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (HasLiftT.mk.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (CoeTCₓ.coe.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeBase.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeSubtype.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x S))))) s))) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (HasLiftT.mk.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (CoeTCₓ.coe.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeBase.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeSubtype.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x S))))) s) (rfl.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (HasLiftT.mk.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (CoeTCₓ.coe.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeBase.{succ u1, succ u1} (coeSort.{succ u1, succ (succ u1)} (Set.{u1} G) Type.{u1} (Set.hasCoeToSort.{u1} G) S) G (coeSubtype.{succ u1} G (fun (x : G) => Membership.Mem.{u1, u1} G (Set.{u1} G) (Set.hasMem.{u1} G) x S))))) s)))))) but is expected to have type forall {G : Type.{u1}} [_inst_1 : Group.{u1} G] {S : Set.{u1} G} (hS : Eq.{succ u1} (Subgroup.{u1} G _inst_1) (Subgroup.closure.{u1} G _inst_1 S) (Top.top.{u1} (Subgroup.{u1} G _inst_1) (Subgroup.instTopSubgroup.{u1} G _inst_1))) (g : G) (s : Set.Elem.{u1} G S), Eq.{succ u1} (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1)) (FunLike.coe.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1)))) (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) (fun (_x : HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) => (fun ([email protected]._hyg.19 : HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) => (Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1))) _x) (EmbeddingLike.toFunLike.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1)))) (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1))) (Function.instEmbeddingLikeEmbedding.{succ u1, succ u1} (HasQuotient.Quotient.{u1, u1} G (Subgroup.{u1} G _inst_1) (QuotientGroup.instHasQuotientSubgroup.{u1} G _inst_1) (Subgroup.center.{u1} G _inst_1)) ((Set.Elem.{u1} G S) -> (Set.Elem.{u1} G (commutatorSet.{u1} G _inst_1))))) (Subgroup.quotientCenterEmbedding.{u1} G _inst_1 S hS) (QuotientGroup.mk.{u1} G _inst_1 (Subgroup.center.{u1} G _inst_1) g) s) (Subtype.mk.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x (commutatorSet.{u1} G _inst_1)) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g (Subtype.val.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x S) s)) (Exists.intro.{succ u1} G (fun (g₁ : G) => Exists.{succ u1} G (fun (g₂ : G) => Eq.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g₁ g₂) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g (Subtype.val.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x S) s)))) g (Exists.intro.{succ u1} G (fun (g₂ : G) => Eq.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g g₂) (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g (Subtype.val.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x S) s))) (Subtype.val.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x S) s) (rfl.{succ u1} G (Bracket.bracket.{u1, u1} G G (commutatorElement.{u1} G _inst_1) g (Subtype.val.{succ u1} G (fun (x : G) => Membership.mem.{u1, u1} G (Set.{u1} G) (Set.instMembershipSet.{u1} G) x S) s)))))) Case conversion may be inaccurate. Consider using '#align subgroup.quotient_center_embedding_apply Subgroup.quotientCenterEmbedding_applyₓ'. -/ theorem quotientCenterEmbedding_apply {S : Set G} (hS : closure S = ⊤) (g : G) (s : S) : quotientCenterEmbedding hS g s = ⟨⁅g, s⁆, g, s, rfl⟩ := rfl #align subgroup.quotient_center_embedding_apply Subgroup.quotientCenterEmbedding_apply end Subgroup
function val=tanDerivVal(z,n) %%TANDERIVVAL Return the value of the nth derivative of tan(x) with respect % to x evaluated at x=z. % %INPUTS: z A matrix of real or complex values at which the nth derivative % of the tangent function is desired. % n The number of derivatives to take. n>=0. % %OUTPUTS: val The value of the nth derivative of the tangent function taken % at all of the points in z. val has the same dimensions as z. % %This function implements the algorithm of [1]. % %REFERENCES: %[1] M. E. Hoffman, "Derivative polynomials for tangent and secant," The % American Mathematical Monthly, vol. 102, no. 1, pp. 23-30, Jan. 1995. % %October 2016 David F. Crouse, Naval Research Laboratory, Washington D.C. %(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. numEls=numel(z); val=zeros(size(z)); for curEl=1:numEls x=z(curEl); u=tan(x); P=zeros(n+1,1); P(1)=u; %The loop implements Equation 5. for k=1:n sumVal=0; for i=0:(k-1) sumVal=sumVal+binomial(k-1,i)*P(i+1)*P(k-1-i+1); end if(k==1) sumVal=sumVal+1; end P(k+1)=sumVal; end val(curEl)=P(end); end end %LICENSE: % %The source code is in the public domain and not licensed or under %copyright. The information and software may be used freely by the public. %As required by 17 U.S.C. 403, third parties producing copyrighted works %consisting predominantly of the material produced by U.S. government %agencies must provide notice with such work(s) identifying the U.S. %Government material incorporated and stating that such material is not %subject to copyright protection. % %Derived works shall not identify themselves in a manner that implies an %endorsement by or an affiliation with the Naval Research Laboratory. % %RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE %SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL %RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS %OF RECIPIENT IN THE USE OF THE SOFTWARE.
Formal statement is: lemma connected_diff_open_from_closed: assumes st: "s \<subseteq> t" and tu: "t \<subseteq> u" and s: "open s" and t: "closed t" and u: "connected u" and ts: "connected (t - s)" shows "connected(u - s)" Informal statement is: If $s \subseteq t \subseteq u$ and $s$ is open, $t$ is closed, $u$ is connected, and $t - s$ is connected, then $u - s$ is connected.
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import datetime import json import random import time from pathlib import Path import numpy as np import torch from torch.utils.data import DataLoader, DistributedSampler import datasets import util.misc as utils from datasets import build_dataset, get_coco_api_from_dataset from engine import evaluate, train_one_epoch from models import build_model as build_yolos_model from util.scheduler import create_scheduler def get_args_parser(): parser = argparse.ArgumentParser('Set YOLOS', add_help=False) parser.add_argument('--lr', default=1e-4, type=float) parser.add_argument('--lr_backbone', default=1e-5, type=float) parser.add_argument('--batch_size', default=2, type=int) parser.add_argument('--weight_decay', default=1e-4, type=float) parser.add_argument('--epochs', default=150, type=int) parser.add_argument('--eval_size', default=800, type=int) parser.add_argument('--clip_max_norm', default=0.1, type=float, help='gradient clipping max norm') parser.add_argument('--use_checkpoint', action='store_true', help='use checkpoint.checkpoint to save mem') # scheduler # Learning rate schedule parameters parser.add_argument('--sched', default='warmupcos', type=str, metavar='SCHEDULER', help='LR scheduler (default: "step", options:"step", "warmupcos"') ## step parser.add_argument('--lr_drop', default=100, type=int) ## warmupcosine # parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', # help='learning rate noise on/off epoch percentages') # parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', # help='learning rate noise limit percent (default: 0.67)') # parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', # help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)') parser.add_argument('--min-lr', type=float, default=1e-7, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--warmup-epochs', type=int, default=0, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # * model setting parser.add_argument("--det_token_num", default=100, type=int, help="Number of det token in the deit backbone") parser.add_argument('--backbone_name', default='tiny', type=str, help="Name of the deit backbone to use") parser.add_argument('--pre_trained', default='', help="set imagenet pretrained model path if not train yolos from scatch") parser.add_argument('--init_pe_size', nargs='+', type=int, help="init pe size (h,w)") parser.add_argument('--mid_pe_size', nargs='+', type=int, help="mid pe size (h,w)") # * Matcher parser.add_argument('--set_cost_class', default=1, type=float, help="Class coefficient in the matching cost") parser.add_argument('--set_cost_bbox', default=5, type=float, help="L1 box coefficient in the matching cost") parser.add_argument('--set_cost_giou', default=2, type=float, help="giou box coefficient in the matching cost") # * Loss coefficients parser.add_argument('--dice_loss_coef', default=1, type=float) parser.add_argument('--bbox_loss_coef', default=5, type=float) parser.add_argument('--giou_loss_coef', default=2, type=float) parser.add_argument('--eos_coef', default=0.1, type=float, help="Relative classification weight of the no-object class") # dataset parameters parser.add_argument('--dataset_file', default='coco') parser.add_argument('--coco_path', type=str) parser.add_argument('--coco_panoptic_path', type=str) parser.add_argument('--remove_difficult', action='store_true') parser.add_argument('--output_dir', default='', help='path where to save, empty for no saving') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=42, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval', action='store_true') parser.add_argument('--num_workers', default=2, type=int) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') return parser def main(args): utils.init_distributed_mode(args) # print("git:\n {}\n".format(utils.get_sha())) print(args) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + utils.get_rank() torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) # import pdb;pdb.set_trace() # Build YOLOS model model, criterion, postprocessors = build_yolos_model(args) # model, criterion, postprocessors = build_model(args) model.to(device) # For parallel model_without_ddp = model if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print('number of params:', n_parameters) def build_optimizer(model, args): if hasattr(model.backbone, 'no_weight_decay'): skip = model.backbone.no_weight_decay() head = [] backbone_decay = [] backbone_no_decay = [] for name, param in model.named_parameters(): if "backbone" not in name and param.requires_grad: head.append(param) if "backbone" in name and param.requires_grad: if len(param.shape) == 1 or name.endswith(".bias") or name.split('.')[-1] in skip: backbone_no_decay.append(param) else: backbone_decay.append(param) param_dicts = [ {"params": head}, {"params": backbone_no_decay, "weight_decay": 0., "lr": args.lr}, {"params": backbone_decay, "lr": args.lr}, ] optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay) return optimizer # Optimizer optimizer = build_optimizer(model_without_ddp, args) lr_scheduler, _ = create_scheduler(args, optimizer) # Dataset dataset_train = build_dataset(image_set='train', args=args) dataset_val = build_dataset(image_set='val', args=args) # import pdb;pdb.set_trace() if args.distributed: sampler_train = DistributedSampler(dataset_train) sampler_val = DistributedSampler(dataset_val, shuffle=False) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) batch_sampler_train = torch.utils.data.BatchSampler( sampler_train, args.batch_size, drop_last=True) data_loader_train = DataLoader(dataset_train, batch_sampler=batch_sampler_train, collate_fn=utils.collate_fn, num_workers=args.num_workers) data_loader_val = DataLoader(dataset_val, args.batch_size, sampler=sampler_val, drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) if args.dataset_file == "coco_panoptic": # We also evaluate AP during panoptic training, on original coco DS coco_val = datasets.coco.build("val", args) base_ds = get_coco_api_from_dataset(coco_val) else: base_ds = get_coco_api_from_dataset(dataset_val) output_dir = Path(args.output_dir) # Load for checkpoint? if args.resume: if args.resume.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.resume, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint: optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) args.start_epoch = checkpoint['epoch'] + 1 # Evaluation if args.eval: test_stats, coco_evaluator = evaluate(model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir) if args.output_dir: utils.save_on_master(coco_evaluator.coco_eval["bbox"].eval, output_dir / "eval.pth") return # Training print("Start training") start_time = time.time() for epoch in range(args.start_epoch, args.epochs): if args.distributed: sampler_train.set_epoch(epoch) # train one epooch train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, args.clip_max_norm) lr_scheduler.step(epoch) # step learning rate scheduler # save model if args.output_dir: checkpoint_paths = [output_dir / 'checkpoint.pth'] # extra checkpoint before LR drop and every 100 epochs if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 100 == 0: checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth') for checkpoint_path in checkpoint_paths: utils.save_on_master({ 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'epoch': epoch, 'args': args, }, checkpoint_path) # evaluate test_stats, coco_evaluator = evaluate( model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir ) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} # log if args.output_dir and utils.is_main_process(): with (output_dir / "log.txt").open("a") as f: f.write(json.dumps(log_stats) + "\n") # for evaluation logs if coco_evaluator is not None: (output_dir / 'eval').mkdir(exist_ok=True) if "bbox" in coco_evaluator.coco_eval: filenames = ['latest.pth'] if epoch % 50 == 0: filenames.append(f'{epoch:03}.pth') for name in filenames: torch.save(coco_evaluator.coco_eval["bbox"].eval, output_dir / "eval" / name) total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) if __name__ == '__main__': parser = argparse.ArgumentParser('YOLOS training and evaluation script', parents=[get_args_parser()]) args = parser.parse_args() if args.output_dir: Path(args.output_dir).mkdir(parents=True, exist_ok=True) main(args)
Require Import SpecDeps. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import Constants. Require Import CommonLib. Require Import AbsAccessor.Spec. Local Open Scope Z_scope. Section Spec. Definition psci_version_spec (rec: Pointer) (adt: RData) : option RData := Some adt {priv: (priv adt) {psci_x0: 65537}}. End Spec.
module Domain using Dates export Person, Address, AddressType, EMAIL, WORK # local function to generate an unique id create_key(name::String) = string(hash(name * string(time()))) # enumerated type for an address. @enum AddressType EMAIL WORK struct Address id::String created::DateTime address_type::AddressType address::String #constructors Address(address_type, address) = new(create_key(address), now(), address_type, address) end # Address struct Person id::String created::DateTime name::String addresses::Array{Address, 1} #constructors Person(name) = new(create_key(name), now(), name, []) Person(name, addresses) = new(create_key(name), now(), name, addresses) end end
Formal statement is: lemma fixes a :: "'a::euclidean_space" shows cbox_sing [simp]: "cbox a a = {a}" and box_sing [simp]: "box a a = {}" Informal statement is: The closed box and open box with the same endpoints are the singleton set and the empty set, respectively.
function [hashVal,hexVal]=genHashVal(inputArray,algorithm) %%GENHASHVAL Get a hash value of a character string or a 1D array of % bytes. That is, integer values from 0 through 255. The hash % value can either be a simple integer value, useful for quick % comparison of strings, or one can get a cryptographic hash as % an an array of integers from 0 to 255 using various % algorithms. Cryptographic hashes are also returned has % hexadecimal strings. % %INPUTS: inputArray A 1-dimensional string of characters or array of % integer values from 0 to 255 for which one desired a % hash code. % algorithm An optional string specifying the algorithm to use to % generate the hash. Possible values are % 'simple' (the default) Use a simple, non-cryptographic % hash function to get a single integer hash for % the input. % 'MD2' Use the MD2 algorithm to get a weak % cryptographic hash, along with its hexidecimal % string. % 'MD5' Use the MD5 algorithm to get a weak % cryptographic hash, along with its hexidecimal % string. % 'SHA-1' Use the SHA-1 algorithm to get a cryptographic % hash along with its hexidecimal string. % 'SHA-384' Use the SHA-384 algorithm to get a % cryptographic hash along with its hexidecimal % string. % 'SHA-256' Use the SHA-256 algorithm to get a % cryptographic hash along with its hexidecimal % string. % 'SHA-512' Use the SHA-512 algorithm to get a % cryptographic hash along with its hexidecimal % string. % %OUTPUTS: hashVal If algorithmis 'simple', then this is an integer hash % code for the given input. Otherwise, it is an array of % bytes representign the has value. % hexVal A hexidecimal string representing the hash value. % %The simple algorithm is executed using the hashCode method in Java's %java.lang.String class. The cryptographic hashes are executed using the %java.security.MessageDigest class. In Matlab, one can directly access Java %functions, which is what was done to implement this function. % %April 2014 David F. Crouse, Naval Research Laboratory, Washington D.C. %(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. if(~ischar(inputArray)&&any(inputArray~=fix(inputArray))||any(inputArray>255)||any(inputArray<0)) error('Hash values can only be obtained from character arrays or arrays of positive integer values from 0 through 255'); end if(nargin<2) algorithm='simple'; end %If the simple aglorithm is chosen. otherwise, a cryptographic has is being %used. if(strcmp(algorithm,'simple')) %Convert the array to a character string. if(~ischar(inputArray)) inputArray=native2unicode(inputArray); end myString=java.lang.String(inputArray); hashVal=myString.hashCode; %Java's integers are always 32-bits. hexVal=dec2hex(typecast(int32(hashVal),'uint32'),8); return; end %The cryptographic has functions work on bytes, not strings. if(ischar(inputArray)) inputArray=unicode2native(inputArray); end myDigest=java.security.MessageDigest.getInstance(algorithm); myDigest.update(inputArray); hashVal=myDigest.digest; hexVal=javax.xml.bind.DatatypeConverter.printHexBinary(hashVal); end %LICENSE: % %The source code is in the public domain and not licensed or under %copyright. The information and software may be used freely by the public. %As required by 17 U.S.C. 403, third parties producing copyrighted works %consisting predominantly of the material produced by U.S. government %agencies must provide notice with such work(s) identifying the U.S. %Government material incorporated and stating that such material is not %subject to copyright protection. % %Derived works shall not identify themselves in a manner that implies an %endorsement by or an affiliation with the Naval Research Laboratory. % %RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE %SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL %RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS %OF RECIPIENT IN THE USE OF THE SOFTWARE.
#- Other VISA Definitions --------------------------------------------------*/ const WORD_SIZE = 64 const VI_NULL = 0 const VI_TRUE = 1 const VI_FALSE = 0 #- Attributes (platform independent size) ----------------------------------*/ const VI_ATTR_RSRC_CLASS = 0xBFFF0001 const VI_ATTR_RSRC_NAME = 0xBFFF0002 const VI_ATTR_RSRC_IMPL_VERSION = 0x3FFF0003 const VI_ATTR_RSRC_LOCK_STATE = 0x3FFF0004 const VI_ATTR_MAX_QUEUE_LENGTH = 0x3FFF0005 const VI_ATTR_USER_DATA_32 = 0x3FFF0007 const VI_ATTR_FDC_CHNL = 0x3FFF000D const VI_ATTR_FDC_MODE = 0x3FFF000F const VI_ATTR_FDC_GEN_SIGNAL_EN = 0x3FFF0011 const VI_ATTR_FDC_USE_PAIR = 0x3FFF0013 const VI_ATTR_SEND_END_EN = 0x3FFF0016 const VI_ATTR_TERMCHAR = 0x3FFF0018 const VI_ATTR_TMO_VALUE = 0x3FFF001A const VI_ATTR_GPIB_READDR_EN = 0x3FFF001B const VI_ATTR_IO_PROT = 0x3FFF001C const VI_ATTR_DMA_ALLOW_EN = 0x3FFF001E const VI_ATTR_ASRL_BAUD = 0x3FFF0021 const VI_ATTR_ASRL_DATA_BITS = 0x3FFF0022 const VI_ATTR_ASRL_PARITY = 0x3FFF0023 const VI_ATTR_ASRL_STOP_BITS = 0x3FFF0024 const VI_ATTR_ASRL_FLOW_CNTRL = 0x3FFF0025 const VI_ATTR_RD_BUF_OPER_MODE = 0x3FFF002A const VI_ATTR_RD_BUF_SIZE = 0x3FFF002B const VI_ATTR_WR_BUF_OPER_MODE = 0x3FFF002D const VI_ATTR_WR_BUF_SIZE = 0x3FFF002E const VI_ATTR_SUPPRESS_END_EN = 0x3FFF0036 const VI_ATTR_TERMCHAR_EN = 0x3FFF0038 const VI_ATTR_DEST_ACCESS_PRIV = 0x3FFF0039 const VI_ATTR_DEST_BYTE_ORDER = 0x3FFF003A const VI_ATTR_SRC_ACCESS_PRIV = 0x3FFF003C const VI_ATTR_SRC_BYTE_ORDER = 0x3FFF003D const VI_ATTR_SRC_INCREMENT = 0x3FFF0040 const VI_ATTR_DEST_INCREMENT = 0x3FFF0041 const VI_ATTR_WIN_ACCESS_PRIV = 0x3FFF0045 const VI_ATTR_WIN_BYTE_ORDER = 0x3FFF0047 const VI_ATTR_GPIB_ATN_STATE = 0x3FFF0057 const VI_ATTR_GPIB_ADDR_STATE = 0x3FFF005C const VI_ATTR_GPIB_CIC_STATE = 0x3FFF005E const VI_ATTR_GPIB_NDAC_STATE = 0x3FFF0062 const VI_ATTR_GPIB_SRQ_STATE = 0x3FFF0067 const VI_ATTR_GPIB_SYS_CNTRL_STATE = 0x3FFF0068 const VI_ATTR_GPIB_HS488_CBL_LEN = 0x3FFF0069 const VI_ATTR_CMDR_LA = 0x3FFF006B const VI_ATTR_VXI_DEV_CLASS = 0x3FFF006C const VI_ATTR_MAINFRAME_LA = 0x3FFF0070 const VI_ATTR_MANF_NAME = 0xBFFF0072 const VI_ATTR_MODEL_NAME = 0xBFFF0077 const VI_ATTR_VXI_VME_INTR_STATUS = 0x3FFF008B const VI_ATTR_VXI_TRIG_STATUS = 0x3FFF008D const VI_ATTR_VXI_VME_SYSFAIL_STATE = 0x3FFF0094 const VI_ATTR_WIN_BASE_ADDR_32 = 0x3FFF0098 const VI_ATTR_WIN_SIZE_32 = 0x3FFF009A const VI_ATTR_ASRL_AVAIL_NUM = 0x3FFF00AC const VI_ATTR_MEM_BASE_32 = 0x3FFF00AD const VI_ATTR_ASRL_CTS_STATE = 0x3FFF00AE const VI_ATTR_ASRL_DCD_STATE = 0x3FFF00AF const VI_ATTR_ASRL_DSR_STATE = 0x3FFF00B1 const VI_ATTR_ASRL_DTR_STATE = 0x3FFF00B2 const VI_ATTR_ASRL_END_IN = 0x3FFF00B3 const VI_ATTR_ASRL_END_OUT = 0x3FFF00B4 const VI_ATTR_ASRL_REPLACE_CHAR = 0x3FFF00BE const VI_ATTR_ASRL_RI_STATE = 0x3FFF00BF const VI_ATTR_ASRL_RTS_STATE = 0x3FFF00C0 const VI_ATTR_ASRL_XON_CHAR = 0x3FFF00C1 const VI_ATTR_ASRL_XOFF_CHAR = 0x3FFF00C2 const VI_ATTR_WIN_ACCESS = 0x3FFF00C3 const VI_ATTR_RM_SESSION = 0x3FFF00C4 const VI_ATTR_VXI_LA = 0x3FFF00D5 const VI_ATTR_MANF_ID = 0x3FFF00D9 const VI_ATTR_MEM_SIZE_32 = 0x3FFF00DD const VI_ATTR_MEM_SPACE = 0x3FFF00DE const VI_ATTR_MODEL_CODE = 0x3FFF00DF const VI_ATTR_SLOT = 0x3FFF00E8 const VI_ATTR_INTF_INST_NAME = 0xBFFF00E9 const VI_ATTR_IMMEDIATE_SERV = 0x3FFF0100 const VI_ATTR_INTF_PARENT_NUM = 0x3FFF0101 const VI_ATTR_RSRC_SPEC_VERSION = 0x3FFF0170 const VI_ATTR_INTF_TYPE = 0x3FFF0171 const VI_ATTR_GPIB_PRIMARY_ADDR = 0x3FFF0172 const VI_ATTR_GPIB_SECONDARY_ADDR = 0x3FFF0173 const VI_ATTR_RSRC_MANF_NAME = 0xBFFF0174 const VI_ATTR_RSRC_MANF_ID = 0x3FFF0175 const VI_ATTR_INTF_NUM = 0x3FFF0176 const VI_ATTR_TRIG_ID = 0x3FFF0177 const VI_ATTR_GPIB_REN_STATE = 0x3FFF0181 const VI_ATTR_GPIB_UNADDR_EN = 0x3FFF0184 const VI_ATTR_DEV_STATUS_BYTE = 0x3FFF0189 const VI_ATTR_FILE_APPEND_EN = 0x3FFF0192 const VI_ATTR_VXI_TRIG_SUPPORT = 0x3FFF0194 const VI_ATTR_TCPIP_ADDR = 0xBFFF0195 const VI_ATTR_TCPIP_HOSTNAME = 0xBFFF0196 const VI_ATTR_TCPIP_PORT = 0x3FFF0197 const VI_ATTR_TCPIP_DEVICE_NAME = 0xBFFF0199 const VI_ATTR_TCPIP_NODELAY = 0x3FFF019A const VI_ATTR_TCPIP_KEEPALIVE = 0x3FFF019B const VI_ATTR_4882_COMPLIANT = 0x3FFF019F const VI_ATTR_USB_SERIAL_NUM = 0xBFFF01A0 const VI_ATTR_USB_INTFC_NUM = 0x3FFF01A1 const VI_ATTR_USB_PROTOCOL = 0x3FFF01A7 const VI_ATTR_USB_MAX_INTR_SIZE = 0x3FFF01AF const VI_ATTR_PXI_DEV_NUM = 0x3FFF0201 const VI_ATTR_PXI_FUNC_NUM = 0x3FFF0202 const VI_ATTR_PXI_BUS_NUM = 0x3FFF0205 const VI_ATTR_PXI_CHASSIS = 0x3FFF0206 const VI_ATTR_PXI_SLOTPATH = 0xBFFF0207 const VI_ATTR_PXI_SLOT_LBUS_LEFT = 0x3FFF0208 const VI_ATTR_PXI_SLOT_LBUS_RIGHT = 0x3FFF0209 const VI_ATTR_PXI_TRIG_BUS = 0x3FFF020A const VI_ATTR_PXI_STAR_TRIG_BUS = 0x3FFF020B const VI_ATTR_PXI_STAR_TRIG_LINE = 0x3FFF020C const VI_ATTR_PXI_SRC_TRIG_BUS = 0x3FFF020D const VI_ATTR_PXI_DEST_TRIG_BUS = 0x3FFF020E const VI_ATTR_PXI_MEM_TYPE_BAR0 = 0x3FFF0211 const VI_ATTR_PXI_MEM_TYPE_BAR1 = 0x3FFF0212 const VI_ATTR_PXI_MEM_TYPE_BAR2 = 0x3FFF0213 const VI_ATTR_PXI_MEM_TYPE_BAR3 = 0x3FFF0214 const VI_ATTR_PXI_MEM_TYPE_BAR4 = 0x3FFF0215 const VI_ATTR_PXI_MEM_TYPE_BAR5 = 0x3FFF0216 const VI_ATTR_PXI_MEM_BASE_BAR0_32 = 0x3FFF0221 const VI_ATTR_PXI_MEM_BASE_BAR1_32 = 0x3FFF0222 const VI_ATTR_PXI_MEM_BASE_BAR2_32 = 0x3FFF0223 const VI_ATTR_PXI_MEM_BASE_BAR3_32 = 0x3FFF0224 const VI_ATTR_PXI_MEM_BASE_BAR4_32 = 0x3FFF0225 const VI_ATTR_PXI_MEM_BASE_BAR5_32 = 0x3FFF0226 const VI_ATTR_PXI_MEM_BASE_BAR0_64 = 0x3FFF0228 const VI_ATTR_PXI_MEM_BASE_BAR1_64 = 0x3FFF0229 const VI_ATTR_PXI_MEM_BASE_BAR2_64 = 0x3FFF022A const VI_ATTR_PXI_MEM_BASE_BAR3_64 = 0x3FFF022B const VI_ATTR_PXI_MEM_BASE_BAR4_64 = 0x3FFF022C const VI_ATTR_PXI_MEM_BASE_BAR5_64 = 0x3FFF022D const VI_ATTR_PXI_MEM_SIZE_BAR0_32 = 0x3FFF0231 const VI_ATTR_PXI_MEM_SIZE_BAR1_32 = 0x3FFF0232 const VI_ATTR_PXI_MEM_SIZE_BAR2_32 = 0x3FFF0233 const VI_ATTR_PXI_MEM_SIZE_BAR3_32 = 0x3FFF0234 const VI_ATTR_PXI_MEM_SIZE_BAR4_32 = 0x3FFF0235 const VI_ATTR_PXI_MEM_SIZE_BAR5_32 = 0x3FFF0236 const VI_ATTR_PXI_MEM_SIZE_BAR0_64 = 0x3FFF0238 const VI_ATTR_PXI_MEM_SIZE_BAR1_64 = 0x3FFF0239 const VI_ATTR_PXI_MEM_SIZE_BAR2_64 = 0x3FFF023A const VI_ATTR_PXI_MEM_SIZE_BAR3_64 = 0x3FFF023B const VI_ATTR_PXI_MEM_SIZE_BAR4_64 = 0x3FFF023C const VI_ATTR_PXI_MEM_SIZE_BAR5_64 = 0x3FFF023D const VI_ATTR_PXI_IS_EXPRESS = 0x3FFF0240 const VI_ATTR_PXI_SLOT_LWIDTH = 0x3FFF0241 const VI_ATTR_PXI_MAX_LWIDTH = 0x3FFF0242 const VI_ATTR_PXI_ACTUAL_LWIDTH = 0x3FFF0243 const VI_ATTR_PXI_DSTAR_BUS = 0x3FFF0244 const VI_ATTR_PXI_DSTAR_SET = 0x3FFF0245 const VI_ATTR_PXI_ALLOW_WRITE_COMBINE = 0x3FFF0246 const VI_ATTR_TCPIP_HISLIP_OVERLAP_EN = 0x3FFF0300 const VI_ATTR_TCPIP_HISLIP_VERSION = 0x3FFF0301 const VI_ATTR_TCPIP_HISLIP_MAX_MESSAGE_KB = 0x3FFF0302 const VI_ATTR_TCPIP_IS_HISLIP = 0x3FFF0303 const VI_ATTR_JOB_ID = 0x3FFF4006 const VI_ATTR_EVENT_TYPE = 0x3FFF4010 const VI_ATTR_SIGP_STATUS_ID = 0x3FFF4011 const VI_ATTR_RECV_TRIG_ID = 0x3FFF4012 const VI_ATTR_INTR_STATUS_ID = 0x3FFF4023 const VI_ATTR_STATUS = 0x3FFF4025 const VI_ATTR_RET_COUNT_32 = 0x3FFF4026 const VI_ATTR_BUFFER = 0x3FFF4027 const VI_ATTR_RECV_INTR_LEVEL = 0x3FFF4041 const VI_ATTR_OPER_NAME = 0xBFFF4042 const VI_ATTR_GPIB_RECV_CIC_STATE = 0x3FFF4193 const VI_ATTR_RECV_TCPIP_ADDR = 0xBFFF4198 const VI_ATTR_USB_RECV_INTR_SIZE = 0x3FFF41B0 const VI_ATTR_USB_RECV_INTR_DATA = 0xBFFF41B1 const VI_ATTR_PXI_RECV_INTR_SEQ = 0x3FFF4240 const VI_ATTR_PXI_RECV_INTR_DATA = 0x3FFF4241 #- Attributes (platform dependent size) ------------------------------------*/ if WORD_SIZE == 64 ViAttrState = ViUInt64 else ViAttrState = ViUInt32 end if WORD_SIZE == 64 const VI_ATTR_USER_DATA_64 = 0x3FFF000A const VI_ATTR_RET_COUNT_64 = 0x3FFF4028 const VI_ATTR_USER_DATA = VI_ATTR_USER_DATA_64 const VI_ATTR_RET_COUNT = VI_ATTR_RET_COUNT_64 else const VI_ATTR_USER_DATA = VI_ATTR_USER_DATA_32 const VI_ATTR_RET_COUNT = VI_ATTR_RET_COUNT_32 end if WORD_SIZE == 64 const VI_ATTR_WIN_BASE_ADDR_64 = 0x3FFF009B const VI_ATTR_WIN_SIZE_64 = 0x3FFF009C const VI_ATTR_MEM_BASE_64 = 0x3FFF00D0 const VI_ATTR_MEM_SIZE_64 = 0x3FFF00D1 end if WORD_SIZE == 64 const VI_ATTR_WIN_BASE_ADDR = VI_ATTR_WIN_BASE_ADDR_64 const VI_ATTR_WIN_SIZE = VI_ATTR_WIN_SIZE_64 const VI_ATTR_MEM_BASE = VI_ATTR_MEM_BASE_64 const VI_ATTR_MEM_SIZE = VI_ATTR_MEM_SIZE_64 const VI_ATTR_PXI_MEM_BASE_BAR0 = VI_ATTR_PXI_MEM_BASE_BAR0_64 const VI_ATTR_PXI_MEM_BASE_BAR1 = VI_ATTR_PXI_MEM_BASE_BAR1_64 const VI_ATTR_PXI_MEM_BASE_BAR2 = VI_ATTR_PXI_MEM_BASE_BAR2_64 const VI_ATTR_PXI_MEM_BASE_BAR3 = VI_ATTR_PXI_MEM_BASE_BAR3_64 const VI_ATTR_PXI_MEM_BASE_BAR4 = VI_ATTR_PXI_MEM_BASE_BAR4_64 const VI_ATTR_PXI_MEM_BASE_BAR5 = VI_ATTR_PXI_MEM_BASE_BAR5_64 const VI_ATTR_PXI_MEM_SIZE_BAR0 = VI_ATTR_PXI_MEM_SIZE_BAR0_64 const VI_ATTR_PXI_MEM_SIZE_BAR1 = VI_ATTR_PXI_MEM_SIZE_BAR1_64 const VI_ATTR_PXI_MEM_SIZE_BAR2 = VI_ATTR_PXI_MEM_SIZE_BAR2_64 const VI_ATTR_PXI_MEM_SIZE_BAR3 = VI_ATTR_PXI_MEM_SIZE_BAR3_64 const VI_ATTR_PXI_MEM_SIZE_BAR4 = VI_ATTR_PXI_MEM_SIZE_BAR4_64 const VI_ATTR_PXI_MEM_SIZE_BAR5 = VI_ATTR_PXI_MEM_SIZE_BAR5_64 else const VI_ATTR_WIN_BASE_ADDR = VI_ATTR_WIN_BASE_ADDR_32 const VI_ATTR_WIN_SIZE = VI_ATTR_WIN_SIZE_32 const VI_ATTR_MEM_BASE = VI_ATTR_MEM_BASE_32 const VI_ATTR_MEM_SIZE = VI_ATTR_MEM_SIZE_32 const VI_ATTR_PXI_MEM_BASE_BAR0 = VI_ATTR_PXI_MEM_BASE_BAR0_32 const VI_ATTR_PXI_MEM_BASE_BAR1 = VI_ATTR_PXI_MEM_BASE_BAR1_32 const VI_ATTR_PXI_MEM_BASE_BAR2 = VI_ATTR_PXI_MEM_BASE_BAR2_32 const VI_ATTR_PXI_MEM_BASE_BAR3 = VI_ATTR_PXI_MEM_BASE_BAR3_32 const VI_ATTR_PXI_MEM_BASE_BAR4 = VI_ATTR_PXI_MEM_BASE_BAR4_32 const VI_ATTR_PXI_MEM_BASE_BAR5 = VI_ATTR_PXI_MEM_BASE_BAR5_32 const VI_ATTR_PXI_MEM_SIZE_BAR0 = VI_ATTR_PXI_MEM_SIZE_BAR0_32 const VI_ATTR_PXI_MEM_SIZE_BAR1 = VI_ATTR_PXI_MEM_SIZE_BAR1_32 const VI_ATTR_PXI_MEM_SIZE_BAR2 = VI_ATTR_PXI_MEM_SIZE_BAR2_32 const VI_ATTR_PXI_MEM_SIZE_BAR3 = VI_ATTR_PXI_MEM_SIZE_BAR3_32 const VI_ATTR_PXI_MEM_SIZE_BAR4 = VI_ATTR_PXI_MEM_SIZE_BAR4_32 const VI_ATTR_PXI_MEM_SIZE_BAR5 = VI_ATTR_PXI_MEM_SIZE_BAR5_32 end #- Event Types -------------------------------------------------------------*/ const VI_EVENT_IO_COMPLETION = 0x3FFF2009 const VI_EVENT_TRIG = 0xBFFF200A const VI_EVENT_SERVICE_REQ = 0x3FFF200B const VI_EVENT_CLEAR = 0x3FFF200D const VI_EVENT_EXCEPTION = 0xBFFF200E const VI_EVENT_GPIB_CIC = 0x3FFF2012 const VI_EVENT_GPIB_TALK = 0x3FFF2013 const VI_EVENT_GPIB_LISTEN = 0x3FFF2014 const VI_EVENT_VXI_VME_SYSFAIL = 0x3FFF201D const VI_EVENT_VXI_VME_SYSRESET = 0x3FFF201E const VI_EVENT_VXI_SIGP = 0x3FFF2020 const VI_EVENT_VXI_VME_INTR = 0xBFFF2021 const VI_EVENT_PXI_INTR = 0x3FFF2022 const VI_EVENT_TCPIP_CONNECT = 0x3FFF2036 const VI_EVENT_USB_INTR = 0x3FFF2037 const VI_ALL_ENABLED_EVENTS = 0x3FFF7FFF #- Other VISA Definitions --------------------------------------------------*/ # const VI_VERSION_MAJOR(ver) ((((ViVersion)ver) & 0xFFF00000 >> 20) # const VI_VERSION_MINOR(ver) ((((ViVersion)ver) & 0x000FFF00 >> 8) # const VI_VERSION_SUBMINOR(ver) ((((ViVersion)ver) & 0x000000FF ) const VI_FIND_BUFLEN = 256 const VI_INTF_GPIB = 1 const VI_INTF_VXI = 2 const VI_INTF_GPIB_VXI = 3 const VI_INTF_ASRL = 4 const VI_INTF_PXI = 5 const VI_INTF_TCPIP = 6 const VI_INTF_USB = 7 const VI_PROT_NORMAL = 1 const VI_PROT_FDC = 2 const VI_PROT_HS488 = 3 const VI_PROT_4882_STRS = 4 const VI_PROT_USBTMC_VENDOR = 5 const VI_FDC_NORMAL = 1 const VI_FDC_STREAM = 2 const VI_LOCAL_SPACE = 0 const VI_A16_SPACE = 1 const VI_A24_SPACE = 2 const VI_A32_SPACE = 3 const VI_A64_SPACE = 4 const VI_PXI_ALLOC_SPACE = 9 const VI_PXI_CFG_SPACE = 10 const VI_PXI_BAR0_SPACE = 11 const VI_PXI_BAR1_SPACE = 12 const VI_PXI_BAR2_SPACE = 13 const VI_PXI_BAR3_SPACE = 14 const VI_PXI_BAR4_SPACE = 15 const VI_PXI_BAR5_SPACE = 16 const VI_OPAQUE_SPACE = 0xFFFF const VI_UNKNOWN_LA = -1 const VI_UNKNOWN_SLOT = -1 const VI_UNKNOWN_LEVEL = -1 const VI_UNKNOWN_CHASSIS = -1 const VI_QUEUE = 1 const VI_HNDLR = 2 const VI_SUSPEND_HNDLR = 4 const VI_ALL_MECH = 0xFFFF const VI_ANY_HNDLR = 0 const VI_TRIG_ALL = -2 const VI_TRIG_SW = -1 const VI_TRIG_TTL0 = 0 const VI_TRIG_TTL1 = 1 const VI_TRIG_TTL2 = 2 const VI_TRIG_TTL3 = 3 const VI_TRIG_TTL4 = 4 const VI_TRIG_TTL5 = 5 const VI_TRIG_TTL6 = 6 const VI_TRIG_TTL7 = 7 const VI_TRIG_ECL0 = 8 const VI_TRIG_ECL1 = 9 const VI_TRIG_ECL2 = 10 const VI_TRIG_ECL3 = 11 const VI_TRIG_ECL4 = 12 const VI_TRIG_ECL5 = 13 const VI_TRIG_STAR_SLOT1 = 14 const VI_TRIG_STAR_SLOT2 = 15 const VI_TRIG_STAR_SLOT3 = 16 const VI_TRIG_STAR_SLOT4 = 17 const VI_TRIG_STAR_SLOT5 = 18 const VI_TRIG_STAR_SLOT6 = 19 const VI_TRIG_STAR_SLOT7 = 20 const VI_TRIG_STAR_SLOT8 = 21 const VI_TRIG_STAR_SLOT9 = 22 const VI_TRIG_STAR_SLOT10 = 23 const VI_TRIG_STAR_SLOT11 = 24 const VI_TRIG_STAR_SLOT12 = 25 const VI_TRIG_STAR_INSTR = 26 const VI_TRIG_PANEL_IN = 27 const VI_TRIG_PANEL_OUT = 28 const VI_TRIG_STAR_VXI0 = 29 const VI_TRIG_STAR_VXI1 = 30 const VI_TRIG_STAR_VXI2 = 31 const VI_TRIG_PROT_DEFAULT = 0 const VI_TRIG_PROT_ON = 1 const VI_TRIG_PROT_OFF = 2 const VI_TRIG_PROT_SYNC = 5 const VI_TRIG_PROT_RESERVE = 6 const VI_TRIG_PROT_UNRESERVE = 7 const VI_READ_BUF = 1 const VI_WRITE_BUF = 2 const VI_READ_BUF_DISCARD = 4 const VI_WRITE_BUF_DISCARD = 8 const VI_IO_IN_BUF = 16 const VI_IO_OUT_BUF = 32 const VI_IO_IN_BUF_DISCARD = 64 const VI_IO_OUT_BUF_DISCARD = 128 const VI_FLUSH_ON_ACCESS = 1 const VI_FLUSH_WHEN_FULL = 2 const VI_FLUSH_DISABLE = 3 const VI_NMAPPED = 1 const VI_USE_OPERS = 2 const VI_DEREF_ADDR = 3 const VI_DEREF_ADDR_BYTE_SWAP = 4 const VI_TMO_IMMEDIATE = 0x00000000 const VI_TMO_INFINITE = 0xFFFFFFFF const VI_NO_LOCK = 0x00000000 const VI_EXCLUSIVE_LOCK = 0x00000001 const VI_SHARED_LOCK = 0x00000002 const VI_LOAD_CONFIG = 0x00000003 const VI_NO_SEC_ADDR = 0xFFFF const VI_ASRL_PAR_NONE = 0 const VI_ASRL_PAR_ODD = 1 const VI_ASRL_PAR_EVEN = 2 const VI_ASRL_PAR_MARK = 3 const VI_ASRL_PAR_SPACE = 4 const VI_ASRL_STOP_ONE = 10 const VI_ASRL_STOP_ONE5 = 15 const VI_ASRL_STOP_TWO = 20 const VI_ASRL_FLOW_NONE = 0 const VI_ASRL_FLOW_XON_XOFF = 1 const VI_ASRL_FLOW_RTS_CTS = 2 const VI_ASRL_FLOW_DTR_DSR = 4 const VI_ASRL_END_NONE = 0 const VI_ASRL_END_LAST_BIT = 1 const VI_ASRL_END_TERMCHAR = 2 const VI_ASRL_END_BREAK = 3 const VI_STATE_ASSERTED = 1 const VI_STATE_UNASSERTED = 0 const VI_STATE_UNKNOWN = -1 const VI_BIG_ENDIAN = 0 const VI_LITTLE_ENDIAN = 1 const VI_DATA_PRIV = 0 const VI_DATA_NPRIV = 1 const VI_PROG_PRIV = 2 const VI_PROG_NPRIV = 3 const VI_BLCK_PRIV = 4 const VI_BLCK_NPRIV = 5 const VI_D64_PRIV = 6 const VI_D64_NPRIV = 7 const VI_D64_2EVME = 8 const VI_D64_SST160 = 9 const VI_D64_SST267 = 10 const VI_D64_SST320 = 11 const VI_WIDTH_8 = 1 const VI_WIDTH_16 = 2 const VI_WIDTH_32 = 4 const VI_WIDTH_64 = 8 const VI_GPIB_REN_DEASSERT = 0 const VI_GPIB_REN_ASSERT = 1 const VI_GPIB_REN_DEASSERT_GTL = 2 const VI_GPIB_REN_ASSERT_ADDRESS = 3 const VI_GPIB_REN_ASSERT_LLO = 4 const VI_GPIB_REN_ASSERT_ADDRESS_LLO = 5 const VI_GPIB_REN_ADDRESS_GTL = 6 const VI_GPIB_ATN_DEASSERT = 0 const VI_GPIB_ATN_ASSERT = 1 const VI_GPIB_ATN_DEASSERT_HANDSHAKE = 2 const VI_GPIB_ATN_ASSERT_IMMEDIATE = 3 const VI_GPIB_HS488_DISABLED = 0 const VI_GPIB_HS488_NIMPL = -1 const VI_GPIB_UNADDRESSED = 0 const VI_GPIB_TALKER = 1 const VI_GPIB_LISTENER = 2 const VI_VXI_CMD16 = 0x0200 const VI_VXI_CMD16_RESP16 = 0x0202 const VI_VXI_RESP16 = 0x0002 const VI_VXI_CMD32 = 0x0400 const VI_VXI_CMD32_RESP16 = 0x0402 const VI_VXI_CMD32_RESP32 = 0x0404 const VI_VXI_RESP32 = 0x0004 const VI_ASSERT_SIGNAL = -1 const VI_ASSERT_USE_ASSIGNED = 0 const VI_ASSERT_IRQ1 = 1 const VI_ASSERT_IRQ2 = 2 const VI_ASSERT_IRQ3 = 3 const VI_ASSERT_IRQ4 = 4 const VI_ASSERT_IRQ5 = 5 const VI_ASSERT_IRQ6 = 6 const VI_ASSERT_IRQ7 = 7 const VI_UTIL_ASSERT_SYSRESET = 1 const VI_UTIL_ASSERT_SYSFAIL = 2 const VI_UTIL_DEASSERT_SYSFAIL = 3 const VI_VXI_CLASS_MEMORY = 0 const VI_VXI_CLASS_EXTENDED = 1 const VI_VXI_CLASS_MESSAGE = 2 const VI_VXI_CLASS_REGISTER = 3 const VI_VXI_CLASS_OTHER = 4 const VI_PXI_ADDR_NONE = 0 const VI_PXI_ADDR_MEM = 1 const VI_PXI_ADDR_IO = 2 const VI_PXI_ADDR_CFG = 3 const VI_TRIG_UNKNOWN = -1 const VI_PXI_LBUS_UNKNOWN = -1 const VI_PXI_LBUS_NONE = 0 const VI_PXI_LBUS_STAR_TRIG_BUS_0 = 1000 const VI_PXI_LBUS_STAR_TRIG_BUS_1 = 1001 const VI_PXI_LBUS_STAR_TRIG_BUS_2 = 1002 const VI_PXI_LBUS_STAR_TRIG_BUS_3 = 1003 const VI_PXI_LBUS_STAR_TRIG_BUS_4 = 1004 const VI_PXI_LBUS_STAR_TRIG_BUS_5 = 1005 const VI_PXI_LBUS_STAR_TRIG_BUS_6 = 1006 const VI_PXI_LBUS_STAR_TRIG_BUS_7 = 1007 const VI_PXI_LBUS_STAR_TRIG_BUS_8 = 1008 const VI_PXI_LBUS_STAR_TRIG_BUS_9 = 1009 const VI_PXI_STAR_TRIG_CONTROLLER = 1413
lemma pseudo_mod: fixes f g :: "'a::{comm_ring_1,semiring_1_no_zero_divisors} poly" defines "r \<equiv> pseudo_mod f g" assumes g: "g \<noteq> 0" shows "\<exists>a q. a \<noteq> 0 \<and> smult a f = g * q + r" "r = 0 \<or> degree r < degree g"
The offset polynomial of a polynomial $p$ is zero if and only if $p$ is zero.
static char help[] = "Simple ODE system to test implicit and IMEX methods when *both* RHSFunction()\n" "and IFunction() are supplied. Jacobians are supplied as well. The problem\n" "has form\n" " F(t,u,dudt) = G(t,u)\n" "where u(t) = (x(t),y(t)) and dF/d(dudt) is invertible, so the problem is a\n" "2D ODE IVP. Functions F (IFunction) and G (RHSFunction) are actually linear,\n" "but the ProblemType is set to TS_NONLINEAR type. By default the system is\n" " x' + y' + x + 2y = x + 8y\n" " y' + 3x + 4y = 4x + 4y\n" "The implicit methods like BEULER, THETA, CN, BDF should be able to handle\n" "this system. Apparently ROSW can also handle it. However, ARKIMEX and EIMEX\n" "require dF/d(dudt) to be the identity. (But consider option\n" "-ts_arkimex_fully_implicit.) If option -identity_in_F is given then an\n" "equivalent system is formed,\n" " x' + x + 2y = 8y\n" " y' + 3x + 4y = 4x + 4y\n" "Both of these systems are trivial transformations of the system\n" "x'=6y-x, y'=x. With the initial conditions chosen below, x(0)=1 and y(0)=3,\n" "the exact solution to the above systems is x(t) = -3 e^{-3t} + 4 e^{2t},\n" "y(t) = e^{-3t} + 2 e^{2t}, and we compute the final numerical error\n" "accordingly. Default type is BDF. See the manual pages for the various\n" "methods (e.g. TSROSW, TSARKIMEX, TSEIMEX, ...) for further information.\n\n"; #include <petsc.h> typedef struct { PetscBool identity_in_F; } Ctx; extern PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec F,void*); extern PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*); extern PetscErrorCode FormRHSFunction(TS,PetscReal,Vec,Vec,void*); extern PetscErrorCode FormRHSJacobian(TS,PetscReal,Vec,Mat,Mat,void*); int main(int argc,char **argv) { PetscErrorCode ierr; TS ts; Vec u, uexact; Mat JF,JG; Ctx user; PetscReal tf,xf,yf,errnorm; PetscInt steps; PetscInitialize(&argc,&argv,(char*)0,help); user.identity_in_F = PETSC_FALSE; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"", "Simple F(t,u,u')=G(t,u) ODE system.","TS"); CHKERRQ(ierr); ierr = PetscOptionsBool("-identity_in_F","set up system so the dF/d(dudt) = I", "ex54.c",user.identity_in_F,&(user.identity_in_F),NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr); ierr = VecSetSizes(u,PETSC_DECIDE,2); CHKERRQ(ierr); ierr = VecSetFromOptions(u); CHKERRQ(ierr); ierr = MatCreate(PETSC_COMM_WORLD,&JF); CHKERRQ(ierr); ierr = MatSetSizes(JF,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr); ierr = MatSetFromOptions(JF); CHKERRQ(ierr); ierr = MatSetUp(JF); CHKERRQ(ierr); ierr = MatDuplicate(JF,MAT_DO_NOT_COPY_VALUES,&JG); CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr); ierr = TSSetIFunction(ts,NULL,FormIFunction,&user); CHKERRQ(ierr); ierr = TSSetIJacobian(ts,JF,JF,FormIJacobian,&user); CHKERRQ(ierr); ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,&user); CHKERRQ(ierr); ierr = TSSetRHSJacobian(ts,JG,JG,FormRHSJacobian,&user); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); // helps with ARKIMEX if you also set -ts_arkimex_fully_implicit: // ierr = TSSetEquationType(ts,TS_EQ_IMPLICIT); CHKERRQ(ierr); ierr = TSSetType(ts,TSBDF); CHKERRQ(ierr); ierr = TSSetTime(ts,0.0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,1.0); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,0.01); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetFromOptions(ts);CHKERRQ(ierr); ierr = VecSetValue(u,0,1.0,INSERT_VALUES); CHKERRQ(ierr); ierr = VecSetValue(u,1,3.0,INSERT_VALUES); CHKERRQ(ierr); ierr = VecAssemblyBegin(u); CHKERRQ(ierr); ierr = VecAssemblyEnd(u); CHKERRQ(ierr); ierr = TSSolve(ts,u); CHKERRQ(ierr); ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); ierr = TSGetTime(ts,&tf); CHKERRQ(ierr); xf = -3.0 * PetscExpReal(-3.0*tf) + 4.0 * PetscExpReal(2.0*tf); yf = PetscExpReal(-3.0*tf) + 2.0 * PetscExpReal(2.0*tf); //ierr = PetscPrintf(PETSC_COMM_WORLD, // "xf = %.6f, yf = %.6f\n",xf,yf); CHKERRQ(ierr); ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr); ierr = VecSetValue(uexact,0,xf,INSERT_VALUES); CHKERRQ(ierr); ierr = VecSetValue(uexact,1,yf,INSERT_VALUES); CHKERRQ(ierr); ierr = VecAssemblyBegin(uexact); CHKERRQ(ierr); ierr = VecAssemblyEnd(uexact); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecNorm(u,NORM_2,&errnorm); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "error norm at tf = %.6f from %d steps: |u-u_exact| = %.5e\n", tf,steps,errnorm); CHKERRQ(ierr); VecDestroy(&u); VecDestroy(&uexact); MatDestroy(&JF); MatDestroy(&JG); TSDestroy(&ts); return PetscFinalize(); } PetscErrorCode FormIFunction(TS ts, PetscReal t, Vec u, Vec dudt, Vec F, void *user) { PetscErrorCode ierr; const PetscReal *au, *adudt; PetscReal *aF; PetscBool flag = ((Ctx*)user)->identity_in_F; ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = VecGetArrayRead(dudt,&adudt); CHKERRQ(ierr); ierr = VecGetArray(F,&aF); if (flag) { aF[0] = adudt[0] + au[0] + 2.0 * au[1]; aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1]; } else { aF[0] = adudt[0] + adudt[1] + au[0] + 2.0 * au[1]; aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1]; } ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr); ierr = VecRestoreArrayRead(dudt,&adudt); CHKERRQ(ierr); ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr); return 0; } // computes J = dF/du + a dF/d(dudt) PetscErrorCode FormIJacobian(TS ts, PetscReal t, Vec u, Vec dudt, PetscReal a, Mat J, Mat P, void *user) { PetscErrorCode ierr; PetscInt row[2] = {0, 1}, col[2] = {0, 1}; PetscReal v[4]; PetscBool flag = ((Ctx*)user)->identity_in_F; if (flag) { v[0] = a + 1.0; v[1] = 2.0; v[2] = 3.0; v[3] = a + 4.0; } else { v[0] = a + 1.0; v[1] = a + 2.0; v[2] = 3.0; v[3] = a + 4.0; } ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; } PetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec u, Vec G, void *user) { PetscErrorCode ierr; const PetscReal *au; PetscReal *aG; PetscBool flag = ((Ctx*)user)->identity_in_F; ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = VecGetArray(G,&aG); CHKERRQ(ierr); if (flag) { aG[0] = 8.0 * au[1]; aG[1] = 4.0 * au[0] + 4.0 * au[1]; } else { aG[0] = au[0] + 8.0 * au[1]; aG[1] = 4.0 * au[0] + 4.0 * au[1]; } ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr); ierr = VecRestoreArray(G,&aG); CHKERRQ(ierr); return 0; } PetscErrorCode FormRHSJacobian(TS ts, PetscReal t, Vec u, Mat J, Mat P, void *user) { PetscErrorCode ierr; PetscInt row[2] = {0, 1}, col[2] = {0, 1}; PetscReal v[4]; PetscBool flag = ((Ctx*)user)->identity_in_F; if (flag) { v[0] = 0.0; v[1] = 8.0; v[2] = 4.0; v[3] = 4.0; } else { v[0] = 1.0; v[1] = 8.0; v[2] = 4.0; v[3] = 4.0; } ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; }
[STATEMENT] lemma swapidseq_ext_of_permutation: assumes "p permutes S" and "finite S" shows "\<exists>n. swapidseq_ext S n p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>n. swapidseq_ext S n p [PROOF STEP] using cycle_decomp_imp_swapidseq_ext[OF cycle_decomposition[OF assms]] [PROOF STATE] proof (prove) using this: \<exists>n. swapidseq_ext S n p goal (1 subgoal): 1. \<exists>n. swapidseq_ext S n p [PROOF STEP] .
# CS422 Data Mining # Vijay K. Gurbani, Ph.D. # Illinois Institute of Technology # DBSCAN clustering on non-globular data library(fpc) library(factoextra) library(dbscan) set.seed(123) rm(list=ls()) data("multishapes", package = "factoextra") df <- multishapes[, 1:2] plot(df, main="Raw points before DBSCAN") # Let's run k-means on this first. Choose a value of k... k <- kmeans(df, centers=5, nstart=25) fviz_cluster(k, df) # ---- Now, onto dbscan # Run dbscan db <- fpc::dbscan(df, eps = 0.15, MinPts = 5) plot(db, df, main = "DBSCAN", frame = FALSE) # You can also draw this using fviz_cluster fviz_cluster(db, df, stand = FALSE, ellipse = F, geom = "point") # In the output below, column names are cluster numbers. Cluster 0 corresponds # to noise (outliers) print(db) # How to determine eps and k (MinPts)? # k is provided by the user. EPS is determined by looking at the "knee". # For example, head(kNNdist(df, k=5)) shows a numeric vector with distance # to its k-nearest neighbours. kNNdistplot() samples the points from df and # calculates the distance to 5-NN. Look at the "knee" and you will find the # (pot of gold, err) eps. dbscan::kNNdistplot(df, k = 5) abline(h = 0.15, lty = 2)
function [result,croppedImage] = isGoodPhoto(img) minWidth = 480; minHeight = 480; %minWidth = 128; %minHeight = 128; croppedImage = []; if isa(img,'char') img = imread(img); end if isa(img,'logical') result = 'binary'; return; end if ndims(img)>3 result = 'animation'; return; end if size(img,1)<minHeight || size(img,2)<minWidth result = 'too small'; return; end persistent emptyFlickrGIF; persistent emptyFlickrPNG; if isempty(emptyFlickrGIF) [emptyFlickrGIF,map]= imread('emptyFlickr.gif'); if ~isempty( map ) emptyFlickrGIF = ind2rgb( emptyFlickrGIF, map ); end end if isempty(emptyFlickrPNG) emptyFlickrPNG = imread('emptyFlickr.png'); end % check if it is flickr empty image imgT = imresize(img,[size(emptyFlickrGIF,1), size(emptyFlickrGIF,2)]); if size(imgT,3)==1 diff= sum(reshape(abs(im2double(imgT)-rgb2gray(emptyFlickrGIF)),1,[])); else diff= sum(reshape(abs(im2double(imgT)-emptyFlickrGIF),1,[])); end if diff<50 result = 'flickr empty'; return; end imgT = imresize(img,[size(emptyFlickrPNG,1), size(emptyFlickrPNG,2)]); if size(imgT,3)==1 diff= sum(reshape(abs(imgT-rgb2gray(emptyFlickrPNG)),1,[])); else diff= sum(reshape(abs(imgT-emptyFlickrPNG),1,[])); end if diff<50 result = 'flickr empty'; return; end % check if it is line drawing if size(img,3)==1 h = imhist(img); if sum(h(240:end))/sum(h) > 0.5 result = 'too white'; return; elseif sum(h(1:10))/sum(h) > 0.5 result = 'too black'; return; end else h = imhist(img(:,:,1)) + imhist(img(:,:,2)) + imhist(img(:,:,3)); if sum(h(240:end))/sum(h) > 0.6 result = 'too white'; return; elseif sum(h(1:10))/sum(h) > 0.8 result = 'too black'; return; end end imgG = img; G = fspecial('gaussian',[5 5],2); %# Filter it imgG = imfilter(imgG,G,'symmetric','same'); if size(imgG,3)>1 imgG = rgb2gray(imgG); end tto = edge(imgG,'canny'); if sum(tto(:))/numel(tto) < 0.01 result = 'too pure'; return; end %{ % check if it is line drawing imgG = img; if size(imgG,3)>1 imgG = rgb2gray(imgG); end h = imhist(imgG); if sum(h(240:end))/sum(h) > 0.5 result = 'too white'; return; elseif sum(h(1:10))/sum(h) > 0.5 result = 'too black'; return; else [~,ind]=max(h); if sum(h(max(1,ind-7):min(256,ind+7)))/sum(h) > 0.7 result = 'too pure'; return; end end %} % maybe useful http://www.mathworks.com/matlabcentral/fileexchange/25354-cropmat if size(img,3)==1 ttWhite = img>252; else ttWhite = img(:,:,1)>252 & img(:,:,2)>252 & img(:,:,3)>252; end if size(img,3)==1 ttBlack = img<5; else ttBlack = img(:,:,1)<5 & img(:,:,2)<5 & img(:,:,3)<5; end wWhite=sum(ttWhite,1) > size(tto,1)*0.7; hWhite=sum(ttWhite,2) > size(tto,2)*0.7; wBlack=sum(ttBlack,1) > size(tto,1)*0.7; hBlack=sum(ttBlack,2) > size(tto,2)*0.7; anyEdgeW = sum(tto,1) > size(tto,1)*0.01; anyEdgeH = sum(tto,2) > size(tto,2)*0.01; minW=find(anyEdgeW, 1 )-1+2; maxW=size(imgG,2)-find(anyEdgeW, 1, 'last' ); minH=find(anyEdgeH, 1 )-1+2; maxH=size(imgG,1)-find(anyEdgeH, 1, 'last' ); try if minW<3 || maxW<3 minW = 0; maxW = 0; else wMargin = wWhite | wBlack; if ~(any(wMargin(1:minW)) && any(wMargin(end-maxW:end))) minW = 0; maxW = 0; end end if minH<3 || maxH<3 minH = 0; maxH = 0; else hMargin = hWhite | hBlack; if ~(any(hMargin(1:minH)) && any(hMargin(end-maxH:end))) minH = 0; maxH = 0; end end if minW>0 || maxW>0 || minH>0 || maxH>0 croppedImage = img(minH+1:size(imgG,1)-maxH,minW+1:size(imgG,2)-maxW,:); result = 'crop'; if size(croppedImage,1)<minHeight || size(croppedImage,2)<minWidth result = 'too small'; end return; end catch end %{ % automatic image cropping % http://stackoverflow.com/questions/11121657/find-the-edges-of-image-and-crop-it-in-matlab %# instead of "==" you can check for similarity within a tolerance %tt=img(:,:,1)==img(:,:,2) & img(:,:,2) == img(:,:,3); if size(img,3)==1 tt = img>252; else tt = img(:,:,1)>252 & img(:,:,2)>252 & img(:,:,3)>252; end %# invert tt so that it's 1 where there is signal tt = ~tt; %# clean up some of the smaller artifacts tto = imopen(tt,strel('square',10)); %# get the areas and bounding box of the areas above threshold %# as an additional criterion, you could also use excentricity stats = regionprops(tto,'BoundingBox','Area'); if ~isempty(stats) area = cat(1,stats.Area); [~,maxAreaIdx] = max(area); bb = round(stats(maxAreaIdx).BoundingBox); %# note that regionprops switches x and y (it's a long story) croppedImage = img(bb(2):bb(2)+bb(4)-1,bb(1):bb(1)+bb(3)-1,:); if size(croppedImage,1)<size(img,1)-5 || size(croppedImage,2)<size(img,2)-5 result = 'crop'; return; end end %% black if size(img,3)==1 tt = img<5; else tt = img(:,:,1)<5 & img(:,:,2)<5 & img(:,:,3)<5; end %# invert tt so that it's 1 where there is signal tt = ~tt; %# clean up some of the smaller artifacts tto = imopen(tt,strel('square',10)); %# get the areas and bounding box of the areas above threshold %# as an additional criterion, you could also use excentricity stats = regionprops(tto,'BoundingBox','Area'); if ~isempty(stats) area = cat(1,stats.Area); [~,maxAreaIdx] = max(area); bb = round(stats(maxAreaIdx).BoundingBox); %# note that regionprops switches x and y (it's a long story) croppedImage = img(bb(2):bb(2)+bb(4)-1,bb(1):bb(1)+bb(3)-1,:); if size(croppedImage,1)<size(img,1)-5 || size(croppedImage,2)<size(img,2)-5 result = 'crop'; return; end end %} result = 'good'; return;
Reines participated in a number of nuclear tests , and writing reports on their results . These included Operation Crossroads at Bikini Atoll in 1946 , Operation Sandstone at Eniwetok Atoll in 1948 , and Operation Ranger and Operation Buster – Jangle at the Nevada Test Site . In 1951 he was the director of Operation Greenhouse series of nuclear tests in the Pacific . This saw the first American tests of boosted fission weapons , an important step towards thermonuclear weapons . He studied the effects of nuclear blasts , and co @-@ authored a paper with John von Neumann on Mach stem formation , an important aspect of an air blast wave .
Formal statement is: lemma decseqD: "decseq f \<Longrightarrow> i \<le> j \<Longrightarrow> f j \<le> f i" Informal statement is: If $f$ is a decreasing sequence, then $f(j) \leq f(i)$ for all $i \leq j$.
lemma continuous_on_inv_into: fixes f :: "'a::topological_space \<Rightarrow> 'b::t2_space" assumes s: "continuous_on s f" "compact s" and f: "inj_on f s" shows "continuous_on (f ` s) (the_inv_into s f)"
Require Import Omega. Require Import bigstep. Require Import coinduction. Require Import datatypes. Require Import Ndiv2oo. Require Import streams_vs_lists. (* Function div2(n) = n/2 if n is even undefined otherwise Example machine: 1 1 -> 1 B 1 B -> 2 R 2 1 -> 3 R 3 B -> 3 R 3 1 -> 4 B 4 B -> 2 R Definition div2: Spec := (1, one, W B, 1) :: (1, B , R, 2) :: (2, one, R, 3) :: (3, B , R, 3) :: (3, one, W B, 4) :: (4, B , R, 2) :: nil. *) (************************ Convergence proof ************************) Fixpoint repeat (n:nat): list Sym := match n with | 0 => nil | (S m) => (cons B (cons one (repeat m))) end. Lemma repeat_comm: forall n l, (Cons B (Cons one (app_ls (repeat n) l))) = (app_ls (repeat n) (Cons B (Cons one l))). induction n. simpl. reflexivity. simpl. intro. rewrite <- IHn. reflexivity. Qed. (* cycle from the state 2, if an even number of ones *) Lemma div2_stops_2even: forall n l, bf div2 (pair l (app_ls (ones (2*n)) Bs)) 2 (pair (app_ls (repeat n) l) Bs) 2. induction n. simpl. intro. apply bfH. unfold is_value. auto. simpl. intro. apply bfR with 3. auto. simpl. replace (n + S (n + 0)) with (S (2*n)). simpl. apply bfW with 4 B. auto. simpl. apply bfR with 2. auto. simpl. replace (n + (n + 0)) with (2*n). rewrite repeat_comm. apply IHn. omega. omega. Qed. (* stop from the starting state 1 *) Lemma div2_stops: forall n, bf div2 (pair Bs (Cons one (app_ls (ones (2*n)) Bs))) 1 (pair (app_ls (repeat n) (Cons B Bs)) Bs) 2. intros. apply bfW with 1 B. auto. simpl. apply bfR with 2. auto. simpl. replace (n + (n + 0)) with (2*n). apply div2_stops_2even. omega. Qed.
function s = mean(f, dim) %MEAN Average or mean value of a SPHEREFUN. % MEAN(F) takes the mean in the latitude-direction (default), i.e., % MEAN(F) = 1/pi sum(F). % % MEAN(F, DIM) takes the mean along the direction DIM. If DIM = 1 it is the % latitude-direction and if DIM = 2 then it is the longitude-direction. % % See also SPHEREFUN/MEAN2, SPHEREFUN/STD2. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % Empty check: if ( isempty( f ) ) s = chebfun; return end if ( nargin == 1) % Default to the y-direction: dim = 1; end dom = f.domain; s = sum( f, dim ); if ( dim == 1 ) s = s / pi; % Mean in the latitude direction (default) elseif ( dim == 2 ) s = s / (2*pi); % Mean in the longitude direction else error('CHEBFUN:SPHEREFUN:mean:dim', ... 'Mean not in longitude (LAMBDA) or latitude (THETA) direction.') end end
One of the Car Dealerships in town.
State Before: M : Type u_2 N : Type ?u.14217 G : Type ?u.14220 A : Type ?u.14223 B : Type ?u.14226 α : Type u_1 β : Type ?u.14232 γ : Type ?u.14235 δ : Type ?u.14238 inst✝¹ : SMul M α p : Prop inst✝ : Decidable p a : M b₁ b₂ : α ⊢ (a • if p then b₁ else b₂) = if p then a • b₁ else a • b₂ State After: no goals Tactic: split_ifs <;> rfl
is.installed <- function(mypkg) is.element(mypkg, installed.packages()[,1]) required.packages <- c('optparse', 'XML', 'Rsamtools', 'Repitools', 'rtracklayer' ) for (package in required.packages) { if (!is.installed(package)) { print (paste("ERROR! Package :", package, ": is missing!")) } }
function levenberg_marquardt(f::Function, g::Function, x0::Vector{Float64}; tolX=1e-8, tolG=1e-12, maxIter=100, lambda=100.0, show_trace=false, quiet=false) # finds argmin sum(f(x).^2) using the Levenberg-Marquardt algorithm # x # The function f should take an input vector of length n and return an output vector of length m # The function g is the Jacobian of f, and should be an m x n matrix # x0 is an initial guess for the solution # fargs is a tuple of additional arguments to pass to f # available options: # tolX - search tolerance in x # tolG - search tolerance in gradient # maxIter - maximum number of iterations # lambda - (inverse of) initial trust region radius # show_trace - print a status summary on each iteration if true # returns: x, J # x - least squares solution for x # J - estimate of the Jacobian of f at x const MAX_LAMBDA = 1e16 # minimum trust region radius const MIN_LAMBDA = 1e-16 # maximum trust region radius const MIN_STEP_QUALITY = 1e-3 const MIN_DIAGONAL = 1e-6 # lower bound on values of diagonal matrix used to regularize the trust region step converged = false iterCt = 0 x = x0 delta_x = copy(x0) f_calls = 0 g_calls = 0 fcur = f(x) f_calls += 1 residual = norm(fcur)^2 while ~converged && iterCt < maxIter J = g(x) g_calls += 1 # we want to solve: # argmin 0.5*||J(x)*delta_x + f(x)||^2 + lambda*||diagm(J'*J)*delta_x||^2 # Solving for the minimum gives: # (J'*J + lambda*DtD) * delta_x == -J^T * f(x), where DtD = diagm(sum(J.^2,1)) # Where we have used the equivalence: diagm(J'*J) = diagm(sum(J.^2, 1)) # It is additionally useful to bound the elements of DtD below to help # prevent "parameter evaporation". DtD = diagm(Float64[max(x, MIN_DIAGONAL) for x in sum(J.^2,1)]) delta_x = ( J'*J + sqrt(lambda)*DtD ) \ -J'*fcur # if the linear assumption is valid, our new residual should be: predicted_residual = norm(J*delta_x + fcur)^2 # check for numerical problems in solving for delta_x by ensuring that the predicted residual is smaller # than the current residual if predicted_residual > residual + 2max(eps(predicted_residual),eps(residual)) warn("""Problem solving for delta_x: predicted residual increase. $predicted_residual (predicted_residual) > $residual (residual) + $(eps(predicted_residual)) (eps)""") end # try the step and compute its quality trial_f = f(x + delta_x) f_calls += 1 trial_residual = norm(trial_f)^2 # step quality = residual change / predicted residual change rho = (trial_residual - residual) / (predicted_residual - residual) if rho > MIN_STEP_QUALITY x += delta_x fcur = trial_f residual = trial_residual # increase trust region radius lambda = max(0.1*lambda, MIN_LAMBDA) else # decrease trust region radius lambda = min(10*lambda, MAX_LAMBDA) end iterCt += 1 # check convergence criteria: # 1. Small gradient: norm(J^T * fcur, Inf) < tolG # 2. Small step size: norm(delta_x) < tolX converged = (norm(J' * fcur, Inf) < tolG) || (norm(delta_x) < tolX*(tolX + norm(x))) end x end function nlsfitworker(model::Function, y::Matrix{Float64}, x::Vector{Float64}, p0::Vector{Float64}) # performs Levenberg-Marquardt fitting nparams = length(p0) n = size(y,2) params = zeros(nparams, n) resids = similar(y) for j in 1:n f(p) = model(x, p) - y[:,j] g = Calculus.jacobian(f, :forward) results = levenberg_marquardt(f, g, p0; tolX=1e-3, tolG=1e-4, lambda=10.0) resids[:,j] = f(results) / sqrt(norm(y[:,j])) params[:,j] = results end (params, resids) end function nlsfit(f::Function, y::Matrix{Float64}, idxs::Vector{Int}, x::Vector{Float64}, p0::Vector{Float64}) tic() nt, n = size(y) nw = nworkers() nidxs = length(idxs) params = zeros(length(p0), n) resids = zeros(nt, n) dof = nt - length(p0) if nw > 1 reflist = Any[] idxperworker = round(Int, nidxs / nw) workeridxs = Any[idxs[(w-1)*idxperworker+1:min(w*idxperworker,nidxs)] for w in 1:nw] @dprint "fitting $nt x $idxperworker points on each of $nw workers" workerids = workers() for w in 1:nw r = @spawnat workerids[w] nlsfitworker(f, y[:,workeridxs[w]], x, p0) push!(reflist, r) end for w in 1:nw params[:,workeridxs[w]], resids[:,workeridxs[w]] = fetch(reflist[w]) end else # run on one CPU core @dprint "running $nt x $nidxs points on one CPU core" params[:,idxs], resids[:,idxs] = nlsfitworker(f, y[:,idxs], x, p0) end t = toq() vps = nidxs / t @dprint @sprintf "processed %d voxels in %.1f s (%.1f vox/s)\n" nidxs t vps (params, resids, dof) end
lemma norm_power: "norm (x ^ n) = norm x ^ n" for x :: "'a::real_normed_div_algebra"
%!TEX root = ../OGUSAdoc.tex We start the \ogindia section on modeling the household with a description of the demographics of the model. \citet{Nishiyama:2015} and \citet{DeBackerEtAl:2017} have recently shown that demographic dynamics are likely the biggest influence on macroeconomic time series, exhibiting more influence than fiscal variables or household preference parameters. In this chapter, we characterize the equations and parameters that govern the transition dynamics of the population distribution by age. In \ogindia, we take the approach of taking mortality rates and fertility rates from outside estimates. But we estimate our immigration rates as residuals using the mortality rates, fertility rates, and at least two consecutive periods of population distribution data. This approach makes sense if one modeling a country in which in one is not confident in the immigration rate data. If the country has good immigration data, then the immigration residual approach we describe below can be skipped. We define $\omega_{s,t}$ as the number of households of age $s$ alive at time $t$. A measure $\omega_{1,t}$ of households is born in each period $t$ and live for up to $E+S$ periods, with $S\geq 4$.\footnote{Theoretically, the model works without loss of generality for $S\geq 3$. However, because we are calibrating the ages outside of the economy to be one-fourth of $S$ (e.g., ages 21 to 100 in the economy, and ages 1 to 20 outside of the economy), it is convenient for $S$ to be at least 4.} Households are termed ``youth'', and do not participate in market activity during ages $1\leq s\leq E$. The households enter the workforce and economy in period $E+1$ and remain in the workforce until they unexpectedly die or live until age $s=E+S$. We model the population with households age $s\leq E$ outside of the workforce and economy in order most closely match the empirical population dynamics. The population of agents of each age in each period $\omega_{s,t}$ evolves according to the following function, \begin{equation}\label{EqPopLawofmotion} \begin{split} \omega_{1,t+1} &= (1 - \rho_0)\sum_{s=1}^{E+S} f_s\omega_{s,t} + i_1\omega_{1,t}\quad\forall t \\ \omega_{s+1,t+1} &= (1 - \rho_s)\omega_{s,t} + i_{s+1}\omega_{s+1,t}\quad\forall t\quad\text{and}\quad 1\leq s \leq E+S-1 \end{split} \end{equation} where $f_s\geq 0$ is an age-specific fertility rate, $i_s$ is an age-specific net immigration rate, $\rho_s$ is an age-specific mortality hazard rate, and $\rho_0$ is an infant mortality rate.\footnote{The parameter $\rho_s$ is the probability that a household of age $s$ dies before age $s+1$.} The total population in the economy $N_t$ at any period is simply the sum of households in the economy, the population growth rate in any period $t$ from the previous period $t-1$ is $g_{n,t}$, $\tilde{N}_t$ is the working age population, and $\tilde{g}_{n,t}$ is the working age population growth rate in any period $t$ from the previous period $t-1$. \begin{equation}\label{EqPopN} N_t\equiv\sum_{s=1}^{E+S} \omega_{s,t} \quad\forall t \end{equation} \begin{equation}\label{EqPopGrowth} g_{n,t+1} \equiv \frac{N_{t+1}}{N_t} - 1 \quad\forall t \end{equation} \begin{equation}\label{EqPopNtil} \tilde{N}_t\equiv\sum_{s=E+1}^{E+S} \omega_{s,t} \quad\forall t \end{equation} \begin{equation}\label{EqPopGrowthTil} \tilde{g}_{n,t+1} \equiv \frac{\tilde{N}_{t+1}}{\tilde{N}_t} - 1 \quad\forall t \end{equation} We discuss the approach to estimating fertility rates $f_s$, mortality rates $\rho_s$, and immigration rates $i_s$ in Sections \ref{SecDemogFert}, \ref{SecDemogMort}, and \ref{SecDemogImm}. \section{Fertility rates}\label{SecDemogFert} In \ogindia, we assume that the fertility rates for each age cohort $f_s$ are constant across time. However, this assumption is conceptually straightforward to relax. Our data for U.S. fertility rates by age come from \citet[Table 3, p. 18]{MartinEtAl:2015} National Vital Statistics Report, which is final fertility rate data for 2013. Figure \ref{FigFertRates} shows the fertility-rate data and the estimated average fertility rates for $E+S=100$. \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigFertRates}\textbf{Fertility rates by age ($f_s$) for $E+S=100$}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/fert_rates.png}}} \end{figure} The large blue circles are the 2013 U.S. fertility rate data from \citet{MartinEtAl:2015}. These are 9 fertility rates $[0.3, 12.3, 47.1, 80.7, 105.5, 98.0, 49.3, 10.4, 0.8]$ that correspond to the midpoint ages of the following age (in years) bins $[10-14, 15-17, 18-19, 20-24, 25-29, 30-34, 35-39, 40-44, 45-49]$. In order to get our cubic spline interpolating function to fit better at the endpoints we added to fertility rates of zero to ages 9 and 10, and we added two fertility rates of zero to ages 55 and 56. The blue line in Figure \ref{FigFertRates} shows the cubic spline interpolated function of the data. The red diamonds in Figure \ref{FigFertRates} are the average fertility rate in age bins spanning households born at the beginning of period 1 (time = 0) and dying at the end of their 100th year. Let the total number of model years that a household lives be $E+S\leq 100$. Then the span from the beginning of period 1 (the beginning of year 0) to the end of period 100 (the end of year 99) is divided up into $E+S$ bins of equal length. We calculate the average fertility rate in each of the $E+S$ model-period bins as the average population-weighted fertility rate in that span. The red diamonds in Figure \ref{FigFertRates} are the average fertility rates displayed at the midpoint in each of the $E+S$ model-period bins. \section{Mortality rates}\label{SecDemogMort} The mortality rates in our model $\rho_s$ are a one-period hazard rate and represent the probability of dying within one year, given that an household is alive at the beginning of period $s$. We assume that the mortality rates for each age cohort $\rho_s$ are constant across time. The infant mortality rate of $\rho_0=0.00587$ comes from the 2015 U.S. CIA World Factbook. Our data for U.S. mortality rates by age come from the Actuarial Life Tables of the U.S. Social Security Administration \citep[see][]{SocSec:2015}, from which the most recent mortality rate data is for 2011. Figure \ref{FigMortRates} shows the mortality rate data and the corresponding model-period mortality rates for $E+S=100$. \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigMortRates}\textbf{Mortality rates by age ($\rho_s$) for $E+S=100$}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/mort_rates.png}}} \end{figure} The mortality rates in Figure \ref{FigMortRates} are a population-weighted average of the male and female mortality rates reported in \citet{SocSec:2015}. Figure \ref{FigMortRates} also shows that the data provide mortality rates for ages up to 111-years-old. We truncate the maximum age in years in our model to 100-years old. In addition, we constrain the mortality rate to be 1.0 or 100 percent at the maximum age of 100. \section{Immigration rates}\label{SecDemogImm} Because of the difficulty in getting accurate immigration rate data by age, we estimate the immigration rates by age in our model $i_s$ as the average residual that reconciles the current-period population distribution with next period's population distribution given fertility rates $f_s$ and mortality rates $\rho_s$. Solving equations \eqref{EqPopLawofmotion} for the immigration rate $i_s$ gives the following characterization of the immigration rates in given population levels in any two consecutive periods $\omega_{s,t}$ and $\omega_{s,t+1}$ and the fertility rates $f_s$ and mortality rates $\rho_s$. \begin{equation}\label{EqPopImmRates} \begin{split} i_1 &= \frac{\omega_{1,t+1} - (1 - \rho_0)\sum_{s=1}^{E+S}f_s\omega_{s,t}}{\omega_{1,t}}\quad\forall t \\ i_{s+1} &= \frac{\omega_{s+1,t+1} - (1 - \rho_s)\omega_{s,t}}{\omega_{s+1,t}}\qquad\qquad\forall t\quad\text{and}\quad 1\leq s \leq E+S-1 \end{split} \end{equation} \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigImmRates}\textbf{Immigration rates by age ($i_s$), residual, $E+S=100$}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/imm_rates_orig.png}}} \end{figure} We calculate our immigration rates for three different consecutive-year-periods of population distribution data (2010 through 2013). Our four years of population distribution by age data come from \citet{Census:2015}. The immigration rates $i_s$ that we use in our model are the the residuals described in \eqref{EqPopImmRates} averaged across the three periods. Figure \ref{FigImmRates} shows the estimated immigration rates for $E+S=100$ and given the fertility rates from Section \ref{SecDemogFert} and the mortality rates from Section \ref{SecDemogMort}. At the end of Section \ref{SecDemogPopSSTP}, we describe a small adjustment that we make to the immigration rates after a certain number of periods in order to make computation of the transition path equilibrium of the model compute more robustly. \section{Population steady-state and transition path}\label{SecDemogPopSSTP} This model requires information about mortality rates $\rho_s$ in order to solve for the household's problem each period. It also requires the steady-state stationary population distribution $\bar{\omega}_{s}$ and population growth rate $\bar{g}_n$ as well as the full transition path of the stationary population distribution $\hat{\omega}_{s,t}$ and population grow rate $\tilde{g}_{n,t}$ from the current state to the steady-state. To solve for the steady-state and the transition path of the stationary population distribution, we write the stationary population dynamic equations \eqref{EqPopLawofmotionStat} and their matrix representation \eqref{EqPopLOMstatmat}. \begin{equation}\label{EqPopLawofmotionStat} \begin{split} \hat{\omega}_{1,t+1} &= \frac{(1-\rho_0)\sum_{s=1}^{E+S} f_s\hat{\omega}_{s,t} + i_1\hat{\omega}_{1,t}}{1+\tilde{g}_{n,t+1}}\quad\forall t \\ \hat{\omega}_{s+1,t+1} &= \frac{(1 - \rho_s)\hat{\omega}_{s,t} + i_{s+1}\hat{\omega}_{s+1,t}}{1+\tilde{g}_{n,t+1}}\qquad\quad\:\forall t\quad\text{and}\quad 1\leq s \leq E+S-1 \end{split} \end{equation} \begin{equation}\label{EqPopLOMstatmat} \begin{split} & \begin{bmatrix} \hat{\omega}_{1,t+1} \\ \hat{\omega}_{2,t+1} \\ \hat{\omega}_{2,t+1} \\ \vdots \\ \hat{\omega}_{E+S-1,t+1} \\ \hat{\omega}_{E+S,t+1} \end{bmatrix}= \frac{1}{1 + g_{n,t+1}} \times ... \\ & \begin{bmatrix} (1-\rho_0)f_1+i_1 & (1-\rho_0)f_2 & (1-\rho_0)f_3 & \hdots & (1-\rho_0)f_{E+S-1} & (1-\rho_0)f_{E+S} \\ 1-\rho_1 & i_2 & 0 & \hdots & 0 & 0 \\ 0 & 1-\rho_2 & i_3 & \hdots & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & \hdots & i_{E+S-1} & 0 \\ 0 & 0 & 0 & \hdots & 1-\rho_{E+S-1} & i_{E+S} \end{bmatrix} \begin{bmatrix} \hat{\omega}_{1,t} \\ \hat{\omega}_{2,t} \\ \hat{\omega}_{2,t} \\ \vdots \\ \hat{\omega}_{E+S-1,t} \\ \hat{\omega}_{E+S,t} \end{bmatrix} \end{split} \end{equation} We can write system \eqref{EqPopLOMstatmat} more simply in the following way. \begin{equation}\label{EqPopLOMstatmat2} \bm{\hat{\omega}}_{t+1} = \frac{1}{1+g_{n,t+1}}\bm{\Omega}\bm{\hat{\omega}}_t \quad\forall t \end{equation} The stationary steady-state population distribution $\bm{\bar{\omega}}$ is the eigenvector $\bm{\omega}$ with eigenvalue $(1+\bar{g}_n)$ of the matrix $\bm{\Omega}$ that satisfies the following version of \eqref{EqPopLOMstatmat2}. \begin{equation}\label{EqPopLOMss} (1+\bar{g}_n)\bm{\bar{\omega}} = \bm{\Omega}\bm{\bar{\omega}} \end{equation} \begin{proposition} If the age $s=1$ immigration rate is $i_1>-(1-\rho_0)f_1$ and the other immigration rates are strictly positive $i_s>0$ for all $s\geq 2$ such that all elements of $\bm{\Omega}$ are nonnegative, then there exists a unique positive real eigenvector $\bm{\bar{\omega}}$ of the matrix $\bm{\Omega}$, and it is a stable equilibrium. \end{proposition} \begin{proof} First, note that the matrix $\bm{\Omega}$ is square and non-negative. This is enough for a general version of the Perron-Frobenius Theorem to state that a positive real eigenvector exists with a positive real eigenvalue. This is not yet enough for uniqueness. For it to be unique by a version of the Perron-Fobenius Theorem, we need to know that the matrix is irreducible. This can be easily shown. The matrix is of the form $$\bm{\Omega} = \begin{bmatrix} * & * & * & \hdots & * & * & *\\ * & * & 0 & \hdots & 0 & 0 & 0 \\ 0 & * & * & \hdots & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \hdots & * & * & 0 \\ 0 & 0 & 0 & \hdots & 0 & * & * \end{bmatrix} $$ Where each * is strictly positive. It is clear to see that taking powers of the matrix causes the sub-diagonal positive elements to be moved down a row and another row of positive entries is added at the top. None of these go to zero since the elements were all non-negative to begin with. $$\bm{\Omega}^2 = \begin{bmatrix} * & * & * & \hdots & * & * & *\\ * & * & * & \hdots & * & * & * \\ 0 & * & * & \hdots & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & \hdots & * & * & 0 \\ 0 & 0 & 0 & \hdots & 0 & * & * \end{bmatrix}; ~~~ \bm{\Omega}^{S+E-1} = \begin{bmatrix} * & * & * & \hdots & * & * & *\\ * & * & * & \hdots & * & * & * \\ * & * & * & \hdots & * & * & * \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ * & * & * & \hdots & * & * & * \\ 0 & 0 & 0 & \hdots & 0 & * & * \end{bmatrix} $$ $$\bm{\Omega}^{S+E} = \begin{bmatrix} * & * & * & \hdots & * & * & *\\ * & * & * & \hdots & * & * & * \\ * & * & * & \hdots & * & * & * \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ * & * & * & \hdots & * & * & * \\ * & * & * & \hdots & * & * & * \end{bmatrix} $$ Existence of an $m \in \mathbb N $ such that $\left(\bf\Omega^m\right)_{ij} \neq 0 ~~ ( > 0)$ is one of the definitions of an irreducible (primitive) matrix. It is equivalent to saying that the directed graph associated with the matrix is strongly connected. Now the Perron-Frobenius Theorem for irreducible matrices gives us that the equilibrium vector is unique. We also know from that theorem that the eigenvalue associated with the positive real eigenvector will be real and positive. This eigenvalue, $p$, is the Perron eigenvalue and it is the steady state population growth rate of the model. By the PF Theorem for irreducible matrices, $| \lambda_i | \leq p$ for all eigenvalues $\lambda_i$ and there will be exactly $h$ eigenvalues that are equal, where $h$ is the period of the matrix. Since our matrix $\bf\Omega$ is aperiodic, the steady state growth rate is the unique largest eigenvalue in magnitude. This implies that almost all initial vectors will converge to this eigenvector under iteration. \end{proof} For a full treatment and proof of the Perron-Frobenius Theorem, see \citet{Suzumura:1983}. Because the population growth process is exogenous to the model, we calibrate it to annual age data for age years $s=1$ to $s=100$. Figure \ref{FigOrigVsFixSSpop} shows the steady-state population distribution $\bm{\bar{\omega}}$ and the population distribution after 120 periods $\bm{\hat{\omega}}_{120}$. Although the two distributions look very close to each other, they are not exactly the same. \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigOrigVsFixSSpop}\textbf{Theoretical steady-state population distribution vs. population distribution at period $t=120$}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/OrigVsFixSSpop.png}}} \end{figure} Further, we find that the maximum absolute difference between the population levels $\hat{\omega}_{s,t}$ and $\hat{\omega}_{s,t+1}$ was $1.3852\times 10^{-5}$ after 160 periods. That is to say, that after 160 periods, given the estimated mortality, fertility, and immigration rates, the population has not achieved its steady state. For convergence in our solution method over a reasonable time horizon, we want the population to reach a stationary distribution after $T$ periods. To do this, we artificially impose that the population distribution in period $t=120$ is the steady-state. As can be seen from Figure \ref{FigOrigVsFixSSpop}, this assumption is not very restrictive. Figure \ref{FigImmRateChg} shows the change in immigration rates that would make the period $t=120$ population distribution equal be the steady-state. The maximum absolute difference between any two corresponding immigration rates in Figure \ref{FigImmRateChg} is 0.0028. \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigImmRateChg}\textbf{Original immigration rates vs. adjusted immigration rates to make fixed steady-state population distribution}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/OrigVsAdjImm.png}}} \end{figure} The most recent year of population data come from \citet{Census:2015} population estimates for both sexes for 2013. We those data and use the population transition matrix \eqref{EqPopLOMstatmat2} to age it to the current model year of 2015. We then use \eqref{EqPopLOMstatmat2} to generate the transition path of the population distribution over the time period of the model. Figure \ref{FigPopDistPath} shows the progression from the 2013 population data to the fixed steady-state at period $t=120$. The time path of the growth rate of the economically active population $\tilde{g}_{n,t}$ is shown in Figure \ref{FigGrowthPath}. \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigPopDistPath}\textbf{Stationary population distribution at periods along transition path}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/PopDistPath.png}}} \end{figure} \begin{figure}[htbp]\centering \captionsetup{width=4.0in} \caption{\label{FigGrowthPath}\textbf{Time path of the population growth rate $\tilde{g}_{n,t}$}} \fbox{\resizebox{4.0in}{3.0in}{\includegraphics{./images/GrowthPath.png}}} \end{figure}
import numpy as np from glupy.math import ensure_cartesian from matplotlib.axes import Axes from mpl_toolkits.mplot3d import Axes3D from posekit.skeleton import Skeleton # Colours to use for groups of joints. Makes it easier to distinguish left from right. GROUP_COLOURS = dict( centre=(1.0, 0.0, 1.0), left=(0.0, 0.0, 1.0), right=(1.0, 0.0, 0.0), ) def plot_joints_2d(ax: Axes, joints_2d, skeleton: Skeleton, alpha=1.0, point_size=8, visibilities=None): artists = [] for joint_id, joint in enumerate(joints_2d): meta = skeleton.get_joint_metadata(joint_id) parent_id = meta['parent'] color = GROUP_COLOURS[meta['group']] if visibilities is not None: if not visibilities[joint_id] or not visibilities[parent_id]: color = tuple(map(lambda x: max(x, 0.65), color)) parent = joints_2d[parent_id] offset = parent - joint if np.linalg.norm(offset, ord=2) >= 1: artist = ax.arrow( joint[0], joint[1], offset[0], offset[1], color=color, alpha=alpha, head_width=2, length_includes_head=True, ) artists.append(artist) if point_size > 0: xs = joints_2d[..., 0:1] ys = joints_2d[..., 1:2] artists.append(ax.scatter(xs, ys, color='grey', alpha=alpha, s=point_size)) return artists def plot_joints_3d(ax: Axes3D, joints_3d, skeleton: Skeleton, invert=True, alpha=1.0, mask=None): """Plot a visual representation of the skeleton Matplotlib 3D axes.""" # NOTE: y and z axes are swapped, but we will relabel them appropriately. joints_3d = ensure_cartesian(np.asarray(joints_3d), d=3) xs = joints_3d[..., 0:1] ys = joints_3d[..., 2:3] zs = joints_3d[..., 1:2] ax.set_xlabel('x') ax.set_ylabel('z') ax.set_zlabel('y') # Correct aspect ratio (https://stackoverflow.com/a/21765085). max_range = np.array([ xs.max() - xs.min(), ys.max() - ys.min(), zs.max() - zs.min() ]).max() / 2.0 mid_x = (xs.max() + xs.min()) * 0.5 mid_y = (ys.max() + ys.min()) * 0.5 mid_z = (zs.max() + zs.min()) * 0.5 ax.set_xlim(mid_x - max_range, mid_x + max_range) ax.set_ylim(mid_y - max_range, mid_y + max_range) ax.set_zlim(mid_z - max_range, mid_z + max_range) if invert: ax.invert_zaxis() # Set starting view. ax.view_init(elev=20, azim=-100) artists = [] # Plot the bones as quivers. for joint_id, joint in enumerate(joints_3d): meta = skeleton.get_joint_metadata(joint_id) color = GROUP_COLOURS[meta['group']] parent_id = meta['parent'] if mask is not None: if not mask[joint_id] or not mask[parent_id]: color = tuple(map(lambda x: max(x, 0.65), color)) parent = joints_3d[parent_id] offset = parent - joint artists.append(ax.quiver( [joint[0]], [joint[2]], [joint[1]], [offset[0]], [offset[2]], [offset[1]], color=color, alpha=alpha, )) # Plot the joints as points. artists.append(ax.scatter(xs, ys, zs, color='grey', alpha=alpha)) return artists
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-} module Network.Trainer ( Trainer(..) , CostFunction , CostFunction' , TrainingData , Selection , StopCondition , quadraticCost , quadraticCost' , minibatch , online , trainNTimes , trainUntilErrorLessThan , trainUntil ) where import Network.Network import Network.Neuron import Network.Layer import System.Random import System.Random.Shuffle (shuffle') import Data.List.Split (chunksOf) import Numeric.LinearAlgebra -- | Trainer is a typeclass for all trainer types - a trainer will take in -- an instance of itself, a network, a list of training data, and return a -- new network trained on the data. class (Network n) => Trainer a n where fit :: Selection -> a -> n -> [TrainingData] -> n evaluate :: a -> n -> TrainingData -> Double -- | A CostFunction is used for evaluating a network's performance on a given -- input type CostFunction = Vector Double -> Vector Double -> Double -- | A CostFunction' (derivative) is used in backPropagation type CostFunction' = Vector Double -> Vector Double -> Vector Double -- | A tuple of (input, expected output) type TrainingData = (Vector Double, Vector Double) -- | A selection function for performing gradient descent type Selection = [TrainingData] -> [[TrainingData]] -- | A predicate (given a network, trainer, a list of training -- data, and the number of [fit]s performed) that -- tells the trainer to stop training type StopCondition t n = n -> t -> [TrainingData] -> Int -> Bool -- | The quadratic cost function (1/2) * sum (y - a) ^ 2 quadraticCost :: Vector Double -> Vector Double -> Double quadraticCost y a = sumElements $ 0.5 * (a - y) ** 2 -- | The derivative of the quadratic cost function sum (y - a) quadraticCost' :: Vector Double -> Vector Double -> Vector Double quadraticCost' y a = a - y -- | The minibatch function becomes a Selection when partially applied -- with the minibatch size minibatch :: Int -> [TrainingData] -> [[TrainingData]] minibatch size = chunksOf size -- | If we want to train the network online online :: [TrainingData] -> [[TrainingData]] online = minibatch 1 -- | This function returns true if the error of the network is less than -- a given error value, given a network, a trainer, a list of -- training data, and a counter (should start with 0) -- Note: Is there a way to have a counter with a recursive function -- without providing 0? networkErrorLessThan :: (Trainer t n) => Double -> n -> t -> [TrainingData] -> Int -> Bool networkErrorLessThan err network trainer dat _ = meanError < err where meanError = (sum errors) / fromIntegral (length errors) errors = map (evaluate trainer network) dat -- | Given a network, a trainer, a list of training data, -- and N, this function trains the network with the list of -- training data N times trainNTimes :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> Int -> n trainNTimes g network trainer s dat n = trainUntil g network trainer s dat completion 0 where completion _ _ _ n' = (n == n') -- | Given a network, a trainer, a list of training data, -- and an error value, this function trains the network with the list of -- training data until the error of the network (calculated -- by averaging the errors of each training data) is less than -- the given error value trainUntilErrorLessThan :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> Double -> n trainUntilErrorLessThan g network trainer s dat err = trainUntil g network trainer s dat (networkErrorLessThan err) 0 -- | This function trains a network until a given TrainCompletionPredicate -- is satisfied. trainUntil :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> StopCondition t n -> Int -> n trainUntil g network trainer s dat completion n = if completion network trainer dat n then network else trainUntil g' network' trainer s (shuffle' dat (length dat) g'') completion (n+1) where network' = fit s trainer network dat (g', g'') = split g
$\newcommand{\RR}{\mathbb{R}}$ $\newcommand{\R}[1]{\RR^{#1}}$ $\newcommand{\SO}[1]{\mathit{SO}(#1)}$ # The $\SO{3} \subset \SO{5}$ Subgroup Chain ## Background ACM uses the subgroup chain $\SO{3} \subset \SO{5}$ where $\SO{5}$ acts on the 5-dimensional space of quadrapole moments $q_M, M \in \{-2, -1, 0, 1, 2\}$ which transform as an $L=2$ irrep of $\SO{3}$. The inner product on this space is $|q|^2 = \sum_M |q_M|^2$. ## Problem Show that the action of $\SO{3}$ on the quadrapole moments leaves the norm invariant so that we have a subgroup inclusion $\SO{3} \subset \SO{5}$. ## The Fundamental Representation of $\SO{3}$ The fundamental representation of $\SO{3}$ acts on 3-dimensional space $\R{3}$ endowed with the usual Euclidean inner product. First we need to decide how to represent $\R{3}$. ## Real Numbers and Symbols SymPy supports real and complex numeric types. ```python from sympy import * mlue = Integer(42) mlue, mlue.is_real, type(mlue.is_real) ``` (42, True, bool) ```python alpha = Rational(1, 137) alpha, alpha.is_real, type(alpha.is_real) ``` (1/137, True, bool) By default, the real number status of symbols is undefined. ```python z = symbols('z') z.is_real, type(z.is_real) ``` (None, NoneType) SymPy also allows symbols to be explicitly declared as real. ```python w = symbols('w', real=False) w.is_real, type(w.is_real) ``` (False, bool) ```python a = symbols('a', real=True) a, a.is_real, type(a.is_real) ``` (a, True, bool) ## Vectors There are several ways to represent vectors in Python and SymPy. The simplest way might be to represent vectors in $\R{3}$ as SymPy matrices whose shape is (3, 1), i.e. as column vectors. ```python def is_real_matrix(A: Matrix) -> bool: return isinstance(A, Matrix) and all([a.is_real for a in A]) A1 = Matrix([[mlue, alpha], [a, 0]]) assert is_real_matrix(A1) A1 ``` $\displaystyle \left[\begin{matrix}42 & \frac{1}{137}\\a & 0\end{matrix}\right]$ ```python W = Matrix([w]) assert not is_real_matrix(Matrix([w])) W ``` $\displaystyle \left[\begin{matrix}w\end{matrix}\right]$ ```python def is_R3_vector(v: Matrix) -> bool: return is_real_matrix(v) and v.shape == (3, 1) e1 = Matrix([1, 0, 0]) assert is_R3_vector(e1) e1 ``` $\displaystyle \left[\begin{matrix}1\\0\\0\end{matrix}\right]$ ```python e1.shape ``` (3, 1) ```python type(e1) ``` sympy.matrices.dense.MutableDenseMatrix In SymPy, `Matrix` objects are mutable. Mathematically it is more natural to regard objects as immutable. Therefore, `ImmutableMatrix` should probably be used for the basis vectors of $\R{3}$. However, I'll never mutate the vectors so, for simplicity, I'll leave them as `Matrix` for now. ```python e2 = Matrix([0, 1, 0]) e2 ``` $\displaystyle \left[\begin{matrix}0\\1\\0\end{matrix}\right]$ ```python e3 = Matrix([0, 0, 1]) e3 ``` $\displaystyle \left[\begin{matrix}0\\0\\1\end{matrix}\right]$ SymPy implements scalar multiplication and vector addition naturally. ```python v1 = 3*e1 + 4*e2 - 5*e3 v1 ``` $\displaystyle \left[\begin{matrix}3\\4\\-5\end{matrix}\right]$ SymPy `Matrix` objects are iterable. ```python [(c, type(c)) for c in v1] ``` [(3, sympy.core.numbers.Integer), (4, sympy.core.numbers.Integer), (-5, sympy.core.numbers.Integer)] ```python [(i, c) for i, c in enumerate(v1)] ``` [(0, 3), (1, 4), (2, -5)] ## Dual Vectors Dual vectors are created using the transpose operator. ```python def is_R3_dual_vector(f: Matrix) -> bool: return is_real_matrix(f) and f.shape == (1, 3) f1 = e1.T assert(is_R3_dual_vector(f1)) f1 ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\end{matrix}\right]$ ```python [e for e in enumerate(f1)] ``` [(0, 1), (1, 0), (2, 0)] ```python f2 = e2.T f3 = e3.T f1 * v1 ``` $\displaystyle \left[\begin{matrix}3\end{matrix}\right]$ ```python v1.T * v1 ``` $\displaystyle \left[\begin{matrix}50\end{matrix}\right]$ ```python (v1.T * v1).shape ``` (1, 1) ```python [e for e in enumerate(v1.T * v1)] ``` [(0, 50)] ## Inner Product Note that multiplying a dual vector times a vector results in a matrix with shape (1, 1), not a scalar. ```python def inner_product(u: Matrix, v: Matrix) -> Basic: return (u.T * v)[0] norm_v1_squared = inner_product(v1, v1) norm_v1_squared, type(norm_v1_squared) ``` (50, sympy.core.numbers.Integer) ## Linear Transformations A linear transformation is naturally represented by a matrix with shape (3, 3). $\newcommand{\glR}[1]{\mathit{gl}({#1},\RR)}$ The set of linear transformations is denoted $\glR{3}$. ```python def is_gl3R(M: Matrix) -> bool: return is_real_matrix(M) and M.shape == (3, 3) is_gl3R(zeros(3, 3)) ``` True ```python from sympy import eye I3 = eye(3) I3 ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$ ```python I3 * v1 ``` $\displaystyle \left[\begin{matrix}3\\4\\-5\end{matrix}\right]$ ```python two_I = 2 * I3 two_I ``` $\displaystyle \left[\begin{matrix}2 & 0 & 0\\0 & 2 & 0\\0 & 0 & 2\end{matrix}\right]$ ```python two_I * v1 ``` $\displaystyle \left[\begin{matrix}6\\8\\-10\end{matrix}\right]$ ```python zero_M = zeros(3, 3) zero_M ``` $\displaystyle \left[\begin{matrix}0 & 0 & 0\\0 & 0 & 0\\0 & 0 & 0\end{matrix}\right]$ ```python zero_M * v1 ``` $\displaystyle \left[\begin{matrix}0\\0\\0\end{matrix}\right]$ ```python diag_123 = diag(1, 2, 3) diag_123 ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]$ ```python diag_123 * v1 ``` $\displaystyle \left[\begin{matrix}3\\8\\-15\end{matrix}\right]$ ## Bases We can express any vector $v$ as a unique linear combination of any three given linearly independent vectors, e.g. $e_1, e_2, e_3$. ```python a, b, c = symbols('a b c') lc = a * e1 + b * e2 + c * e3 lc ``` $\displaystyle \left[\begin{matrix}a\\b\\c\end{matrix}\right]$ ```python eqns = lc - v1 eqns ``` $\displaystyle \left[\begin{matrix}a - 3\\b - 4\\c + 5\end{matrix}\right]$ ```python A, B = linear_eq_to_matrix(eqns, [a, b, c]) A ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$ ```python B ``` $\displaystyle \left[\begin{matrix}3\\4\\-5\end{matrix}\right]$ ```python linsolve((A, B), [a, b, c]) ``` $\displaystyle \left\{\left( 3, \ 4, \ -5\right)\right\}$ ```python system = [eq for eq in eqns] system ``` [a - 3, b - 4, c + 5] ```python linsolve(system, [a, b, c]) ``` $\displaystyle \left\{\left( 3, \ 4, \ -5\right)\right\}$ ```python solution = { [a, b, c][i]: value for i, value in enumerate((3, 4, -5))} solution ``` {a: 3, b: 4, c: -5} ```python lc.subs(solution) ``` $\displaystyle \left[\begin{matrix}3\\4\\-5\end{matrix}\right]$ ```python lc.subs(solution) == v1 ``` True ## Nonsingular Linear Transformations $\newcommand{\GLR}[1]{\mathit{GL}({#1},\RR)}$ The nonsingular linear transformations are denoted $\GLR{3})$. ```python def is_GL3R(A: Matrix) -> bool: return is_gl3R(A) and simplify(det(A)) != 0 det(I3), type(det(I3)) ``` (1, sympy.core.numbers.One) ```python assert is_GL3R(I3) ``` ## Special Linear Transformations $\newcommand{\SLR}[1]{\mathit{SL}({#1},\RR)}$ The set of special linear transformations is denoted $\SLR{3}$. ```python def is_SL3R(A: Matrix) -> bool: return is_gl3R(A) and simplify(det(A)) == 1 assert is_SL3R(I3) ``` ## Orthogonal Transformations $\newcommand{\O}[1]{\mathit{O}({#1})}$ The set of orthogonal transformations is denoted $\O{3}$. They preserve the inner product. ```python def is_O3(M: Matrix) -> bool: return is_gl3R(M) and simplify(M.T * M) == eye(3) assert is_O3(I3) reflect_z = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, -1]]) assert is_O3(reflect_z) reflect_z ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & -1\end{matrix}\right]$ ## Special Orthogonal Transformations The set of special orthogonal transformations is denoted $\SO{3}$. They preserve orientation. ```python def is_SO3(M: Matrix) -> bool: return is_O3(M) and is_SL3R(M) assert is_SO3(I3) assert not is_SO3(reflect_z) ``` ## Rotations about the z-axis Let $R_z(\theta)$ denote a counter-clockwise rotation about the z-axis by the angle $\theta$. ```python def rotate_z(theta: Basic) -> Matrix: assert isinstance(theta, Basic) assert theta.is_real return Matrix([[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]) R_0 = rotate_z(S.Zero) assert is_SO3(R_0) R_0 ``` $\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$ ```python R_45 = rotate_z(pi/4) assert is_SO3(R_45) R_45 ``` $\displaystyle \left[\begin{matrix}\frac{\sqrt{2}}{2} & - \frac{\sqrt{2}}{2} & 0\\\frac{\sqrt{2}}{2} & \frac{\sqrt{2}}{2} & 0\\0 & 0 & 1\end{matrix}\right]$ ```python theta = symbols('theta', real=True) theta, theta.is_real ``` (theta, True) ```python R_theta = rotate_z(theta) assert is_SO3(R_theta) R_theta ``` $\displaystyle \left[\begin{matrix}\cos{\left(\theta \right)} & - \sin{\left(\theta \right)} & 0\\\sin{\left(\theta \right)} & \cos{\left(\theta \right)} & 0\\0 & 0 & 1\end{matrix}\right]$ ```python v1 ``` $\displaystyle \left[\begin{matrix}3\\4\\-5\end{matrix}\right]$ ```python R_theta * v1 ``` $\displaystyle \left[\begin{matrix}- 4 \sin{\left(\theta \right)} + 3 \cos{\left(\theta \right)}\\3 \sin{\left(\theta \right)} + 4 \cos{\left(\theta \right)}\\-5\end{matrix}\right]$ ## Bivectors Next consider the action $\rho$ of $\SO{3}$ on the tensor product $\R{3} \otimes \R{3}$. $$ \rho(R) (u \otimes v) = (R~u) \otimes (R~v) $$ Clearly $\R{3} \otimes \R{3}$ has dimension 9. We can represent its vectors as `Matrix` objects that have shape (9,1). We need to define a standard basis and the tensor product operation on vectors.
# Routines for taking steps using either Euler or SDC using FastGaussQuadrature function step_euler(dt, sol, solver, ubc1, ubc2) alpha = solver.alpha F1, F2 = ugradu(sol) RHS1 = alpha^2*(sol.U1 - dt*F1) RHS2 = alpha^2*(sol.U2 - dt*F2) newsol = solver.solve(RHS1, RHS2, ubc1, ubc2) return newsol end function step_bdf(dt, prevsol, sol, solver, ubc1, ubc2) alpha = solver.alpha F1, F2 = ugradu(sol) prevF1, prevF2 = ugradu(prevsol) RHS1 = 1/3*alpha^2*(4*sol.U1 - prevsol.U1 - 2*dt*(2*F1 - prevF1)) RHS2 = 1/3*alpha^2*(4*sol.U2 - prevsol.U2 - 2*dt*(2*F2 - prevF2)) newsol = solver.solve(RHS1, RHS2, ubc1, ubc2) return newsol end function sdc_substep(dt, sdc_order) return sdc_order > 1 ? dt / (sdc_order-1) : dt end function sdc_integration(M) # Setup substeps x = collect(linspace(-1, 1, M)) # Vandermonde matrix (transposed) At = ones(M,M) for m=2:M @. At[m, :] = At[m-1, :]*x end # Use Gauss-Legendre for quadrature xleg, wleg = gausslegendre(M) # Compute substep integration weights I = zeros(M,M-1) for m=1:M-1 a, b = x[m], x[m+1] wint = wleg*(b-a)/2 xint = (xleg+1)*(b-a)/2 + a xint_i = ones(M) p = zeros(M) p[1] = sum(wint) for i=2:M xint_i .*= xint p[i] = sum(wint .* xint_i) end I[:,m] = At\p end return I/2 end function step_sdc(dt, order, sol, solver, ubc1, ubc2) # TODO: Need to implement BC time dependence alpha = solver.alpha Re = alpha^2*dt P = order # order-1 can also work K = order if order>1 W = sdc_integration(P) else # Fallback to Euler P = 2 K = 1 end # Set initial conditions for all passes solutions = Array{Solution}(P, K) for k=1:K solutions[1, k] = sol end # First pass (k=0) # Eulers steps for m=1:P-1 init = solutions[m, 1] F1init, F2init = ugradu(init) RHS1 = alpha^2*init.U1 - Re*F1init RHS2 = alpha^2*init.U2 - Re*F2init solutions[m+1, 1] = solver.solve(RHS1, RHS2, ubc1, ubc2) end # Subsequent passes for k=1:K-1 for m=1:P-1 # Load historic stages that we need init = solutions[m, k+1] # Substep initial condition pred = solutions[m+1, k ] # Prediction hist = solutions[m , k ] # Prediction history # Post-process stages F1init, F2init = ugradu(init) # L1pred = alpha^2*pred.U1 - pred.RHS1 L2pred = alpha^2*pred.U2 - pred.RHS2 # F1hist, F2hist = ugradu(hist) # Integrate s = size(init.U1) I1, I2 = zeros(s), zeros(s) L = dt*(order-1) w = W[:, m]*L for n=1:P tmp = solutions[n, k] F1tmp, F2tmp = ugradu(tmp) L1tmp = alpha^2*tmp.U1 - tmp.RHS1 L2tmp = alpha^2*tmp.U2 - tmp.RHS2 I1 += w[n]*( L1tmp - Re*F1tmp ) I2 += w[n]*( L2tmp - Re*F2tmp ) end # f(t) = 1 + t # @show t1 = quadgk(f, dt*(m-1), dt*m)[1] # @show t2 = sum(w .* f(0:dt:dt*(P-1))) # @show t1-t2 # @assert abs(t1-t2)/abs(t1) < 1e-14 # Create new RHS RHS1 = alpha^2*init.U1 - Re*(F1init-F1hist) - L1pred + I1/dt RHS2 = alpha^2*init.U2 - Re*(F2init-F2hist) - L2pred + I2/dt # solutions[m+1, k+1] = solver.solve(RHS1, RHS2, ubc1, ubc2) end end if K>1 # Output error est (UNTESTED) maxnorm(v) = maximum(abs.(v)) l2norm(v) = sqrt(sum(vec(v.^2))) corr1 = solutions[P, K].U1 - solutions[P, K-1].U1 corr2 = solutions[P, K].U2 - solutions[P, K-1].U2 sol = solutions[P,K] info("U1 SDC err est: l2=", l2norm(corr1)/l2norm(sol.U1),", max=", maxnorm(corr1)/maxnorm(sol.U1)) info("U2 SDC err est: l2=", l2norm(corr2)/l2norm(sol.U2),", max=", maxnorm(corr2)/maxnorm(sol.U2)) end return solutions[P,K] # Original order 2 code # # First take Euler step # F1, F2 = ugradu(sol) # RHS1 = alpha^2*U1 - Re*F1 # RHS2 = alpha^2*U2 - Re*F2 # prov = solver.solve(RHS1, RHS2, ubc1, ubc2) # # Post process Euler step # F1prov, F2prov = ugradu(prov) # L1prov = alpha^2*prov.U1 - prov.RHS1 # L2prov = alpha^2*prov.U2 - prov.RHS2 # # Post process initial conds # L1 = alpha^2*sol.U1 - sol.RHS1 # L2 = alpha^2*sol.U2 - sol.RHS2 # # Integrate # I1 = (L1-Re*F1 + L1prov-Re*F1prov)/2 # I2 = (L2-Re*F2 + L2prov-Re*F2prov)/2 # # Take correction step # RHS1 = Re/dt*U1 - L1prov + Re*I1 # RHS2 = Re/dt*U2 - L2prov + Re*I2 # newsol = solver.solve(RHS1, RHS2, ubc1, ubc2) # return newsol end