Datasets:
AI4M
/

text
stringlengths
0
3.34M
lemma locally_diff_closed: "\<lbrakk>locally P S; closedin (top_of_set S) t\<rbrakk> \<Longrightarrow> locally P (S - t)"
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef NOMPI #include <mpi.h> #endif #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include "allvars.h" #include "proto.h" /*! \file driftfac.c * \brief compute loop-up tables for prefactors in cosmological integration */ static double logTimeBegin; static double logTimeMax; /*! This function computes look-up tables for factors needed in * cosmological integrations. The (simple) integrations are carried out * with the GSL library. Separate factors are computed for the "drift", * and the gravitational and hydrodynamical "kicks". The lookup-table is * used for reasons of speed. */ void init_drift_table(void) { #define WORKSIZE 100000 int i; double result, abserr; gsl_function F; gsl_integration_workspace *workspace; logTimeBegin = log(All.TimeBegin); logTimeMax = log(All.TimeMax); workspace = gsl_integration_workspace_alloc(WORKSIZE); for(i = 0; i < DRIFT_TABLE_LENGTH; i++) { F.function = &drift_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); DriftTable[i] = result; F.function = &gravkick_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); GravKickTable[i] = result; F.function = &hydrokick_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); HydroKickTable[i] = result; } gsl_integration_workspace_free(workspace); } /*! This function integrates the cosmological prefactor for a drift step * between time0 and time1. The value returned is * \f[ \int_{a_0}^{a_1} * \frac{{\rm d}a}{H(a)} * \f] */ double get_drift_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * DriftTable[0]; else df1 = DriftTable[i1 - 1] + (DriftTable[i1] - DriftTable[i1 - 1]) * (u1 - i1); u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * DriftTable[0]; else df2 = DriftTable[i2 - 1] + (DriftTable[i2] - DriftTable[i2 - 1]) * (u2 - i2); return df2 - df1; } /*! This function integrates the cosmological prefactor for a kick step of * the gravitational force. */ double get_gravkick_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * GravKickTable[0]; else df1 = GravKickTable[i1 - 1] + (GravKickTable[i1] - GravKickTable[i1 - 1]) * (u1 - i1); u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * GravKickTable[0]; else df2 = GravKickTable[i2 - 1] + (GravKickTable[i2] - GravKickTable[i2 - 1]) * (u2 - i2); return df2 - df1; } /*! This function integrates the cosmological prefactor for a kick step of * the hydrodynamical force. */ double get_hydrokick_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * HydroKickTable[0]; else df1 = HydroKickTable[i1 - 1] + (HydroKickTable[i1] - HydroKickTable[i1 - 1]) * (u1 - i1); u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * HydroKickTable[0]; else df2 = HydroKickTable[i2 - 1] + (HydroKickTable[i2] - HydroKickTable[i2 - 1]) * (u2 - i2); return df2 - df1; } /*! Integration kernel for drift factor computation. */ double drift_integ(double a, void *param) { double h; h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda; h = All.Hubble * sqrt(h); return 1 / (h * a * a * a); } /*! Integration kernel for gravitational kick factor computation. */ double gravkick_integ(double a, void *param) { double h; h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda; h = All.Hubble * sqrt(h); return 1 / (h * a * a); } /*! Integration kernel for hydrodynamical kick factor computation. */ double hydrokick_integ(double a, void *param) { double h; h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda; h = All.Hubble * sqrt(h); return 1 / (h * pow(a, 3 * GAMMA_MINUS1) * a); } double growthfactor_integ(double a, void *param) { double s; s = All.Omega0 + (1 - All.Omega0 - All.OmegaLambda) * a + All.OmegaLambda * a * a * a; s = sqrt(s); return pow(sqrt(a) / s, 3); }
State Before: R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι ⊢ (⨆ (i : ι), map (single i) (p i)) = pi Set.univ p State After: case intro R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι ⊢ (⨆ (i : ι), map (single i) (p i)) = pi Set.univ p Tactic: cases nonempty_fintype ι State Before: case intro R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι ⊢ (⨆ (i : ι), map (single i) (p i)) = pi Set.univ p State After: case intro.refine'_1 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι i : ι ⊢ map (single i) (p i) ≤ pi Set.univ p case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι ⊢ pi Set.univ p ≤ ⨆ (i : ι), map (single i) (p i) Tactic: refine' (iSup_le fun i => _).antisymm _ State Before: case intro.refine'_1 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι i : ι ⊢ map (single i) (p i) ≤ pi Set.univ p State After: case intro.refine'_1.intro.intro R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι i : ι x : φ i hx : x ∈ p i j : ι ⊢ ↑(single i) x j ∈ (fun i => ↑(p i)) j Tactic: rintro _ ⟨x, hx : x ∈ p i, rfl⟩ j - State Before: case intro.refine'_1.intro.intro R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι i : ι x : φ i hx : x ∈ p i j : ι ⊢ ↑(single i) x j ∈ (fun i => ↑(p i)) j State After: no goals Tactic: rcases em (j = i) with (rfl | hj) <;> simp [*] State Before: case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι ⊢ pi Set.univ p ≤ ⨆ (i : ι), map (single i) (p i) State After: case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι x : (i : ι) → φ i hx : x ∈ pi Set.univ p ⊢ x ∈ ⨆ (i : ι), map (single i) (p i) Tactic: intro x hx State Before: case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι x : (i : ι) → φ i hx : x ∈ pi Set.univ p ⊢ x ∈ ⨆ (i : ι), map (single i) (p i) State After: case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι x : (i : ι) → φ i hx : x ∈ pi Set.univ p ⊢ ∑ i : ι, Pi.single i (x i) ∈ ⨆ (i : ι), map (single i) (p i) Tactic: rw [← Finset.univ_sum_single x] State Before: case intro.refine'_2 R : Type u K : Type u' M : Type v V : Type v' M₂ : Type w V₂ : Type w' M₃ : Type y V₃ : Type y' M₄ : Type z ι : Type x ι' : Type x' inst✝⁴ : Semiring R φ : ι → Type u_1 inst✝³ : (i : ι) → AddCommMonoid (φ i) inst✝² : (i : ι) → Module R (φ i) I : Set ι p q : (i : ι) → Submodule R (φ i) x✝ : (i : ι) → φ i inst✝¹ : DecidableEq ι inst✝ : Finite ι val✝ : Fintype ι x : (i : ι) → φ i hx : x ∈ pi Set.univ p ⊢ ∑ i : ι, Pi.single i (x i) ∈ ⨆ (i : ι), map (single i) (p i) State After: no goals Tactic: exact sum_mem_iSup fun i => mem_map_of_mem (hx i trivial)
(**************************************************************************) (* This is part of EXCEPTIONS, it is distributed under the terms of the *) (* GNU Lesser General Public License version 3 *) (* (see file LICENSE for more details) *) (* *) (* Copyright 2015: Jean-Guillaume Dumas, Dominique Duval *) (* Burak Ekici, Damien Pous. *) (**************************************************************************) Require Import Relations Morphisms. Require Import Program. Require Prerequistes Terms Decorations Axioms Derived_CoProjections. Set Implicit Arguments. Module Make(Import M: Prerequistes.T). Module Export Derived_CoProductsExp := Derived_CoProjections.Make(M). Definition lcoprod {X1 Y1 X2 Y2} (f1: term X1 X2) (f2: term Y1 Y2) : term (X1 + Y1) (X2 + Y2) := copair (in1 o f1) (in2 o f2). Definition rcoprod {X Y X' Y'} (f1: term X X') (f2: term Y Y') : term (X+Y) (X'+Y') := rcopair (in1 o f1) (in2 o f2). Lemma is_lcoprod: forall k X' X Y' Y (f1: term X X') (f2: term Y Y'), PPG f1 -> is k f1 -> is k f2 -> is k (lcoprod f1 f2). (* FIXED *) Proof. intros k X' X Y' Y f1 f2 H1 H2 H3. induction k; edecorate. Qed. Lemma is_rcoprod: forall k X' X Y' Y (f1: term X X') (f2: term Y Y'), PPG f2 -> is k f1 -> is k f2 -> is k (rcoprod f1 f2). (* FIXED *) Proof. intros k X' X Y' Y f1 g2 H1 H2 H3. induction k; edecorate. Qed. Lemma w_lcoprod_eq: forall X1 X2 Y1 Y2 (f: term X1 X2) (g: term Y1 Y2), PPG f -> (lcoprod f g) o in1 ~ in1 o f. Proof. intros X1 X2 Y1 Y2 f g H. apply w_lcopair_eq; edecorate. Qed. Lemma s_lcoprod_eq: forall X1 X2 Y1 Y2 (f: term X1 X2) (g: term Y1 Y2), PPG f -> (lcoprod f g) o in2 == in2 o g. Proof. intros X1 X2 Y1 Y2 f g H. apply s_lcopair_eq; edecorate. Qed. Lemma s_rcoprod_eq: forall X1 X2 Y1 Y2 (f: term X1 X2) (g: term Y1 Y2), PPG g -> (rcoprod f g) o in1 == in1 o f. Proof. intros X1 X2 Y1 Y2 f g H. apply s_rcopair_eq; edecorate. Qed. Lemma w_rcoprod_eq: forall X1 X2 Y1 Y2 (f: term X1 X2) (g: term Y1 Y2), PPG g -> (rcoprod f g) o in2 ~ in2 o g. Proof. intros X1 X2 Y1 Y2 f g H. apply w_rcopair_eq; edecorate. Qed. Lemma lcoprod_u: forall X1 X2 Y1 Y2 (f1 f2: term (Y2 + Y1) (X2 + X1)), (f1 o in1 ~ f2 o in1) /\ (f1 o in2 == f2 o in2) -> f1 == f2. Proof. intros X1 X2 Y1 Y2 f1 f2 (H0&H1). apply lcopair_u. split; [exact H0| exact H1]. Qed. Lemma rcoprod_u: forall X1 X2 Y1 Y2 (f1 f2: term (Y2 + Y1) (X2 + X1)), (f1 o in1 == f2 o in1) /\ (f1 o in2 ~ f2 o in2) -> f1 == f2. Proof. intros X1 X2 Y1 Y2 f1 f2 (H0&H1). apply rcopair_u. split; [exact H0| exact H1]. Qed. End Make.
module Algebra.Solver.Ring.Sum import Algebra.Solver.Ring.Expr import Algebra.Solver.Ring.Prod import Algebra.Solver.Ring.SolvableRing import Algebra.Solver.Ring.Util %default total ||| A single term in a normalized arithmetic expressions. ||| ||| This is a product of all variables each raised to ||| a given power, multiplied with a factors (which is supposed ||| to reduce during elaboration). public export record Term (a : Type) (as : List a) where constructor T factor : a prod : Prod a as ||| Evaluate a term. public export eterm : Ring a => {as : List a} -> Term a as -> a eterm (T f p) = f * eprod p ||| Negate a term. public export negTerm : Ring a => Term a as -> Term a as negTerm (T f p) = T (negate f) p ||| Normalized arithmetic expression in a commutative ||| ring (represented as an (ordered) sum of terms). public export data Sum : (a : Type) -> (as : List a) -> Type where Nil : {0 as : List a} -> Sum a as (::) : {0 as : List a} -> Term a as -> Sum a as -> Sum a as ||| Evaluate a sum of terms. public export esum : Ring a => {as : List a} -> Sum a as -> a esum [] = 0 esum (x :: xs) = eterm x + esum xs ||| Negate a sum of terms. public export negate : Ring a => Sum a as -> Sum a as negate [] = [] negate (x :: y) = negTerm x :: negate y -------------------------------------------------------------------------------- -- Normalizer -------------------------------------------------------------------------------- ||| Add two sums of terms. ||| ||| The order of terms will be kept. If two terms have identical ||| products of variables, they will be unified by adding their ||| factors. public export add : SolvableRing a => Sum a as -> Sum a as -> Sum a as add [] ys = ys add xs [] = xs add (T m x :: xs) (T n y :: ys) = case compProd x y of LT => T m x :: add xs (T n y :: ys) GT => T n y :: add (T m x :: xs) ys EQ => T (m + n) y :: add xs ys ||| Normalize a sum of terms by removing all terms with a ||| `zero` factor. public export normSum : SolvableRing a => Sum a as -> Sum a as normSum [] = [] normSum (T f p :: y) = case isZero f of Just refl => normSum y Nothing => T f p :: normSum y ||| Multiplies a single term with a sum of terms. public export mult1 : SolvableRing a => Term a as -> Sum a as -> Sum a as mult1 (T f p) (T g q :: xs) = T (f * g) (mult p q) :: mult1 (T f p) xs mult1 _ [] = [] ||| Multiplies two sums of terms. public export mult : SolvableRing a => Sum a as -> Sum a as -> Sum a as mult [] ys = [] mult (x :: xs) ys = add (mult1 x ys) (mult xs ys) ||| Normalizes an arithmetic expression to a sum of products. public export norm : SolvableRing a => {as : List a} -> Expr a as -> Sum a as norm (Lit n) = [T n one] norm (Var x y) = [T 1 $ fromVar y] norm (Neg x) = negate $ norm x norm (Plus x y) = add (norm x) (norm y) norm (Mult x y) = mult (norm x) (norm y) norm (Minus x y) = add (norm x) (negate $ norm y) ||| Like `norm` but removes all `zero` terms. public export normalize : SolvableRing a => {as : List a} -> Expr a as -> Sum a as normalize e = normSum (norm e) -------------------------------------------------------------------------------- -- Proofs -------------------------------------------------------------------------------- -- Adding two sums via `add` preserves the evaluation result. 0 padd : SolvableRing a => (x,y : Sum a as) -> esum x + esum y === esum (add x y) padd [] xs = plusZeroLeftNeutral padd (x :: xs) [] = plusZeroRightNeutral padd (T m x :: xs) (T n y :: ys) with (compProd x y) proof eq _ | LT = Calc $ |~ (m * eprod x + esum xs) + (n * eprod y + esum ys) ~~ m * eprod x + (esum xs + (n * eprod y + esum ys)) ..< plusAssociative ~~ m * eprod x + esum (add xs (T n y :: ys)) ... cong (m * eprod x +) (padd xs (T n y :: ys)) _ | GT = Calc $ |~ (m * eprod x + esum xs) + (n * eprod y + esum ys) ~~ n * eprod y + ((m * eprod x + esum xs) + esum ys) ..< p213 ~~ n * eprod y + esum (add (T m x :: xs) ys) ... cong (n * eprod y +) (padd (T m x :: xs) ys) _ | EQ = case pcompProd x y eq of Refl => Calc $ |~ (m * eprod x + esum xs) + (n * eprod x + esum ys) ~~ (m * eprod x + n * eprod x) + (esum xs + esum ys) ... p1324 ~~ (m + n) * eprod x + (esum xs + esum ys) ..< cong (+ (esum xs + esum ys)) rightDistributive ~~ (m + n) * eprod x + esum (add xs ys) ... cong ((m + n) * eprod x +) (padd xs ys) -- Small utility lemma 0 psum0 : SolvableRing a => {x,y,z : a} -> x === y -> x === 0 * z + y psum0 prf = Calc $ |~ x ~~ y ... prf ~~ 0 + y ..< plusZeroLeftNeutral ~~ 0 * z + y ..< cong (+ y) multZeroLeftAbsorbs -- Multiplying a sum with a term preserves the evaluation result. 0 pmult1 : SolvableRing a => (m : a) -> (p : Prod a as) -> (s : Sum a as) -> esum (mult1 (T m p) s) === (m * eprod p) * esum s pmult1 m p [] = sym multZeroRightAbsorbs pmult1 m p (T n q :: xs) = Calc $ |~ (m * n) * (eprod (mult p q)) + esum (mult1 (T m p) xs) ~~ (m * n) * (eprod p * eprod q) + esum (mult1 (T m p) xs) ... cong (\x => (m*n) * x + esum (mult1 (T m p) xs)) (pmult p q) ~~ (m * eprod p) * (n * eprod q) + esum (mult1 (T m p) xs) ..< cong (+ esum (mult1 (T m p) xs)) m1324 ~~ (m * eprod p) * (n * eprod q) + (m * eprod p) * esum xs ... cong ((m * eprod p) * (n * eprod q) +) (pmult1 m p xs) ~~ (m * eprod p) * (n * eprod q + esum xs) ..< leftDistributive -- Multiplying two sums of terms preserves the evaluation result. 0 pmult : SolvableRing a => (x,y : Sum a as) -> esum x * esum y === esum (mult x y) pmult [] y = multZeroLeftAbsorbs pmult (T n x :: xs) y = Calc $ |~ (n * eprod x + esum xs) * esum y ~~ (n * eprod x) * esum y + esum xs * esum y ... rightDistributive ~~ (n * eprod x) * esum y + esum (mult xs y) ... cong ((n * eprod x) * esum y +) (pmult xs y) ~~ esum (mult1 (T n x) y) + esum (mult xs y) ..< cong (+ esum (mult xs y)) (pmult1 n x y) ~~ esum (add (mult1 (T n x) y) (mult xs y)) ... padd (mult1 (T n x) y) (mult xs y) -- Evaluating a negated term is equivalent to negate the -- result of evaluating the term. 0 pnegTerm : SolvableRing a => (x : Term a as) -> eterm (negTerm x) === neg (eterm x) pnegTerm (T f p) = multNegLeft -- Evaluating a negated sum of terms is equivalent to negate the -- result of evaluating the sum of terms. 0 pneg : SolvableRing a => (x : Sum a as) -> esum (negate x) === neg (esum x) pneg [] = sym $ negZero pneg (x :: y) = Calc $ |~ eterm (negTerm x) + esum (negate y) ~~ neg (eterm x) + esum (negate y) ... cong (+ esum (negate y)) (pnegTerm x) ~~ neg (eterm x) + neg (esum y) ... cong (neg (eterm x) +) (pneg y) ~~ neg (eterm x + esum y) ..< negDistributes -- Removing zero values from a sum of terms does not -- affect the evaluation result. 0 pnormSum : SolvableRing a => (s : Sum a as) -> esum (normSum s) === esum s pnormSum [] = Refl pnormSum (T f p :: y) with (isZero f) _ | Nothing = Calc $ |~ f * eprod p + esum (normSum y) ~~ f * eprod p + esum y ... cong ((f * eprod p) +) (pnormSum y) _ | Just refl = Calc $ |~ esum (normSum y) ~~ esum y ... pnormSum y ~~ 0 + esum y ..< plusZeroLeftNeutral ~~ 0 * eprod p + esum y ..< cong (+ esum y) multZeroLeftAbsorbs ~~ f * eprod p + esum y ..< cong (\x => x * eprod p + esum y) refl -- Evaluating an expression gives the same result as -- evaluating its normalized form. 0 pnorm : SolvableRing a => (e : Expr a as) -> eval e === esum (norm e) pnorm (Lit n) = Calc $ |~ n ~~ n * 1 ..< multOneRightNeutral ~~ n * eprod (one {as}) ..< cong (n *) (pone as) ~~ n * eprod (one {as}) + 0 ..< plusZeroRightNeutral pnorm (Var x y) = Calc $ |~ x ~~ eprod (fromVar y) ..< pvar as y ~~ 1 * eprod (fromVar y) ..< multOneLeftNeutral ~~ 1 * eprod (fromVar y) + 0 ..< plusZeroRightNeutral pnorm (Neg x) = Calc $ |~ neg (eval x) ~~ neg (esum (norm x)) ... cong neg (pnorm x) ~~ esum (negate (norm x)) ..< pneg (norm x) pnorm (Plus x y) = Calc $ |~ eval x + eval y ~~ esum (norm x) + eval y ... cong (+ eval y) (pnorm x) ~~ esum (norm x) + esum (norm y) ... cong (esum (norm x) +) (pnorm y) ~~ esum (add (norm x) (norm y)) ... padd _ _ pnorm (Mult x y) = Calc $ |~ eval x * eval y ~~ esum (norm x) * eval y ... cong (* eval y) (pnorm x) ~~ esum (norm x) * esum (norm y) ... cong (esum (norm x) *) (pnorm y) ~~ esum (mult (norm x) (norm y)) ... Sum.pmult _ _ pnorm (Minus x y) = Calc $ |~ eval x - eval y ~~ eval x + neg (eval y) ... minusIsPlusNeg ~~ esum (norm x) + neg (eval y) ... cong (+ neg (eval y)) (pnorm x) ~~ esum (norm x) + neg (esum (norm y)) ... cong (\v => esum (norm x) + neg v) (pnorm y) ~~ esum (norm x) + esum (negate (norm y)) ..< cong (esum (norm x) +) (pneg (norm y)) ~~ esum (add (norm x) (negate (norm y))) ... padd _ _ -- Evaluating an expression gives the same result as -- evaluating its normalized form. 0 pnormalize : SolvableRing a => (e : Expr a as) -> eval e === esum (normalize e) pnormalize e = Calc $ |~ eval e ~~ esum (norm e) ... pnorm e ~~ esum (normSum (norm e)) ..< pnormSum (norm e) -------------------------------------------------------------------------------- -- Solver -------------------------------------------------------------------------------- ||| Given a list `as` of variables and two arithmetic expressions ||| over these variables, if the expressions are converted ||| to the same normal form, evaluating them gives the same ||| result. ||| ||| This simple fact allows us to conveniently and quickly ||| proof arithmetic equalities required in other parts of ||| our code. For instance: ||| ||| ```idris example ||| 0 binom1 : {x,y : Bits8} ||| -> (x + y) * (x + y) === x * x + 2 * x * y + y * y ||| binom1 = solve [x,y] ||| ((x .+. y) * (x .+. y)) ||| (x .*. x + 2 *. x *. y + y .*. y) ||| ``` export 0 solve : SolvableRing a => (as : List a) -> (e1,e2 : Expr a as) -> (prf : normalize e1 === normalize e2) => eval e1 === eval e2 solve _ e1 e2 = Calc $ |~ eval e1 ~~ esum (normalize e1) ...(pnormalize e1) ~~ esum (normalize e2) ...(cong esum prf) ~~ eval e2 ..<(pnormalize e2) -------------------------------------------------------------------------------- -- Examples -------------------------------------------------------------------------------- 0 binom1 : {x,y : Bits8} -> (x + y) * (x + y) === x * x + 2 * x * y + y * y binom1 = solve [x,y] ((x .+. y) * (x .+. y)) (x .*. x + 2 *. x *. y + y .*. y) 0 binom2 : {x,y : Bits8} -> (x - y) * (x - y) === x * x - 2 * x * y + y * y binom2 = solve [x,y] ((x .-. y) * (x .-. y)) (x .*. x - 2 *. x *. y + y .*. y) 0 binom3 : {x,y : Bits8} -> (x + y) * (x - y) === x * x - y * y binom3 = solve [x,y] ((x .+. y) * (x .-. y)) (x .*. x - y .*. y)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! EVB-QMDFF - RPMD molecular dynamics and rate constant calculations on ! black-box generated potential energy surfaces ! ! Copyright (c) 2021 by Julien Steffen ([email protected]) ! Stefan Grimme ([email protected]) (QMDFF code) ! ! Permission is hereby granted, free of charge, to any person obtaining a ! copy of this software and associated documentation files (the "Software"), ! to deal in the Software without restriction, including without limitation ! the rights to use, copy, modify, merge, publish, distribute, sublicense, ! and/or sell copies of the Software, and to permit persons to whom the ! Software is furnished to do so, subject to the following conditions: ! ! The above copyright notice and this permission notice shall be included in ! all copies or substantial portions of the Software. ! ! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ! THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ! FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ! DEALINGS IN THE SOFTWARE. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! subroutine recross: Perform a complete recrossing factor ! calculation for the RPMD rate constant task ! ! part of EVB ! subroutine recross(rank,psize,dt,xi_ideal,energy_ts,kappa) use general use evb_mod implicit none ! ! include MPI library ! include 'mpif.h' integer::i,j,k,l,m,o ! loop index integer::rank ! the actual MPI processor ID real(kind=8)::pi ! pi.. real(kind=8)::dt ! the timestep in atomic units real(kind=8)::xi_ideal ! the xi value of the PMF max, set as constraint real(kind=8)::xi_real ! the real xi value, here =xi_ideal real(kind=8)::dxi_act(3,natoms) ! the derivative of xi real(kind=8)::d2xi_act(3,natoms,3,natoms) ! the hessian of xi real(kind=8)::derivs(3,natoms,nbeads) ! the gradient vector for all beads real(kind=8)::q_start(3,natoms,nbeads) ! the initial ts structure for reset real(kind=8)::q_save(3,natoms,nbeads) ! the start structure for a bunch of childs real(kind=8)::p_save(3,natoms,nbeads) ! the start momentum for a child pair real(kind=8)::q_1b(3,natoms) ! coordinate vector for one bead real(kind=8)::act_coord(3,natoms) ! coordinates for xi determination real(kind=8),dimension(3,natoms)::derivs_1d ! for gradient calculation real(kind=8)::kappa_num(child_evol) ! the time dependent recrossing factor real(kind=8)::Vpot ! the potential energy of the used PES real(kind=8)::en_act ! the actual energy real(kind=8)::fs,vs ! recrossing factor fractions real(kind=8)::k_save ! the stored force constant real(kind=8)::kappa_denom ! denominator for the recrossing factor calculation real(kind=8)::num_total(child_evol),denom_total ! the final kappa calculation real(kind=8)::kappa ! the final result! real(kind=8)::dt_info ! time in ps for information real(kind=8)::t_total,t_actual ! print out of elapsed parent times real(kind=8)::test123 ! for MPI debug real(kind=8)::energy_act ! the actual energy real(kind=8)::energy_ts ! energy of the transition state integer::andersen_save ! frequency for andersen thermostat (stored) ! for MPI parallelization integer::ierr,ID integer::psize,source,status(MPI_STATUS_SIZE) integer::count,tag_mpi,dest real(kind=8)::message(child_evol+2) integer::maxwork,numwork integer::loop_large ! number of loops over all slaves integer::loop_rest ! number of loops over remaining tasks integer::schedule ! info message for process integer::err_act,err_count,struc_reset,traj_error ! error handling variables pi=3.1415926535897932384d0 ! the pi dt_info=0.001*dt*2.41888428E-2 ! time in ps for information write out t_total=child_times*child_interv*0.001*dt*2.41888428E-2 ! the total ! time in ps that the parent trajectory will evolve t_actual=0.d0 ! the already vanished parent trajectory time ! ! store the start structure ! q_start=q_i ! ! first, equilibrate the parent trajectory: umbrella trajectory with ! infinite strong potential ! start with the TS structure (should be a good initial guess) ! ! Initialize the dynamics ! andersen_step=0 if (andersen_step .eq. 0) then andersen_step=int(dsqrt(dble(recr_equi))) end if if (rank .eq. 0) then ! ! first reset point ! 112 continue write(15,'(a,f11.4,a,f11.4,a)') " Evolving parent trajectory at Xi= ",xi_ideal, & & " for",real(recr_equi)*dt_info," ps." write(*,'(a,f11.4,a,f11.4,a)') " Evolving parent trajectory at Xi= ",xi_ideal, & & " for",real(recr_equi)*dt_info," ps." call mdinit_bias(xi_ideal,dxi_act,derivs,1,1) ! ! do dynamics with the verlet subroutine, constrain is activated ! do i=1,recr_equi call verlet_bias(i,dt,xi_ideal,xi_real,dxi_act,en_act,derivs,j,1) ! ! check the trajectory, if failed, go to beginning of trajectory ! --> check after some equilibration time first! ! if (recross_check .and. i .gt. 1000) then call rpmd_check(i,child_interv,4,0,0,en_act,xi_ideal,xi_ideal,energy_ts,& & err_act,struc_reset,err_count,traj_error) ! ! If too many errors occured, terminate the recrossing calculation, set a ! default recrossing coefficient of 0.5 and go back to main program ! if (err_count .gt. err_max) then write(*,*) "ERROR! The recrossing calculation cannot be finished due to" write(*,*) " a large amount of errors!" write(*,*) "A default recrossing value will be used instead (kappa=0.5)" kappa=0.5d0 return end if if (traj_error .eq. 1) then ! ! take the TS structure as good starting condition ! q_i=q_start goto 112 end if end if end do end if ! ! Set the time dependent recrossing factor to 0! ! num_total=0.d0 denom_total=0.d0 ! define default tag value tag_mpi=0 ! define default count value count=1 ! define the number of worksteps maxwork=child_times ! ! After the parent trajectory is equilibrated, sample it child_interv ! MD steps and start child_point child trajectories after it ! this will be repeated until all child trajectories are started ! (this are child_times big cycles ! All is done via the MPI master worker setup. The recrossing ! factor is transferred between the processes ! Before starting, broadcast the positions and momenta of the systems ! particles ! call mpi_bcast(q_i,natoms*3*nbeads,MPI_DOUBLE_PRECISION,0,MPI_COMM_WORLD,ierr) call mpi_bcast(p_i,natoms*3*nbeads,MPI_DOUBLE_PRECISION,0,MPI_COMM_WORLD,ierr) call mpi_bcast(xi_ideal,1,MPI_DOUBLE_PRECISION,0,MPI_COMM_WORLD,ierr) call mpi_barrier(mpi_comm_world,ierr) ! ! The master process (rank=0) it sends the actual child sampling tasks ! to the worker that will do the samplings for a bunch of child ! trajectories ! loop_large=int(child_times/(psize-1)) loop_rest=mod(child_times,psize-1) if (rank .eq. 0) then ! ! at first, give each slave a task until all full rounds are finished ! do i=1,loop_large+1 do j=1,psize-1 schedule=i if (i .eq. loop_large+1) then if (j .gt. loop_rest) then schedule=-1 else cycle end if end if dest=j ! ! print info message before each spawn wafe of child trajectories ! write(15,'(a,i6,a,f11.4,a)') " Spawning",child_point," child trajectories." write(15,'(a,f11.4,a,f11.4,a)') "Already",t_actual," ps of in total",t_total,& & " ps are elapsed." write(*,'(a,i6,a,f11.4,a)') " Spawning",child_point," child trajectories." write(*,'(a,f11.4,a,f11.4,a)') "Already",t_actual," ps of in total",t_total,& & " ps are elapsed." call mpi_send(schedule, count, MPI_DOUBLE_PRECISION, dest,tag_mpi,MPI_COMM_WORLD,ierr) end do ! ! recieve results from all slaves for the i'th round ! do j=1,psize-1 if (i .lt. loop_large+1) then message=0 call mpi_recv(message, child_evol+2, MPI_DOUBLE_PRECISION, MPI_ANY_SOURCE,tag_mpi, & & MPI_COMM_WORLD,status,ierr) t_actual=t_actual+message(1) denom_total=denom_total+message(2) num_total=num_total+(message(3:child_evol+2)) write(15,'(a,f12.8)') "The actual recrossing coefficient is: ",& & num_total(child_evol)/denom_total write(*,'(a,f12.8)') "The actual recrossing coefficient is: ",& & num_total(child_evol)/denom_total end if end do end do ! ! Now, do the remaining jobs (modulo) ! do j=1,loop_rest dest=j ! ! print info message before each spawn wafe of child trajectories ! write(15,'(a,i6,a,f11.4,a)') " Spawning",child_point," child trajectories." write(15,'(a,f11.4,a,f11.4,a)') "Already",t_actual," ps of in total",t_total,& & " ps are elapsed." write(*,'(a,i6,a,f11.4,a)') " Spawning",child_point," child trajectories." write(*,'(a,f11.4,a,f11.4,a)') "Already",t_actual," ps of in total",t_total,& & " ps are elapsed." call mpi_send(i, count, MPI_DOUBLE_PRECISION, dest,tag_mpi,MPI_COMM_WORLD,ierr) end do do j=1,loop_rest call mpi_recv(message, child_evol+2, MPI_DOUBLE_PRECISION, MPI_ANY_SOURCE,tag_mpi, & & MPI_COMM_WORLD,status,ierr) t_actual=t_actual+message(1) denom_total=denom_total+message(2) num_total=num_total+(message(3:child_evol+2)) write(15,'(a,f12.8)') "The actual recrossing coefficient is: ",& & num_total(child_evol)/denom_total write(*,'(a,f12.8)') "The actual recrossing coefficient is: ",& & num_total(child_evol)/denom_total end do ! ! Switch off the remaining processors ! do j=1,loop_rest dest=j call mpi_send(-1, count, MPI_DOUBLE_PRECISION, dest,tag_mpi,MPI_COMM_WORLD,ierr) end do else source=0 message=rank do call mpi_recv(numwork, count, MPI_DOUBLE_PRECISION, 0,tag_mpi,MPI_COMM_WORLD,status,ierr) ! ! If no more samplings are to do, exit with the current worker ! if (numwork .eq. -1) then exit end if ! ! reset the recross parameters for this child run ! t_actual=0.d0 num_total=0.d0 denom_total=0.d0 q_save=q_i ! store the current position to recap it in each child k_save=k_force ! store the force constant for the next parent time k_force=0.d0 ! set the force to zero for all childs! andersen_save=andersen_step ! save interval for thermostat andersen_step=0 ! no thermostat for the childs! ! ! print info message before each spawn wafe of child trajectories ! call andersen do j=1,child_point/2 ! ! start pairs of two childs with momenta of different signs! ! ! write(*,*) "before andersen!",p_i call andersen ! write(*,*) "after andersen!",p_i p_save=p_i do k=1,2 kappa_num=0.d0 kappa_denom=0.d0 if (k .eq. 1) then p_i=p_save else if (k .eq. 2) then p_i=-p_save end if q_i=q_save call get_centroid(act_coord) !extract centroid from q_i call calc_xi(act_coord,xi_ideal,xi_real,dxi_act,d2xi_act,2) ! ! calculate gradient for the whole ring polymer ! do l=1,nbeads q_1b=q_i(:,:,l) call gradient (q_1b,vpot,derivs_1d,l) derivs(:,:,l)=derivs_1d end do ! ! calculate the recrossing velocity for the recrossing factor ! vs = 0.0d0 do l = 1, 3 do m = 1, Natoms do o=1,nbeads vs = vs + dxi_act(l,m) * p_i(l,m,o) / mass(m) end do end do end do vs = vs/nbeads ! ! calculate the recrossing flux for the recrossing factor ! fs = 0.0d0 do l = 1, 3 do m = 1, Natoms fs = fs + dxi_act(l,m) * dxi_act(l,m) / mass(m) end do end do fs = sqrt(fs / (2.0d0 * pi * beta)) ! ! increase the denominator of kappa if the velocity is positive ! if (vs .gt. 0) then kappa_denom=kappa_denom+vs/fs end if ! ! now do the actual evaluation of the child trajectory ! no bias potential and no temperature shall be applied! ! ! do l=1,child_evol ! write(*,*) "centroid3!",q_i call verlet_bias(l,dt,xi_ideal,xi_real,dxi_act,en_act,derivs,m,2) if (xi_real .gt.0) then kappa_num(l)=kappa_num(l)+vs/fs end if end do num_total=num_total+kappa_num denom_total=denom_total+kappa_denom ! stop "HUohouhuo" end do end do ! ! use the configuration stored before the sampling of the child ! trajectories as if they never appeared! ! k_force=k_save andersen_step=andersen_save q_i=q_save andersen_step=0 ! ! second reset point ! 113 continue if (andersen_step .eq. 0) then andersen_step=int(dsqrt(dble(child_interv))) end if ! ! Also redo the initialization of the dynamics ! call mdinit_bias(xi_ideal,dxi_act,derivs,1,2) ! ! Sample the parent trajectory to generate a new starting configuration ! for the childs do j=1,child_interv call verlet_bias(i,dt,xi_ideal,xi_real,dxi_act,en_act,derivs,j,1) ! ! check the trajectory, if failed, go to beginning of trajectory ! if (recross_check) then call rpmd_check(j,child_interv,4,0,0,en_act,xi_ideal,xi_ideal,energy_ts,& & err_act,struc_reset,err_count,traj_error) ! ! If too many errors occured, terminate the recrossing calculation, set a ! default recrossing coefficient of 0.5 and go back to main program ! if (err_count .gt. err_max) then write(*,*) "ERROR! The recrossing calculation cannot be finished due to" write(*,*) " a large amount of errors!" write(*,*) "A default recrossing value will be used instead (kappa=0.5)" kappa=0.5d0 return end if if (traj_error .eq. 1) then ! ! take the TS structure as good starting condition ! q_i=q_save goto 113 end if end if end do ! ! increment the informational time that has elapsed so far ! t_actual=t_actual+child_interv*0.001*dt*2.41888428E-2 message(1)=t_actual message(2)=denom_total message(3:child_evol+1)=num_total call mpi_send(message, child_evol+2, MPI_DOUBLE_PRECISION, source,tag_mpi,MPI_COMM_WORLD,ierr) end do end if call mpi_barrier(mpi_comm_world,ierr) ! ! Write out the success message with the final recrossing factor ! Only for the master process ! kappa=num_total(child_evol)/denom_total if (rank .eq. 0) then write(15,*) write(15,*) "The recrossing calculation was successful!" write(15,'(a,f12.8)') "The final recrossing factor is:",kappa write(15,*) write(*,*) write(*,*) "The recrossing calculation was successful!" write(*,'(a,f12.8)') "The final recrossing factor is:",kappa write(*,*) ! ! write out the time dependent recrossing factor! ! open(unit=56,file="recrossing_time.dat",status="unknown") write(56,*) "# This is the time dependent recrossing factor calculated with EVB-QMDFF!" write(56,*) "#" write(56,*) "# t(fs) kappa(t) " write(56,*) "#" do i=1,child_evol write(56,*) i*dt*2.41888428E-2,num_total(i)/denom_total end do close(56) ! ! write out the final recrossing factor as restart for later calculations ! open(unit=33,file="recross_finished",status="unknown") write(33,*) kappa close(33) end if call mpi_barrier(mpi_comm_world,ierr) return end subroutine recross
function [diffx, diff_hor2]=horizondist(llhref, llhpos) Ce2n0=llh2dcm_v000(llhref(1:2),[0;1]); xyz_pos=ecef2geo_v000(llhpos,1); xyz_ref=ecef2geo_v000(llhref,1); diffx=Ce2n0*(xyz_pos-xyz_ref); diff_hor2=sqrt(sum(diffx(1:2).^2)); end
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Correctness of instruction selection for integer division *) Require Import String. Require Import Coqlib Maps. Require Import AST Errors Integers Floats. Require Import Values Memory Globalenvs Builtins Events Cminor Op CminorSel. Require Import SelectOp SelectOpproof SplitLong. Local Open Scope cminorsel_scope. Local Open Scope string_scope. (** * Properties of the helper functions *) Definition helper_declared {F V: Type} (p: AST.program (AST.fundef F) V) (id: ident) (name: string) (sg: signature) : Prop := (prog_defmap p)!id = Some (Gfun (External (EF_runtime name sg))). Definition helper_functions_declared {F V: Type} (p: AST.program (AST.fundef F) V) (hf: helper_functions) : Prop := helper_declared p i64_dtos "__compcert_i64_dtos" sig_f_l /\ helper_declared p i64_dtou "__compcert_i64_dtou" sig_f_l /\ helper_declared p i64_stod "__compcert_i64_stod" sig_l_f /\ helper_declared p i64_utod "__compcert_i64_utod" sig_l_f /\ helper_declared p i64_stof "__compcert_i64_stof" sig_l_s /\ helper_declared p i64_utof "__compcert_i64_utof" sig_l_s /\ helper_declared p i64_sdiv "__compcert_i64_sdiv" sig_ll_l /\ helper_declared p i64_udiv "__compcert_i64_udiv" sig_ll_l /\ helper_declared p i64_smod "__compcert_i64_smod" sig_ll_l /\ helper_declared p i64_umod "__compcert_i64_umod" sig_ll_l /\ helper_declared p i64_shl "__compcert_i64_shl" sig_li_l /\ helper_declared p i64_shr "__compcert_i64_shr" sig_li_l /\ helper_declared p i64_sar "__compcert_i64_sar" sig_li_l /\ helper_declared p i64_umulh "__compcert_i64_umulh" sig_ll_l /\ helper_declared p i64_smulh "__compcert_i64_smulh" sig_ll_l. (** * Correctness of the instruction selection functions for 64-bit operators *) Section CMCONSTR. Variable prog: program. Variable hf: helper_functions. Hypothesis HELPERS: helper_functions_declared prog hf. Let ge := Genv.globalenv prog. Variable sp: val. Variable e: env. Variable m: mem. Ltac DeclHelper := red in HELPERS; decompose [Logic.and] HELPERS; eauto. Lemma eval_helper: forall bf le id name sg args vargs vres, eval_exprlist ge sp e m le args vargs -> helper_declared prog id name sg -> lookup_builtin_function name sg = Some bf -> builtin_function_sem bf vargs = Some vres -> eval_expr ge sp e m le (Eexternal id sg args) vres. Proof. intros. red in H0. apply Genv.find_def_symbol in H0. destruct H0 as (b & P & Q). rewrite <- Genv.find_funct_ptr_iff in Q. econstructor; eauto. simpl. red. rewrite H1. constructor; auto. Qed. Corollary eval_helper_1: forall bf le id name sg arg1 varg1 vres, eval_expr ge sp e m le arg1 varg1 -> helper_declared prog id name sg -> lookup_builtin_function name sg = Some bf -> builtin_function_sem bf (varg1 :: nil) = Some vres -> eval_expr ge sp e m le (Eexternal id sg (arg1 ::: Enil)) vres. Proof. intros. eapply eval_helper; eauto. constructor; auto. constructor. Qed. Corollary eval_helper_2: forall bf le id name sg arg1 arg2 varg1 varg2 vres, eval_expr ge sp e m le arg1 varg1 -> eval_expr ge sp e m le arg2 varg2 -> helper_declared prog id name sg -> lookup_builtin_function name sg = Some bf -> builtin_function_sem bf (varg1 :: varg2 :: nil) = Some vres -> eval_expr ge sp e m le (Eexternal id sg (arg1 ::: arg2 ::: Enil)) vres. Proof. intros. eapply eval_helper; eauto. constructor; auto. constructor; auto. constructor. Qed. Remark eval_builtin_1: forall bf le id sg arg1 varg1 vres, eval_expr ge sp e m le arg1 varg1 -> lookup_builtin_function id sg = Some bf -> builtin_function_sem bf (varg1 :: nil) = Some vres -> eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: Enil)) vres. Proof. intros. econstructor. econstructor. eauto. constructor. simpl. red. rewrite H0. constructor. auto. Qed. Remark eval_builtin_2: forall bf le id sg arg1 arg2 varg1 varg2 vres, eval_expr ge sp e m le arg1 varg1 -> eval_expr ge sp e m le arg2 varg2 -> lookup_builtin_function id sg = Some bf -> builtin_function_sem bf (varg1 :: varg2 :: nil) = Some vres -> eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: arg2 ::: Enil)) vres. Proof. intros. econstructor. constructor; eauto. constructor; eauto. constructor. simpl. red. rewrite H1. constructor. auto. Qed. Definition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop := forall le a x, eval_expr ge sp e m le a x -> exists v, eval_expr ge sp e m le (cstr a) v /\ Val.lessdef (sem x) v. Definition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop := forall le a x b y, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> exists v, eval_expr ge sp e m le (cstr a b) v /\ Val.lessdef (sem x y) v. Ltac EvalOp := eauto; match goal with | [ |- eval_exprlist _ _ _ _ _ Enil _ ] => constructor | [ |- eval_exprlist _ _ _ _ _ (_:::_) _ ] => econstructor; EvalOp | [ |- eval_expr _ _ _ _ _ (Eletvar _) _ ] => constructor; simpl; eauto | [ |- eval_expr _ _ _ _ _ (Elet _ _) _ ] => econstructor; EvalOp | [ |- eval_expr _ _ _ _ _ (lift _) _ ] => apply eval_lift; EvalOp | [ |- eval_expr _ _ _ _ _ _ _ ] => eapply eval_Eop; [EvalOp | simpl; eauto] | _ => idtac end. Lemma eval_splitlong: forall le a f v sem, (forall le a b x y, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> exists v, eval_expr ge sp e m le (f a b) v /\ (forall p q, x = Vint p -> y = Vint q -> v = sem (Vlong (Int64.ofwords p q)))) -> match v with Vlong _ => True | _ => sem v = Vundef end -> eval_expr ge sp e m le a v -> exists v', eval_expr ge sp e m le (splitlong a f) v' /\ Val.lessdef (sem v) v'. Proof. intros until sem; intros EXEC UNDEF. unfold splitlong. case (splitlong_match a); intros. - InvEval; subst. exploit EXEC. eexact H2. eexact H3. intros [v' [A B]]. exists v'; split. auto. destruct v1; simpl in *; try (rewrite UNDEF; auto). destruct v0; simpl in *; try (rewrite UNDEF; auto). erewrite B; eauto. - exploit (EXEC (v :: le) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))). EvalOp. EvalOp. intros [v' [A B]]. exists v'; split. econstructor; eauto. destruct v; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto. Qed. Lemma eval_splitlong_strict: forall le a f va v, eval_expr ge sp e m le a (Vlong va) -> (forall le a1 a2, eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) -> eval_expr ge sp e m le a2 (Vint (Int64.loword va)) -> eval_expr ge sp e m le (f a1 a2) v) -> eval_expr ge sp e m le (splitlong a f) v. Proof. intros until v. unfold splitlong. case (splitlong_match a); intros. - InvEval. destruct v1; simpl in H; try discriminate. destruct v0; inv H. apply H0. rewrite Int64.hi_ofwords; auto. rewrite Int64.lo_ofwords; auto. - EvalOp. apply H0; EvalOp. Qed. Lemma eval_splitlong2: forall le a b f va vb sem, (forall le a1 a2 b1 b2 x1 x2 y1 y2, eval_expr ge sp e m le a1 x1 -> eval_expr ge sp e m le a2 x2 -> eval_expr ge sp e m le b1 y1 -> eval_expr ge sp e m le b2 y2 -> exists v, eval_expr ge sp e m le (f a1 a2 b1 b2) v /\ (forall p1 p2 q1 q2, x1 = Vint p1 -> x2 = Vint p2 -> y1 = Vint q1 -> y2 = Vint q2 -> v = sem (Vlong (Int64.ofwords p1 p2)) (Vlong (Int64.ofwords q1 q2)))) -> match va, vb with Vlong _, Vlong _ => True | _, _ => sem va vb = Vundef end -> eval_expr ge sp e m le a va -> eval_expr ge sp e m le b vb -> exists v, eval_expr ge sp e m le (splitlong2 a b f) v /\ Val.lessdef (sem va vb) v. Proof. intros until sem; intros EXEC UNDEF. unfold splitlong2. case (splitlong2_match a b); intros. - InvEval; subst. exploit (EXEC le h1 l1 h2 l2); eauto. intros [v [A B]]. exists v; split; auto. destruct v1; simpl in *; try (rewrite UNDEF; auto). destruct v0; try (rewrite UNDEF; auto). destruct v2; simpl in *; try (rewrite UNDEF; auto). destruct v3; try (rewrite UNDEF; auto). erewrite B; eauto. - InvEval; subst. exploit (EXEC (vb :: le) (lift h1) (lift l1) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))). EvalOp. EvalOp. EvalOp. EvalOp. intros [v [A B]]. exists v; split. econstructor; eauto. destruct v1; simpl in *; try (rewrite UNDEF; auto). destruct v0; try (rewrite UNDEF; auto). destruct vb; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto. - InvEval; subst. exploit (EXEC (va :: le) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil)) (lift h2) (lift l2)). EvalOp. EvalOp. EvalOp. EvalOp. intros [v [A B]]. exists v; split. econstructor; eauto. destruct va; try (rewrite UNDEF; auto). destruct v1; simpl in *; try (rewrite UNDEF; auto). destruct v0; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto. - exploit (EXEC (vb :: va :: le) (Eop Ohighlong (Eletvar 1 ::: Enil)) (Eop Olowlong (Eletvar 1 ::: Enil)) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))). EvalOp. EvalOp. EvalOp. EvalOp. intros [v [A B]]. exists v; split. EvalOp. destruct va; try (rewrite UNDEF; auto); destruct vb; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite ! Int64.ofwords_recompose; auto. Qed. Lemma eval_splitlong2_strict: forall le a b f va vb v, eval_expr ge sp e m le a (Vlong va) -> eval_expr ge sp e m le b (Vlong vb) -> (forall le a1 a2 b1 b2, eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) -> eval_expr ge sp e m le a2 (Vint (Int64.loword va)) -> eval_expr ge sp e m le b1 (Vint (Int64.hiword vb)) -> eval_expr ge sp e m le b2 (Vint (Int64.loword vb)) -> eval_expr ge sp e m le (f a1 a2 b1 b2) v) -> eval_expr ge sp e m le (splitlong2 a b f) v. Proof. assert (INV: forall v1 v2 n, Val.longofwords v1 v2 = Vlong n -> v1 = Vint(Int64.hiword n) /\ v2 = Vint(Int64.loword n)). { intros. destruct v1; simpl in H; try discriminate. destruct v2; inv H. rewrite Int64.hi_ofwords; rewrite Int64.lo_ofwords; auto. } intros until v. unfold splitlong2. case (splitlong2_match a b); intros. - InvEval. exploit INV. eexact H. intros [EQ1 EQ2]. exploit INV. eexact H0. intros [EQ3 EQ4]. subst. auto. - InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst. econstructor. eauto. apply H1; EvalOp. - InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst. econstructor. eauto. apply H1; EvalOp. - EvalOp. apply H1; EvalOp. Qed. Lemma is_longconst_sound: forall le a x n, is_longconst a = Some n -> eval_expr ge sp e m le a x -> x = Vlong n. Proof. unfold is_longconst; intros until n; intros LC. destruct (is_longconst_match a); intros. inv LC. InvEval. simpl in H5. inv H5. auto. discriminate. Qed. Lemma is_longconst_zero_sound: forall le a x, is_longconst_zero a = true -> eval_expr ge sp e m le a x -> x = Vlong Int64.zero. Proof. unfold is_longconst_zero; intros. destruct (is_longconst a) as [n|] eqn:E; try discriminate. revert H. predSpec Int64.eq Int64.eq_spec n Int64.zero. intros. subst. eapply is_longconst_sound; eauto. congruence. Qed. Lemma eval_lowlong: unary_constructor_sound lowlong Val.loword. Proof. unfold lowlong; red. intros until x. destruct (lowlong_match a); intros. InvEval; subst. exists v0; split; auto. destruct v1; simpl; auto. destruct v0; simpl; auto. rewrite Int64.lo_ofwords. auto. exists (Val.loword x); split; auto. EvalOp. Qed. Lemma eval_highlong: unary_constructor_sound highlong Val.hiword. Proof. unfold highlong; red. intros until x. destruct (highlong_match a); intros. InvEval; subst. exists v1; split; auto. destruct v1; simpl; auto. destruct v0; simpl; auto. rewrite Int64.hi_ofwords. auto. exists (Val.hiword x); split; auto. EvalOp. Qed. Lemma eval_longconst: forall le n, eval_expr ge sp e m le (longconst n) (Vlong n). Proof. intros. EvalOp. rewrite Int64.ofwords_recompose; auto. Qed. Theorem eval_intoflong: unary_constructor_sound intoflong Val.loword. Proof eval_lowlong. Theorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu. Proof. red; intros. unfold longofintu. econstructor; split. EvalOp. unfold Val.longofintu. destruct x; auto. replace (Int64.repr (Int.unsigned i)) with (Int64.ofwords Int.zero i); auto. apply Int64.same_bits_eq; intros. rewrite Int64.testbit_repr by auto. rewrite Int64.bits_ofwords by auto. fold (Int.testbit i i0). destruct (zlt i0 Int.zwordsize). auto. rewrite Int.bits_zero. rewrite Int.bits_above by lia. auto. Qed. Theorem eval_longofint: unary_constructor_sound longofint Val.longofint. Proof. red; intros. unfold longofint. destruct (longofint_match a). - InvEval. econstructor; split. apply eval_longconst. auto. - exploit (eval_shrimm ge sp e m (Int.repr 31) (x :: le) (Eletvar 0)). EvalOp. intros [v1 [A B]]. econstructor; split. EvalOp. destruct x; simpl; auto. simpl in B. inv B. simpl. replace (Int64.repr (Int.signed i)) with (Int64.ofwords (Int.shr i (Int.repr 31)) i); auto. apply Int64.same_bits_eq; intros. rewrite Int64.testbit_repr by auto. rewrite Int64.bits_ofwords by auto. rewrite Int.bits_signed by lia. destruct (zlt i0 Int.zwordsize). auto. assert (Int64.zwordsize = 2 * Int.zwordsize) by reflexivity. rewrite Int.bits_shr by lia. change (Int.unsigned (Int.repr 31)) with (Int.zwordsize - 1). f_equal. destruct (zlt (i0 - Int.zwordsize + (Int.zwordsize - 1)) Int.zwordsize); lia. Qed. Theorem eval_negl: unary_constructor_sound negl Val.negl. Proof. unfold negl; red; intros. destruct (is_longconst a) eqn:E. - econstructor; split. apply eval_longconst. exploit is_longconst_sound; eauto. intros EQ; subst x. simpl. auto. - exists (Val.negl x); split; auto. eapply (eval_builtin_1 (BI_standard BI_negl)); eauto. Qed. Theorem eval_notl: unary_constructor_sound notl Val.notl. Proof. red; intros. unfold notl. apply eval_splitlong; auto. intros. exploit eval_notint. eexact H0. intros [va [A B]]. exploit eval_notint. eexact H1. intros [vb [C D]]. exists (Val.longofwords va vb); split. EvalOp. intros; subst. simpl in *. inv B; inv D. simpl. unfold Int.not. rewrite <- Int64.decompose_xor. auto. destruct x; auto. Qed. Theorem eval_longoffloat: forall le a x y, eval_expr ge sp e m le a x -> Val.longoffloat x = Some y -> exists v, eval_expr ge sp e m le (longoffloat a) v /\ Val.lessdef y v. Proof. intros; unfold longoffloat. econstructor; split. eapply (eval_helper_1 (BI_standard BI_i64_dtos)); eauto. DeclHelper. auto. auto. Qed. Theorem eval_longuoffloat: forall le a x y, eval_expr ge sp e m le a x -> Val.longuoffloat x = Some y -> exists v, eval_expr ge sp e m le (longuoffloat a) v /\ Val.lessdef y v. Proof. intros; unfold longuoffloat. econstructor; split. eapply (eval_helper_1 (BI_standard BI_i64_dtou)); eauto. DeclHelper. auto. auto. Qed. Theorem eval_floatoflong: forall le a x y, eval_expr ge sp e m le a x -> Val.floatoflong x = Some y -> exists v, eval_expr ge sp e m le (floatoflong a) v /\ Val.lessdef y v. Proof. intros; unfold floatoflong. exists y; split; auto. eapply (eval_helper_1 (BI_standard BI_i64_stod)); eauto. DeclHelper. auto. simpl. destruct x; simpl in H0; inv H0; auto. Qed. Theorem eval_floatoflongu: forall le a x y, eval_expr ge sp e m le a x -> Val.floatoflongu x = Some y -> exists v, eval_expr ge sp e m le (floatoflongu a) v /\ Val.lessdef y v. Proof. intros; unfold floatoflongu. exists y; split; auto. eapply (eval_helper_1 (BI_standard BI_i64_utod)); eauto. DeclHelper. auto. simpl. destruct x; simpl in H0; inv H0; auto. Qed. Theorem eval_longofsingle: forall le a x y, eval_expr ge sp e m le a x -> Val.longofsingle x = Some y -> exists v, eval_expr ge sp e m le (longofsingle a) v /\ Val.lessdef y v. Proof. intros; unfold longofsingle. destruct x; simpl in H0; inv H0. destruct (Float32.to_long f) as [n|] eqn:EQ; simpl in H2; inv H2. exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B. apply Float32.to_long_double in EQ. eapply eval_longoffloat; eauto. simpl. change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto. Qed. Theorem eval_longuofsingle: forall le a x y, eval_expr ge sp e m le a x -> Val.longuofsingle x = Some y -> exists v, eval_expr ge sp e m le (longuofsingle a) v /\ Val.lessdef y v. Proof. intros; unfold longuofsingle. destruct x; simpl in H0; inv H0. destruct (Float32.to_longu f) as [n|] eqn:EQ; simpl in H2; inv H2. exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B. apply Float32.to_longu_double in EQ. eapply eval_longuoffloat; eauto. simpl. change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto. Qed. Theorem eval_singleoflong: forall le a x y, eval_expr ge sp e m le a x -> Val.singleoflong x = Some y -> exists v, eval_expr ge sp e m le (singleoflong a) v /\ Val.lessdef y v. Proof. intros; unfold singleoflong. exists y; split; auto. eapply (eval_helper_1 (BI_standard BI_i64_stof)); eauto. DeclHelper. auto. simpl. destruct x; simpl in H0; inv H0; auto. Qed. Theorem eval_singleoflongu: forall le a x y, eval_expr ge sp e m le a x -> Val.singleoflongu x = Some y -> exists v, eval_expr ge sp e m le (singleoflongu a) v /\ Val.lessdef y v. Proof. intros; unfold singleoflongu. exists y; split; auto. eapply (eval_helper_1 (BI_standard BI_i64_utof)); eauto. DeclHelper. auto. simpl. destruct x; simpl in H0; inv H0; auto. Qed. Theorem eval_andl: binary_constructor_sound andl Val.andl. Proof. red; intros. unfold andl. apply eval_splitlong2; auto. intros. exploit eval_and. eexact H1. eexact H3. intros [va [A B]]. exploit eval_and. eexact H2. eexact H4. intros [vb [C D]]. exists (Val.longofwords va vb); split. EvalOp. intros; subst. simpl in B; inv B. simpl in D; inv D. simpl. f_equal. rewrite Int64.decompose_and. auto. destruct x; auto. destruct y; auto. Qed. Theorem eval_orl: binary_constructor_sound orl Val.orl. Proof. red; intros. unfold orl. apply eval_splitlong2; auto. intros. exploit eval_or. eexact H1. eexact H3. intros [va [A B]]. exploit eval_or. eexact H2. eexact H4. intros [vb [C D]]. exists (Val.longofwords va vb); split. EvalOp. intros; subst. simpl in B; inv B. simpl in D; inv D. simpl. f_equal. rewrite Int64.decompose_or. auto. destruct x; auto. destruct y; auto. Qed. Theorem eval_xorl: binary_constructor_sound xorl Val.xorl. Proof. red; intros. unfold xorl. apply eval_splitlong2; auto. intros. exploit eval_xor. eexact H1. eexact H3. intros [va [A B]]. exploit eval_xor. eexact H2. eexact H4. intros [vb [C D]]. exists (Val.longofwords va vb); split. EvalOp. intros; subst. simpl in B; inv B. simpl in D; inv D. simpl. f_equal. rewrite Int64.decompose_xor. auto. destruct x; auto. destruct y; auto. Qed. Lemma is_intconst_sound: forall le a x n, is_intconst a = Some n -> eval_expr ge sp e m le a x -> x = Vint n. Proof. unfold is_intconst; intros until n; intros LC. destruct a; try discriminate. destruct o; try discriminate. destruct e0; try discriminate. inv LC. intros. InvEval. auto. Qed. Remark eval_shift_imm: forall (P: expr -> Prop) n a0 a1 a2 a3, (n = Int.zero -> P a0) -> (0 <= Int.unsigned n < Int.zwordsize -> Int.ltu n Int.iwordsize = true -> Int.ltu (Int.sub Int.iwordsize n) Int.iwordsize = true -> Int.ltu n Int64.iwordsize' = true -> P a1) -> (Int.zwordsize <= Int.unsigned n < Int64.zwordsize -> Int.ltu (Int.sub n Int.iwordsize) Int.iwordsize = true -> P a2) -> P a3 -> P (if Int.eq n Int.zero then a0 else if Int.ltu n Int.iwordsize then a1 else if Int.ltu n Int64.iwordsize' then a2 else a3). Proof. intros until a3; intros A0 A1 A2 A3. predSpec Int.eq Int.eq_spec n Int.zero. apply A0; auto. assert (NZ: Int.unsigned n <> 0). { red; intros. elim H. rewrite <- (Int.repr_unsigned n). rewrite H0. auto. } destruct (Int.ltu n Int.iwordsize) eqn:LT. exploit Int.ltu_iwordsize_inv; eauto. intros RANGE. assert (0 <= Int.zwordsize - Int.unsigned n < Int.zwordsize) by lia. apply A1. auto. auto. unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize. rewrite Int.unsigned_repr. rewrite zlt_true; auto. lia. generalize Int.wordsize_max_unsigned; lia. unfold Int.ltu. rewrite zlt_true; auto. change (Int.unsigned Int64.iwordsize') with 64. change Int.zwordsize with 32 in RANGE. lia. destruct (Int.ltu n Int64.iwordsize') eqn:LT'. exploit Int.ltu_inv; eauto. change (Int.unsigned Int64.iwordsize') with (Int.zwordsize * 2). intros RANGE. assert (Int.zwordsize <= Int.unsigned n). unfold Int.ltu in LT. rewrite Int.unsigned_repr_wordsize in LT. destruct (zlt (Int.unsigned n) Int.zwordsize). discriminate. lia. apply A2. tauto. unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize. rewrite Int.unsigned_repr. rewrite zlt_true; auto. lia. generalize Int.wordsize_max_unsigned; lia. auto. Qed. Lemma eval_shllimm: forall n, unary_constructor_sound (fun e => shllimm e n) (fun v => Val.shll v (Vint n)). Proof. unfold shllimm; red; intros. apply eval_shift_imm; intros. + (* n = 0 *) subst n. exists x; split; auto. destruct x; simpl; auto. change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero). rewrite Int64.shl_zero. auto. + (* 0 < n < 32 *) apply eval_splitlong with (sem := fun x => Val.shll x (Vint n)); auto. intros. exploit eval_shlimm. eexact H4. instantiate (1 := n). intros [v1 [A1 B1]]. exploit eval_shlimm. eexact H5. instantiate (1 := n). intros [v2 [A2 B2]]. exploit eval_shruimm. eexact H5. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]]. exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]]. econstructor; split. EvalOp. intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3. inv B1; inv B2; inv B3. simpl in B4. inv B4. simpl. rewrite Int64.decompose_shl_1; auto. destruct x; auto. + (* 32 <= n < 64 *) exploit eval_lowlong. eexact H. intros [v1 [A1 B1]]. exploit eval_shlimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]]. econstructor; split. EvalOp. destruct x; simpl; auto. destruct (Int.ltu n Int64.iwordsize'); auto. simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2. simpl. erewrite <- Int64.decompose_shl_2. instantiate (1 := Int64.hiword i). rewrite Int64.ofwords_recompose. auto. auto. + (* n >= 64 *) econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. reflexivity. reflexivity. auto. Qed. Theorem eval_shll: binary_constructor_sound shll Val.shll. Proof. unfold shll; red; intros. destruct (is_intconst b) as [n|] eqn:IC. - (* Immediate *) exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0. eapply eval_shllimm; eauto. - (* General case *) econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. reflexivity. auto. Qed. Lemma eval_shrluimm: forall n, unary_constructor_sound (fun e => shrluimm e n) (fun v => Val.shrlu v (Vint n)). Proof. unfold shrluimm; red; intros. apply eval_shift_imm; intros. + (* n = 0 *) subst n. exists x; split; auto. destruct x; simpl; auto. change (Int64.shru' i Int.zero) with (Int64.shru i Int64.zero). rewrite Int64.shru_zero. auto. + (* 0 < n < 32 *) apply eval_splitlong with (sem := fun x => Val.shrlu x (Vint n)); auto. intros. exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]]. exploit eval_shruimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]]. exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]]. exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]]. econstructor; split. EvalOp. intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3. inv B1; inv B2; inv B3. simpl in B4. inv B4. simpl. rewrite Int64.decompose_shru_1; auto. destruct x; auto. + (* 32 <= n < 64 *) exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. exploit eval_shruimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]]. econstructor; split. EvalOp. destruct x; simpl; auto. destruct (Int.ltu n Int64.iwordsize'); auto. simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2. simpl. erewrite <- Int64.decompose_shru_2. instantiate (1 := Int64.loword i). rewrite Int64.ofwords_recompose. auto. auto. + (* n >= 64 *) econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. reflexivity. reflexivity. auto. Qed. Theorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu. Proof. unfold shrlu; red; intros. destruct (is_intconst b) as [n|] eqn:IC. - (* Immediate *) exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0. eapply eval_shrluimm; eauto. - (* General case *) econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. reflexivity. auto. Qed. Lemma eval_shrlimm: forall n, unary_constructor_sound (fun e => shrlimm e n) (fun v => Val.shrl v (Vint n)). Proof. unfold shrlimm; red; intros. apply eval_shift_imm; intros. + (* n = 0 *) subst n. exists x; split; auto. destruct x; simpl; auto. change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero). rewrite Int64.shr_zero. auto. + (* 0 < n < 32 *) apply eval_splitlong with (sem := fun x => Val.shrl x (Vint n)); auto. intros. exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]]. exploit eval_shrimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]]. exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]]. exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]]. econstructor; split. EvalOp. intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3. inv B1; inv B2; inv B3. simpl in B4. inv B4. simpl. rewrite Int64.decompose_shr_1; auto. destruct x; auto. + (* 32 <= n < 64 *) exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. assert (eval_expr ge sp e m (v1 :: le) (Eletvar 0) v1) by EvalOp. exploit eval_shrimm. eexact H2. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]]. exploit eval_shrimm. eexact H2. instantiate (1 := Int.repr 31). intros [v3 [A3 B3]]. econstructor; split. EvalOp. destruct x; simpl; auto. destruct (Int.ltu n Int64.iwordsize'); auto. simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2. simpl in B3. inv B3. change (Int.ltu (Int.repr 31) Int.iwordsize) with true. simpl. erewrite <- Int64.decompose_shr_2. instantiate (1 := Int64.loword i). rewrite Int64.ofwords_recompose. auto. auto. + (* n >= 64 *) econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. reflexivity. reflexivity. auto. Qed. Theorem eval_shrl: binary_constructor_sound shrl Val.shrl. Proof. unfold shrl; red; intros. destruct (is_intconst b) as [n|] eqn:IC. - (* Immediate *) exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0. eapply eval_shrlimm; eauto. - (* General case *) econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. reflexivity. auto. Qed. Theorem eval_addl: Archi.ptr64 = false -> binary_constructor_sound addl Val.addl. Proof. unfold addl; red; intros. set (default := Ebuiltin (EF_builtin "__builtin_addl" sig_ll_l) (a ::: b ::: Enil)). assert (DEFAULT: exists v, eval_expr ge sp e m le default v /\ Val.lessdef (Val.addl x y) v). { econstructor; split. eapply eval_builtin_2; eauto. reflexivity. reflexivity. auto. } destruct (is_longconst a) as [p|] eqn:LC1; destruct (is_longconst b) as [q|] eqn:LC2. - exploit (is_longconst_sound le a); eauto. intros EQ; subst x. exploit (is_longconst_sound le b); eauto. intros EQ; subst y. econstructor; split. apply eval_longconst. simpl; auto. - predSpec Int64.eq Int64.eq_spec p Int64.zero; auto. subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x. exists y; split; auto. unfold Val.addl; rewrite H; destruct y; auto. rewrite Int64.add_zero_l; auto. - predSpec Int64.eq Int64.eq_spec q Int64.zero; auto. subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y. exists x; split; auto. unfold Val.addl; rewrite H; destruct x; simpl; auto. rewrite Int64.add_zero; auto. - auto. Qed. Theorem eval_subl: Archi.ptr64 = false -> binary_constructor_sound subl Val.subl. Proof. unfold subl; red; intros. set (default := Ebuiltin (EF_builtin "__builtin_subl" sig_ll_l) (a ::: b ::: Enil)). assert (DEFAULT: exists v, eval_expr ge sp e m le default v /\ Val.lessdef (Val.subl x y) v). { econstructor; split. eapply eval_builtin_2; eauto. reflexivity. reflexivity. auto. } destruct (is_longconst a) as [p|] eqn:LC1; destruct (is_longconst b) as [q|] eqn:LC2. - exploit (is_longconst_sound le a); eauto. intros EQ; subst x. exploit (is_longconst_sound le b); eauto. intros EQ; subst y. econstructor; split. apply eval_longconst. simpl; auto. - predSpec Int64.eq Int64.eq_spec p Int64.zero; auto. replace (Val.subl x y) with (Val.negl y). eapply eval_negl; eauto. subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x. destruct y; simpl; auto. - predSpec Int64.eq Int64.eq_spec q Int64.zero; auto. subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y. exists x; split; auto. unfold Val.subl; rewrite H; destruct x; simpl; auto. rewrite Int64.sub_zero_l; auto. - auto. Qed. Lemma eval_mull_base: binary_constructor_sound mull_base Val.mull. Proof. unfold mull_base; red; intros. apply eval_splitlong2; auto. - intros. set (p := Val.mull' x2 y2). set (le1 := p :: le0). assert (E1: eval_expr ge sp e m le1 (Eop Olowlong (Eletvar O ::: Enil)) (Val.loword p)) by EvalOp. assert (E2: eval_expr ge sp e m le1 (Eop Ohighlong (Eletvar O ::: Enil)) (Val.hiword p)) by EvalOp. exploit eval_mul. apply eval_lift. eexact H2. apply eval_lift. eexact H3. instantiate (1 := p). fold le1. intros [v3 [E3 L3]]. exploit eval_mul. apply eval_lift. eexact H1. apply eval_lift. eexact H4. instantiate (1 := p). fold le1. intros [v4 [E4 L4]]. exploit eval_add. eexact E2. eexact E3. intros [v5 [E5 L5]]. exploit eval_add. eexact E5. eexact E4. intros [v6 [E6 L6]]. exists (Val.longofwords v6 (Val.loword p)); split. EvalOp. eapply eval_builtin_2; eauto. reflexivity. reflexivity. intros. unfold le1, p in *; subst; simpl in *. inv L3. inv L4. inv L5. simpl in L6. inv L6. simpl. f_equal. symmetry. apply Int64.decompose_mul. - destruct x; auto; destruct y; auto. Qed. Lemma eval_mullimm: forall n, unary_constructor_sound (mullimm n) (fun v => Val.mull v (Vlong n)). Proof. unfold mullimm; red; intros. predSpec Int64.eq Int64.eq_spec n Int64.zero. subst n. econstructor; split. apply eval_longconst. destruct x; simpl; auto. rewrite Int64.mul_zero. auto. predSpec Int64.eq Int64.eq_spec n Int64.one. subst n. exists x; split; auto. destruct x; simpl; auto. rewrite Int64.mul_one. auto. destruct (Int64.is_power2' n) as [l|] eqn:P2. exploit eval_shllimm. eauto. instantiate (1 := l). intros [v [A B]]. exists v; split; auto. destruct x; simpl; auto. erewrite Int64.mul_pow2' by eauto. simpl in B. erewrite Int64.is_power2'_range in B by eauto. exact B. apply eval_mull_base; auto. apply eval_longconst. Qed. Theorem eval_mull: binary_constructor_sound mull Val.mull. Proof. unfold mull; red; intros. destruct (is_longconst a) as [p|] eqn:LC1; destruct (is_longconst b) as [q|] eqn:LC2. - exploit (is_longconst_sound le a); eauto. intros EQ; subst x. exploit (is_longconst_sound le b); eauto. intros EQ; subst y. econstructor; split. apply eval_longconst. simpl; auto. - exploit (is_longconst_sound le a); eauto. intros EQ; subst x. replace (Val.mull (Vlong p) y) with (Val.mull y (Vlong p)) in *. eapply eval_mullimm; eauto. destruct y; simpl; auto. rewrite Int64.mul_commut; auto. - exploit (is_longconst_sound le b); eauto. intros EQ; subst y. eapply eval_mullimm; eauto. - apply eval_mull_base; auto. Qed. Theorem eval_mullhu: forall n, unary_constructor_sound (fun a => mullhu a n) (fun v => Val.mullhu v (Vlong n)). Proof. unfold mullhu; intros; red; intros. econstructor; split; eauto. eapply eval_helper_2; eauto. apply eval_longconst. DeclHelper. reflexivity. reflexivity. Qed. Theorem eval_mullhs: forall n, unary_constructor_sound (fun a => mullhs a n) (fun v => Val.mullhs v (Vlong n)). Proof. unfold mullhs; intros; red; intros. econstructor; split; eauto. eapply eval_helper_2; eauto. apply eval_longconst. DeclHelper. reflexivity. reflexivity. Qed. Theorem eval_shrxlimm: forall le a n x z, Archi.ptr64 = false -> eval_expr ge sp e m le a x -> Val.shrxl x (Vint n) = Some z -> exists v, eval_expr ge sp e m le (shrxlimm a n) v /\ Val.lessdef z v. Proof. intros. apply Val.shrxl_shrl_2 in H1. unfold shrxlimm. destruct (Int.eq n Int.zero). - subst z; exists x; auto. - set (le' := x :: le). edestruct (eval_shrlimm (Int.repr 63) le' (Eletvar O)) as (v1 & A1 & B1). constructor. reflexivity. edestruct (eval_shrluimm (Int.sub (Int.repr 64) n) le') as (v2 & A2 & B2). eexact A1. edestruct (eval_addl H le' (Eletvar 0)) as (v3 & A3 & B3). constructor. reflexivity. eexact A2. edestruct (eval_shrlimm n le') as (v4 & A4 & B4). eexact A3. exists v4; split. econstructor; eauto. assert (X: forall v1 v2 n, Val.lessdef v1 v2 -> Val.lessdef (Val.shrl v1 (Vint n)) (Val.shrl v2 (Vint n))). { intros. inv H2; auto. } assert (Y: forall v1 v2 n, Val.lessdef v1 v2 -> Val.lessdef (Val.shrlu v1 (Vint n)) (Val.shrlu v2 (Vint n))). { intros. inv H2; auto. } subst z. eapply Val.lessdef_trans; [|eexact B4]. apply X. eapply Val.lessdef_trans; [|eexact B3]. apply Val.addl_lessdef; auto. eapply Val.lessdef_trans; [|eexact B2]. apply Y. auto. Qed. Theorem eval_divlu_base: forall le a b x y z, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.divlu x y = Some z -> exists v, eval_expr ge sp e m le (divlu_base a b) v /\ Val.lessdef z v. Proof. intros; unfold divlu_base. econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. eassumption. auto. Qed. Theorem eval_modlu_base: forall le a b x y z, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.modlu x y = Some z -> exists v, eval_expr ge sp e m le (modlu_base a b) v /\ Val.lessdef z v. Proof. intros; unfold modlu_base. econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. eassumption. auto. Qed. Theorem eval_divls_base: forall le a b x y z, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.divls x y = Some z -> exists v, eval_expr ge sp e m le (divls_base a b) v /\ Val.lessdef z v. Proof. intros; unfold divls_base. econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. eassumption. auto. Qed. Theorem eval_modls_base: forall le a b x y z, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.modls x y = Some z -> exists v, eval_expr ge sp e m le (modls_base a b) v /\ Val.lessdef z v. Proof. intros; unfold modls_base. econstructor; split. eapply eval_helper_2; eauto. DeclHelper. reflexivity. eassumption. auto. Qed. Remark decompose_cmpl_eq_zero: forall h l, Int64.eq (Int64.ofwords h l) Int64.zero = Int.eq (Int.or h l) Int.zero. Proof. intros. assert (Int64.zwordsize = Int.zwordsize * 2) by reflexivity. predSpec Int64.eq Int64.eq_spec (Int64.ofwords h l) Int64.zero. replace (Int.or h l) with Int.zero. rewrite Int.eq_true. auto. apply Int.same_bits_eq; intros. rewrite Int.bits_zero. rewrite Int.bits_or by auto. symmetry. apply orb_false_intro. transitivity (Int64.testbit (Int64.ofwords h l) (i + Int.zwordsize)). rewrite Int64.bits_ofwords by lia. rewrite zlt_false by lia. f_equal; lia. rewrite H0. apply Int64.bits_zero. transitivity (Int64.testbit (Int64.ofwords h l) i). rewrite Int64.bits_ofwords by lia. rewrite zlt_true by lia. auto. rewrite H0. apply Int64.bits_zero. symmetry. apply Int.eq_false. red; intros; elim H0. apply Int64.same_bits_eq; intros. rewrite Int64.bits_zero. rewrite Int64.bits_ofwords by auto. destruct (zlt i Int.zwordsize). assert (Int.testbit (Int.or h l) i = false) by (rewrite H1; apply Int.bits_zero). rewrite Int.bits_or in H3 by lia. exploit orb_false_elim; eauto. tauto. assert (Int.testbit (Int.or h l) (i - Int.zwordsize) = false) by (rewrite H1; apply Int.bits_zero). rewrite Int.bits_or in H3 by lia. exploit orb_false_elim; eauto. tauto. Qed. Lemma eval_cmpl_eq_zero: forall le a x, eval_expr ge sp e m le a (Vlong x) -> eval_expr ge sp e m le (cmpl_eq_zero a) (Val.of_bool (Int64.eq x Int64.zero)). Proof. intros. unfold cmpl_eq_zero. eapply eval_splitlong_strict; eauto. intros. exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1. exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp. instantiate (1 := Ceq). intros [v2 [A2 B2]]. unfold Val.cmp in B2; simpl in B2. rewrite <- decompose_cmpl_eq_zero in B2. rewrite Int64.ofwords_recompose in B2. destruct (Int64.eq x Int64.zero); inv B2; auto. Qed. Lemma eval_cmpl_ne_zero: forall le a x, eval_expr ge sp e m le a (Vlong x) -> eval_expr ge sp e m le (cmpl_ne_zero a) (Val.of_bool (negb (Int64.eq x Int64.zero))). Proof. intros. unfold cmpl_ne_zero. eapply eval_splitlong_strict; eauto. intros. exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1. exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp. instantiate (1 := Cne). intros [v2 [A2 B2]]. unfold Val.cmp in B2; simpl in B2. rewrite <- decompose_cmpl_eq_zero in B2. rewrite Int64.ofwords_recompose in B2. destruct (negb (Int64.eq x Int64.zero)); inv B2; auto. Qed. Lemma eval_cmplu_gen: forall ch cl a b le x y, eval_expr ge sp e m le a (Vlong x) -> eval_expr ge sp e m le b (Vlong y) -> eval_expr ge sp e m le (cmplu_gen ch cl a b) (Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y) then Int.cmpu cl (Int64.loword x) (Int64.loword y) else Int.cmpu ch (Int64.hiword x) (Int64.hiword y))). Proof. intros. unfold cmplu_gen. eapply eval_splitlong2_strict; eauto. intros. econstructor. econstructor. EvalOp. simpl. eauto. destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp. Qed. Remark int64_eq_xor: forall p q, Int64.eq p q = Int64.eq (Int64.xor p q) Int64.zero. Proof. intros. predSpec Int64.eq Int64.eq_spec p q. subst q. rewrite Int64.xor_idem. rewrite Int64.eq_true. auto. predSpec Int64.eq Int64.eq_spec (Int64.xor p q) Int64.zero. elim H. apply Int64.xor_zero_equal; auto. auto. Qed. Theorem eval_cmplu: forall c le a x b y v, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.cmplu (Mem.valid_pointer m) c x y = Some v -> Archi.ptr64 = false -> eval_expr ge sp e m le (cmplu c a b) v. Proof. intros. unfold Val.cmplu, Val.cmplu_bool in H1. rewrite H2 in H1. simpl in H1. destruct x; simpl in H1; try discriminate H1; destruct y; inv H1. rename i into x. rename i0 into y. destruct c; simpl. - (* Ceq *) exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B. rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto. - (* Cne *) exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B. rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto. - (* Clt *) exploit (eval_cmplu_gen Clt Clt). eexact H. eexact H0. simpl. rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto. - (* Cle *) exploit (eval_cmplu_gen Clt Cle). eexact H. eexact H0. intros. rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y). rewrite Int64.decompose_leu. auto. - (* Cgt *) exploit (eval_cmplu_gen Cgt Cgt). eexact H. eexact H0. simpl. rewrite Int.eq_sym. rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto. - (* Cge *) exploit (eval_cmplu_gen Cgt Cge). eexact H. eexact H0. intros. rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y). rewrite Int64.decompose_leu. rewrite Int.eq_sym. auto. Qed. Lemma eval_cmpl_gen: forall ch cl a b le x y, eval_expr ge sp e m le a (Vlong x) -> eval_expr ge sp e m le b (Vlong y) -> eval_expr ge sp e m le (cmpl_gen ch cl a b) (Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y) then Int.cmpu cl (Int64.loword x) (Int64.loword y) else Int.cmp ch (Int64.hiword x) (Int64.hiword y))). Proof. intros. unfold cmpl_gen. eapply eval_splitlong2_strict; eauto. intros. econstructor. econstructor. EvalOp. simpl. eauto. destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp. Qed. Remark decompose_cmpl_lt_zero: forall h l, Int64.lt (Int64.ofwords h l) Int64.zero = Int.lt h Int.zero. Proof. intros. generalize (Int64.shru_lt_zero (Int64.ofwords h l)). change (Int64.shru (Int64.ofwords h l) (Int64.repr (Int64.zwordsize - 1))) with (Int64.shru' (Int64.ofwords h l) (Int.repr 63)). rewrite Int64.decompose_shru_2. change (Int.sub (Int.repr 63) Int.iwordsize) with (Int.repr (Int.zwordsize - 1)). rewrite Int.shru_lt_zero. destruct (Int64.lt (Int64.ofwords h l) Int64.zero); destruct (Int.lt h Int.zero); auto; intros. elim Int64.one_not_zero. auto. elim Int64.one_not_zero. auto. vm_compute. intuition congruence. Qed. Theorem eval_cmpl: forall c le a x b y v, eval_expr ge sp e m le a x -> eval_expr ge sp e m le b y -> Val.cmpl c x y = Some v -> eval_expr ge sp e m le (cmpl c a b) v. Proof. intros. unfold Val.cmpl in H1. destruct x; simpl in H1; try discriminate. destruct y; inv H1. rename i into x. rename i0 into y. destruct c; simpl. - (* Ceq *) exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B. rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto. - (* Cne *) exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B. rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto. - (* Clt *) destruct (is_longconst_zero b) eqn:LC. + exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0. exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1. inv B1. exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp. instantiate (1 := Clt). intros [v2 [A2 B2]]. unfold Val.cmp in B2. simpl in B2. rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero. destruct (Int.lt (Int64.hiword x) Int.zero); inv B2; auto. + exploit (eval_cmpl_gen Clt Clt). eexact H. eexact H0. simpl. rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto. - (* Cle *) exploit (eval_cmpl_gen Clt Cle). eexact H. eexact H0. intros. rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y). rewrite Int64.decompose_le. auto. - (* Cgt *) exploit (eval_cmpl_gen Cgt Cgt). eexact H. eexact H0. simpl. rewrite Int.eq_sym. rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto. - (* Cge *) destruct (is_longconst_zero b) eqn:LC. + exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0. exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1; inv B1. exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp. instantiate (1 := Cge). intros [v2 [A2 B2]]. unfold Val.cmp in B2; simpl in B2. rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero. destruct (negb (Int.lt (Int64.hiword x) Int.zero)); inv B2; auto. + exploit (eval_cmpl_gen Cgt Cge). eexact H. eexact H0. intros. rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y). rewrite Int64.decompose_le. rewrite Int.eq_sym. auto. Qed. End CMCONSTR.
# CHEM 1000 - Spring 2022 Prof. Geoffrey Hutchison, University of Pittsburgh ## Graded Homework 6 For this homework, we'll focus on: - integrals in 2D polar and 3D spherical space - probability (including integrating continuous distributions) --- As a reminder, you do not need to use Python to solve the problems. If you want, you can use other methods, just put your answers in the appropriate places. To turn in, either download as Notebook (.ipynb) or Print to PDF and upload to Gradescope. Make sure you fill in any place that says YOUR CODE HERE or "YOUR ANSWER HERE", as well as your name and collaborators (i.e., anyone you discussed this with) below: ```python NAME = "" COLLABORATORS = "" ``` ### Cartesian to Spherical Integrals Consider the Cartesian integral: $$ \iiint z^{2} d x d y d z $$ Evaluation is fairly simple over a rectangular region, but if we wish to evaluate across a spherical volume, the limits of integration become messy. Instead, we can transform $z^2$, resulting in the integral: $$ \int_{0}^{a} \int_{0}^{\pi} \int_{0}^{2 \pi}(r \cos \theta)^{2} r^{2} \sin \theta d \varphi d \theta d r $$ Integrate across a sphere of size "a" ```python from sympy import init_session init_session() ``` ```python a, r, theta, phi = symbols("N r theta phi") # technically, we're integrating psi**2 but let's not worry about that now # z => (r*cos(theta)) in spherical coordinates f = (r*cos(theta)**2) integrate(# something) ``` ### Normalizing We often wish to normalize functions. Calculate a normalization constant $N^2$ for the following integral (e.g., evaluate it, set it equal to one, etc.) $$ \int_{0}^{\infty} \int_{0}^{\pi} \int_{0}^{2 \pi} N^2 \mathrm{e}^{-2 r} \cos ^{2} \theta r^{2} \sin \theta d \varphi d \theta d r $$ (This is related to a $2p_z$ hydrogen atomic orbital.) ```python # if you have an error, make sure you run the cell above this N, r, theta, phi = symbols("N r theta phi") # technically, we're integrating psi**2 but let's not worry about that now f = N**2 * exp(-2*r) * cos(theta)**2 integrate(# something) ``` ### Gaussian Distribution and Probability You may have heard much about the Gaussian "normal" distribution ("Bell curve"). If we flip a coin enough, the binomial distribution becomes essentially continuous. Moreover, the "law of large numbers" (i.e., the [central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)) indicates that by taking the enough data points, the sum - and average will tend towards a Gaussian distribution. In short, even if our underlying data comes from some different distribution, the average will become normal (e.g. consider the average velocities in an ideal gas - a mole is a big number). We will spend some time on the Gaussian distribution. - mean $x_0$ - standard deviation $\sigma$, variance $\sigma^2$ A normalized Gaussian distribution is then: $$ p(x) =\frac{1}{\sqrt{2 \pi \sigma^{2}}} \exp \left[-\frac{\left(x-x_{0}\right)^{2}}{2 \sigma^{2}}\right] $$ If the mean $x_0 = 0$, what fraction of data will fall: - within $\pm 0.5\sigma$ - within one standard deviation - within $\pm 1.5 \sigma$ - within $\pm 2.0 \sigma$ (In other words, change the limits of integration on the probability function.) ```python sigma = symbols('sigma') p = (1/sqrt(2*pi*sigma**2))*exp((-x**2)/(2*sigma**2)) simplify(integrate(p, (x, -0.5*sigma, +0.5*sigma))) ``` ### If we want to include "error bars" with 95% confidence, what intervals do we use? YOUR ANSWER HERE What about 99% confidence intervals?
\chapter{Conclusion} %The developed application, called OmniPlay, succeeds in offering a way to incorporate exercises with playing games. A physical therapist can come up with gestures that fit the needs of the patient and link each of these gestures to a keyboard key. As such, any game that can be played with keyboard controls can be played with this application, independent of the chosen gestures. This makes OmniPlay possibly more profitable than custom designed games because it gives patients a very large pool of games to choose from and helps keeping them motivated to do all needed gestures.\\ %The therapist is able to input all required gestures without any programming knowledge. Machine learning algorithms are used to evaluate which of the gestures is performed by the patient and allow the therapist to support the patient in a different way, by focusing together with the patient on playing the game instead of counting the number of times a gesture is done. The way SVM is used to recognize the executed gesture minimizes the time between a gesture execution and a reaction from the application. This allows for a more pleasant experience for the patient while playing games, as they feel more responsive.\\ %Special attention is paid to the application running smooth during its use. The application updates the user's avatar drawn on the interface at a rate of 30 FPS, which is as fast as the Kinect 2.0 camera can measure new data. As an important form of feedback, this helps mimicking user movement in real-time and keeps the user immersed into the experience.\\ %The GUI uses visual elements that express their function through feedforward. The goal is to use objects that users can recognize from real life and inherently know how to interact with. A gentle learning curve paves the way for new users in minimizing the amount of additional information needed before the application can be used. By naturally coupling action to reaction, feedback informs the user of how an interaction affects the application and makes it easier to understand the result of it.\\ The developed application, called OmniPlay, succeeds in offering a way to incorporate exercises with playing games. A physical therapist can come up with gestures that fit the needs of the patient and link each of these gestures to a keyboard key. As such, any game that can be played with keyboard controls can be played with this application, independent of the chosen gestures. This makes OmniPlay potentially more profitable than custom designed games, as it gives patients a very large pool of games to choose from and helps keeping them motivated to do all needed gestures.\\ A machine learning algorithm using support vector machines is used to evaluate the gestures performed by the user. When a recorded gesture is recognized, OmniPlay virtually presses the keyboard button that is assigned to that gesture. By employing a system of splitting the gesture into a number of postures, the OmniPlay can be used to effectively play games using gestures.\\ Using prototypes consisting of mime or hints patterns of interaction combined with WIMP elements, user tests are conducted to come to the conclusion that a combination of elements following the mime pattern and WIMP elements is preferred. The most important aspects of the UI are its simplicity, that all possible actions are permanently on screen and usage of clear and familiar metaphors. From these criteria, a coded prototype is developed where the user can record and evaluate gestures to be used to play any game. A user test demonstrates that the physical therapist is able to input all required gestures without needing any programming knowledge. After some introductory explanation, he is able to find effective gestures on his own that he can use to play a game found online.\\ In the end design of the UI, a proper color coding of the UI elements combined with a well chosen activation threshold for important actions such as the delete button can give the user easy access to these functions without causing accidental activations. An analysis of the design using Wensveen's framework shows that a significant amount of coupling between the action and the function is done via two layers of augmented feedback and feedforward.
function [NABF]=analysis_nabf(f,I1,I2) % function [QABF,LABF,NABF,NABF1]=objective_fusion_perform_fn(f,I1,I2) % %%% objective_fusion_perform_fn: Computes the Objective Fusion Performance Parameters proposed by Petrovic %%% and modified Fusion Artifacts (NABF) measure proposed by B. K. Shreyamsha Kumar %%% %%% Inputs: %%% xrcw -> fused image %%% x -> source images, x{1}, x{2} %%% %%% Outputs: %%% QABF -> Total information transferred from source images to fused image measure proposed by Petrovic %%% LABF -> Total loss of information measure proposed by Petrovic %%% NABF1 -> Fusion Artifacts measure proposed by Petrovic %%% NABF -> Modified Fusion Artifacts measure proposed by B. K. Shreyamsha Kumar %%% %%% Author : B. K. SHREYAMSHA KUMAR %%% Created on 28-10-2011. %%% Updated on 08-11-2011. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Petrovic Metrics %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Parameters for Petrovic Metrics Computation. Td=2; wt_min=0.001; P=1; Lg=1.5; Nrg=0.9999; kg=19; sigmag=0.5; Nra=0.9995; ka=22; sigmaa=0.5; xrcw = (f); x1 = (I1); x2 = (I2); %%% Edge Strength & Orientation. [gvA,ghA]=sobel_fn(x1); gA=sqrt(ghA.^2+gvA.^2); [gvB,ghB]=sobel_fn(x2); gB=sqrt(ghB.^2+gvB.^2); [gvF,ghF]=sobel_fn(xrcw); gF=sqrt(ghF.^2+gvF.^2); %%% Relative Edge Strength & Orientation. [p,q]=size(xrcw); for ii=1:p for jj=1:q if(gA(ii,jj)==0 | gF(ii,jj)==0) gAF(ii,jj)=0; elseif(gA(ii,jj)>gF(ii,jj)) gAF(ii,jj)=gF(ii,jj)/gA(ii,jj); else gAF(ii,jj)=gA(ii,jj)/gF(ii,jj); end if(gB(ii,jj)==0 | gF(ii,jj)==0) gBF(ii,jj)=0; elseif(gB(ii,jj)>gF(ii,jj)) gBF(ii,jj)=gF(ii,jj)/gB(ii,jj); else gBF(ii,jj)=gB(ii,jj)/gF(ii,jj); end if(gvA(ii,jj)==0 & ghA(ii,jj)==0) aA(ii,jj)=0; else aA(ii,jj)=atan(gvA(ii,jj)/ghA(ii,jj)); end if(gvB(ii,jj)==0 & ghB(ii,jj)==0) aB(ii,jj)=0; else aB(ii,jj)=atan(gvB(ii,jj)/ghB(ii,jj)); end if(gvF(ii,jj)==0 & ghF(ii,jj)==0) aF(ii,jj)=0; else aF(ii,jj)=atan(gvF(ii,jj)/ghF(ii,jj)); end end end aAF=abs(abs(aA-aF)-pi/2)*2/pi; aBF=abs(abs(aB-aF)-pi/2)*2/pi; %%% Edge Preservation Coefficient. QgAF=Nrg./(1+exp(-kg*(gAF-sigmag))); QaAF=Nra./(1+exp(-ka*(aAF-sigmaa))); QAF=sqrt(QgAF.*QaAF); QgBF=Nrg./(1+exp(-kg*(gBF-sigmag))); QaBF=Nra./(1+exp(-ka*(aBF-sigmaa))); QBF=sqrt(QgBF.*QaBF); %%% Total Fusion Performance (QABF). wtA=wt_min*ones(p,q); wtB=wt_min*ones(p,q); cA=ones(p,q); cB=ones(p,q); for ii=1:p for jj=1:q if(gA(ii,jj)>=Td) wtA(ii,jj)=cA(ii,jj)*gA(ii,jj)^Lg; end if(gB(ii,jj)>=Td) wtB(ii,jj)=cB(ii,jj)*gB(ii,jj)^Lg; end end end wt_sum=sum(sum(wtA+wtB)); QAF_wtsum=sum(sum(QAF.*wtA))/wt_sum; %% Information Contributions of A. QBF_wtsum=sum(sum(QBF.*wtB))/wt_sum; %% Information Contributions of B. QABF=QAF_wtsum+QBF_wtsum; %% QABF=sum(sum(QAF.*wtA+QBF.*wtB))/wt_sum -> Total Fusion Performance. %%% Fusion Gain (QdeltaABF). Qdelta=abs(QAF-QBF); QCinfo=(QAF+QBF-Qdelta)/2; QdeltaAF=QAF-QCinfo; QdeltaBF=QBF-QCinfo; QdeltaAF_wtsum=sum(sum(QdeltaAF.*wtA))/wt_sum; QdeltaBF_wtsum=sum(sum(QdeltaBF.*wtB))/wt_sum; QdeltaABF=QdeltaAF_wtsum+QdeltaBF_wtsum; %% Total Fusion Gain. QCinfo_wtsum=sum(sum(QCinfo.*(wtA+wtB)))/wt_sum; QABF11=QdeltaABF+QCinfo_wtsum; %% Total Fusion Performance. %%% Fusion Loss (LABF). rr=zeros(p,q); for ii=1:p for jj=1:q if(gF(ii,jj)<=gA(ii,jj) | gF(ii,jj)<=gB(ii,jj)) rr(ii,jj)=1; else rr(ii,jj)=0; end end end LABF=sum(sum(rr.*((1-QAF).*wtA+(1-QBF).*wtB)))/wt_sum; %%% Fusion Artifacts (NABF) by Petrovic. for ii=1:p for jj=1:q if(gF(ii,jj)>gA(ii,jj) & gF(ii,jj)>gB(ii,jj)) na1(ii,jj)=2-QAF(ii,jj)-QBF(ii,jj); else na1(ii,jj)=0; end end end NABF1=sum(sum(na1.*(wtA+wtB)))/wt_sum; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Fusion Artifacts (NABF) changed by B. K. Shreyamsha Kumar . %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for ii=1:p for jj=1:q if(gF(ii,jj)>gA(ii,jj) & gF(ii,jj)>gB(ii,jj)) na(ii,jj)=1; else na(ii,jj)=0; end end end NABF=sum(sum(na.*((1-QAF).*wtA+(1-QBF).*wtB)))/wt_sum; QABF+LABF+NABF1; QABF+LABF+NABF;
lemma summable_imp_bounded: fixes f :: "nat \<Rightarrow> 'a::real_normed_vector" shows "summable f \<Longrightarrow> bounded (range f)"
# _*_ coding: utf-8 _*_ """ Regridding from one grid to another. """ import numpy as np from numpy.lib.stride_tricks import as_strided from numba import jit import scipy.interpolate import scipy.ndimage def hinterp(data, x, y, xout, yout, grid=True): """ Regridding multiple dimensions data. Interpolation occurs in the 2 rightest most indices of grid data. :param grid: input grid, multiple array. :param x: input grid x coordinates, 1D vector. :param y: input grid y coordinates, 1D vector. :param xout: output points x coordinates, 1D vector. :param yout: output points y coordinates, 1D vector. :param grid: output points is a grid. :return: interpolated grid. :Example: >>> data = np.arange(40).reshape(2,5,4) >>> x = np.linspace(0,9,4) >>> y = np.linspace(0,8,5) >>> xout = np.linspace(0,9,7) >>> yout = np.linspace(0,8,9) >>> odata = hinterp(data, x, y, xout, yout) """ # check grid if grid: xxout, yyout = np.meshgrid(xout, yout) else: xxout = xout yyout = yout # interpolated location xx = np.interp(xxout, x, np.arange(len(x), dtype=np.float)) yy = np.interp(yyout, y, np.arange(len(y), dtype=np.float)) # perform bilinear interpolation xx0 = np.floor(xx).astype(int) xx1 = xx0 + 1 yy0 = np.floor(yy).astype(int) yy1 = yy0 + 1 ixx0 = np.clip(xx0, 0, data.shape[-1] - 1) ixx1 = np.clip(xx1, 0, data.shape[-1] - 1) iyy0 = np.clip(yy0, 0, data.shape[-2] - 1) iyy1 = np.clip(yy1, 0, data.shape[-2] - 1) Ia = data[..., iyy0, ixx0] Ib = data[..., iyy1, ixx0] Ic = data[..., iyy0, ixx1] Id = data[..., iyy1, ixx1] wa = (xx1 - xx) * (yy1 - yy) wb = (xx1 - xx) * (yy - yy0) wc = (xx - xx0) * (yy1 - yy) wd = (xx - xx0) * (yy - yy0) return wa * Ia + wb * Ib + wc * Ic + wd * Id def rebin(a, factor, func=None): """Aggregate data from the input array ``a`` into rectangular tiles. The output array results from tiling ``a`` and applying `func` to each tile. ``factor`` specifies the size of the tiles. More precisely, the returned array ``out`` is such that:: out[i0, i1, ...] = func(a[f0*i0:f0*(i0+1), f1*i1:f1*(i1+1), ...]) If ``factor`` is an integer-like scalar, then ``f0 = f1 = ... = factor`` in the above formula. If ``factor`` is a sequence of integer-like scalars, then ``f0 = factor[0]``, ``f1 = factor[1]``, ... and the length of ``factor`` must equal the number of dimensions of ``a``. The reduction function ``func`` must accept an ``axis`` argument. Examples of such function are - ``numpy.mean`` (default), - ``numpy.sum``, - ``numpy.product``, - ... The following example shows how a (4, 6) array is reduced to a (2, 2) array >>> import numpy as np >>> a = np.arange(24).reshape(4, 6) >>> rebin(a, factor=(2, 3), func=np.sum) array([[ 24, 42], [ 96, 114]]) If the elements of `factor` are not integer multiples of the dimensions of `a`, the remaining cells are discarded. >>> rebin(a, factor=(2, 2), func=np.sum) array([[16, 24, 32], [72, 80, 88]]) """ a = np.asarray(a) dim = a.ndim if np.isscalar(factor): factor = dim*(factor,) elif len(factor) != dim: raise ValueError('length of factor must be {} (was {})' .format(dim, len(factor))) if func is None: func = np.mean for f in factor: if f != int(f): raise ValueError('factor must be an int or a tuple of ints ' '(got {})'.format(f)) new_shape = [n//f for n, f in zip(a.shape, factor)]+list(factor) new_strides = [s*f for s, f in zip(a.strides, factor)]+list(a.strides) aa = as_strided(a, shape=new_shape, strides=new_strides) return func(aa, axis=tuple(range(-dim, 0))) def congrid(a, newdims, method='linear', centre=False, minusone=False): """ Arbitrary resampling of source array to new dimension sizes. Currently only supports maintaining the same number of dimensions. To use 1-D arrays, first promote them to shape (x,1). Uses the same parameters and creates the same co-ordinate lookup points as IDL''s congrid routine, which apparently originally came from a VAX/VMS routine of the same name. http://scipy-cookbook.readthedocs.io/items/Rebinning.html :param a: :param newdims: :param method: neighbour - closest value from original data nearest and linear - uses n x 1-D interpolations using scipy.interpolate.interp1d (see Numerical Recipes for validity of use of n 1-D interpolations) spline - uses ndimage.map_coordinates :param centre: True - interpolation points are at the centres of the bins False - points are at the front edge of the bin :param minusone: For example- inarray.shape = (i,j) & new dimensions = (x,y) False - inarray is resampled by factors of (i/x) * (j/y) True - inarray is resampled by(i-1)/(x-1) * (j-1)/(y-1) This prevents extrapolation one element beyond bounds of input array. :return: """ if not (a.dtype in [np.float64, np.float32]): a = np.cast[float](a) m1 = np.cast[int](minusone) ofs = np.cast[int](centre) * 0.5 old = np.array(a.shape) ndims = len(a.shape) if len(newdims) != ndims: print("[congrid] dimensions error. " "This routine currently only support " "rebinning to the same number of dimensions.") return None newdims = np.asarray(newdims, dtype=float) dimlist = [] if method == 'neighbour': for i in range(ndims): base = np.indices(newdims)[i] dimlist.append( (old[i] - m1) / (newdims[i] - m1) * (base + ofs) - ofs) cd = np.array(dimlist).round().astype(int) newa = a[list(cd)] return newa elif method in ['nearest', 'linear']: # calculate new dims for i in range(ndims): base = np.arange(newdims[i]) dimlist.append( (old[i] - m1) / (newdims[i] - m1) * (base + ofs) - ofs) # specify old dims olddims = [np.arange(i, dtype=np.float) for i in list(a.shape)] # first interpolation - for ndims = any mint = scipy.interpolate.interp1d(olddims[-1], a, kind=method) newa = mint(dimlist[-1]) trorder = [ndims - 1] + np.arange(ndims - 1) for i in range(ndims - 2, -1, -1): newa = newa.transpose(trorder) mint = scipy.interpolate.interp1d(olddims[i], newa, kind=method) newa = mint(dimlist[i]) if ndims > 1: # need one more transpose to return to original dimensions newa = newa.transpose(trorder) return newa elif method in ['spline']: nslices = [slice(0, j) for j in list(newdims)] newcoords = np.mgrid[nslices] newcoords_dims = np.arange(np.rank(newcoords)) # make first index last newcoords_dims.append(newcoords_dims.pop(0)) newcoords_tr = newcoords.transpose(newcoords_dims) # makes a view that affects newcoords newcoords_tr += ofs deltas = (np.asarray(old) - m1) / (newdims - m1) newcoords_tr *= deltas newcoords_tr -= ofs newa = scipy.ndimage.map_coordinates(a, newcoords) return newa else: print("Congrid error: Unrecognized interpolation type.\n", "Currently only \'neighbour\', \'nearest\',\'linear\',", "and \'spline\' are supported.") return None @jit def box_average(field, lon, lat, olon, olat, width=None, rm_nan=False): """ Remap high resolution field to coarse with box_average. Accelerated by numba, but slower than rebin. :param field: 2D array (nlat, nlon) for input high resolution. :param lon: 1D array, field longitude coordinates. :param lat: 1D array, field latitude coordinates. :param olon: 1D array, out coarse field longitude coordinates. :param olat: 1D array, out coarse field latitude coordinates. :param width: box width. :param rm_nan: remove nan values when calculate average. :return: 2D array (nlat1, nlon1) for coarse field. """ # check box width if width is None: width = (olon[1] - olon[0]) / 2.0 # define output grid out_field = np.full((olat.size, olon.size), np.nan) # loop every grid point for j in np.arange(olat.size): for i in np.arange(olon.size): # searchsorted is fast. lon_min = np.searchsorted(lon, olon[i] - width) lon_max = np.searchsorted(lon, olon[i] + width) + 1 lat_min = np.searchsorted(lat, olat[j] - width) lat_max = np.searchsorted(lat, olat[j] + width) + 1 temp = field[lat_min:lat_max, lon_min:lon_max] if rm_nan: if np.all(np.isnan(temp)): out_field[j, i] = np.nan else: temp = temp[~np.isnan(temp)] out_field[j, i] = np.mean(temp) else: out_field[j, i] = np.mean(temp) # return return out_field @jit def box_max_avg(field, lon, lat, olon, olat, width=None, number=1, rm_nan=False): """ Remap high resolution field to coarse with box_max_avg. Same sa box_avg, but average the "number" hightest values. Accelerated by numba, but slower than rebin. :param field: 2D array (nlat, nlon) for input high resolution. :param lon: 1D array, field longitude coordinates. :param lat: 1D array, field latitude coordinates. :param olon: 1D array, out coarse field longitude coordinates. :param olat: 1D array, out coarse field latitude coordinates. :param width: box width. :param number: select the number of largest value. :param rm_nan: remove nan values when calculate average. :return: 2D array (nlat1, nlon1) for coarse field. """ # check box width if width is None: width = (olon[1] - olon[0]) / 2.0 # define output grid out_field = np.full((olat.size, olon.size), np.nan) # loop every grid point for j in np.arange(olat.size): for i in np.arange(olon.size): # searchsorted is fast. lon_min = np.searchsorted(lon, olon[i] - width) lon_max = np.searchsorted(lon, olon[i] + width) lat_min = np.searchsorted(lat, olat[j] - width) lat_max = np.searchsorted(lat, olat[j] + width) temp = field[lat_min:lat_max, lon_min:lon_max] if rm_nan: if np.all(np.isnan(temp)): out_field[j, i] = np.nan else: temp = temp[~np.isnan(temp)] if temp.size < number: out_field[j, i] = np.mean(temp) else: out_field[j, i] = np.mean(np.sort(temp)[-number:]) else: if temp.size < number: out_field[j, i] = np.mean(temp) else: out_field[j, i] = np.mean(np.sort(temp)[-number:]) # return return out_field
\subsection{PS2 driver} PS2 driver is simple peripherals that allow connect keyboard or mouse. Driver in this revision is able only to receive. \subsubsection{Function} This peripheral doesn't need any configuration. Just enable interrupt in interrupt driver and is done. When key on connected keyboard are pressed, key code is sent to the PS2 driver. When sending is completed, interrupt is called. \subsubsection{Registers} There is only one register, called PSBR, and it have offset $+0$. After key code is received, it is stored in this register. Register is 8 bits wide. \begin{table}[h] \centering \begin{tabular}{|l|l|l|} \hline \textbf{Offset} & \textbf{Name} & \textbf{Purpose} \\ \hline $+0$ & PSBR & Last received byte from PS2 bus. \\ \hline \end{tabular} \caption{PS2 driver register map} \label{tab:ps2_reg_map} \end{table} \subsubsection{Hacking} There is nothing to change on this peripheral. Interface is also standard. There is only three device specific signals, ps2clk, ps2dat and intrq. Signal intrq should be connected to the interrupt driver and signal ps2clk and ps2dat should be connected to the top level pins. \begin{lstlisting}[language=VHDL, frame=single] entity ps2 is generic( BASE_ADDRESS: unsigned(23 downto 0) := x"000000" ); port( clk: in std_logic; res: in std_logic; address: in unsigned(23 downto 0); data_miso: out unsigned(31 downto 0); RD: in std_logic; ack: out std_logic; ps2clk: in std_logic; ps2dat: in std_logic; intrq: out std_logic ); end entity ps2; \end{lstlisting}
#' gmhelper #' #' Run the gmhelper webapp. #' #' The app is written in shiny and uses a bunch of internal rollers #' and random tables. #' #' @importFrom shiny runApp #' @export gmhelper <- function() { shiny::runApp(file.path(system.file("shinyapp", package="gmhelper"))) }
If $f$ and $g$ converge to $l$ and $m$, respectively, then $f - g$ converges to $l - m$.
-- Andreas, 2018-10-17, re #2757 -- -- Don't project from erased matches. open import Agda.Builtin.List open import Common.Prelude data IsCons {A : Set} : List A → Set where isCons : ∀{@0 x : A} {@0 xs : List A} → IsCons (x ∷ xs) headOfErased : ∀{A} (@0 xs : List A) → IsCons xs → A headOfErased (x ∷ xs) isCons = x -- Should fail with error: -- -- Variable x is declared erased, so it cannot be used here main = printNat (headOfErased (1 ∷ 2 ∷ []) isCons) -- Otherwise, main segfaults.
State Before: ι : Type ?u.36681 α : Type u_1 β : Type ?u.36687 π : ι → Type ?u.36692 inst✝ : GeneralizedHeytingAlgebra α a b c d : α ⊢ a ⇔ a = ⊤ State After: no goals Tactic: rw [bihimp, inf_idem, himp_self]
theory Fofu_Abs_Base imports Complex_Main "HOL-Library.Rewrite" Automatic_Refinement.Misc Refine_Imperative_HOL.Sepref_Misc "Program-Conflict-Analysis.LTS" begin (* TODO: Move *) lemma swap_in_iff_inv: "prod.swap p \<in> S \<longleftrightarrow> p \<in> S\<inverse>" apply (cases p) by auto (* TODO: Move *) lemma length_filter_disj_or_conv: assumes "\<And>x. x\<in>set xs \<longrightarrow> \<not>(P x \<and> Q x)" shows "length [x \<leftarrow> xs. P x \<or> Q x] = length (filter P xs) + length (filter Q xs)" using assms by (induction xs) auto (* TODO: Move. Extract an element from a summation, combined with congruence. *) lemma sum_arb: assumes A_fin: "finite A" and x_mem: "x \<in> A" and x_dif: "\<forall>y\<in>A. y \<noteq> x \<longrightarrow> g y = h y" shows "(\<Sum>a\<in>A. g a) = (\<Sum>a\<in>A - {x}. h a) + g x" proof - have "A = (A - {x}) \<union> {x}" using x_mem by auto moreover note sum.union_disjoint[of "A - {x}" "{x}" g] moreover note sum.cong[of "A - {x}" "A - {x}" g h] ultimately show ?thesis using A_fin x_dif by auto qed lemma trcl_cons_conv: "(u,a#xs,v)\<in>trcl R \<longleftrightarrow> (\<exists>uh. (u,a,uh)\<in>R \<and> (uh,xs,v)\<in>trcl R)" by (auto dest!: trcl_uncons) lemma trcl_conc_conv: "(u,xs@ys,v)\<in>trcl R \<longleftrightarrow> (\<exists>uh. (u,xs,uh)\<in>trcl R \<and> (uh,ys,v)\<in>trcl R)" by (auto dest!: trcl_unconcat intro: trcl_concat) lemmas trcl_conv = trcl_cons_conv trcl_conc_conv \<comment> \<open>Adding these to simpset will split all cons and append operations in paths\<close> end
\chapter[Selected Applications Of Detection Proposals]{Selected Applications Of \newline Detection Proposals} \label{chapter:applications} In the final chapter of this thesis, we present two applications of our detection proposals method. The first is a end-to-end object detection pipeline that uses detection proposals at its core. The second is a simple tracking system that combines detection proposals and matching. The purpose of this chapter is not to improve some specific state of the art, but to show that detection proposals can be used for different problems related to underwater robot perception, in the context of marine debris detection. We expect that the ideas presented in this chapter can be further developed to become state of the art in their respective sub-fields, with specific application to tasks related to collecting marine debris from the ocean floor. \section{End-to-End Object Detection} \subsection{Introduction} We have built a object detection pipeline based on detection proposals. While object detection is a well researched subject, many underwater object detection systems suffer from generalization issues that we have mentioned in the past. There is a rampart use of feature engineering that is problem and object specific, which harms the ability to use such features for different objects and environments. We have previously shown how classic methods for sonar images do not perform adequately for marine debris, and extensions to use deep neural networks are required. A natural extension of our detection proposal system is to include a classification stage so full object detection can be performed. An additional desirable characteristic of a CNN-based object detector is end-to-end training. This consists of training a single network that perform both tasks (detection and classification) in a way that all intermediate steps are also internally learned by the network. Only input images and labels must be provided (hence end-to-end). In this section we showcase a CNN architecture that can perform both object detection (through detection proposals) and object recognition (with a integrated classifier) in a single unified network. We do this using multi-task learning, where a CNN architecture is designed to output two sets of values: An objectness score for detection proposals (same as Chapter \ref{chapter:proposals}), and a softmax probability distribution over class labels (like our image classifiers in Chapter \ref{chapter:sonar-classification}). We show that this architecture can be easily trained with only labeled image crops that contain both objectness and class labels, which effectively makes an end-to-end system with acceptable performance. \subsection{Proposed Method} We design a network that takes a single input image patch and produces two outputs, namely: \begin{itemize} \item \textbf{Objectness}. This corresponds as an objectness score in $[0, 1]$ used to decide if an object is present in the image. Its interpretation is the same as with our detection proposals algorithm (in Chapter \ref{chapter:proposals}). The basic idea is to threshold the objectness score or use ranking to produce detections. This is implemented as a sigmoid activation function. \item \textbf{Class Decision}. This corresponds to one of $C + 1$ pre-defined classes, which indicate the object class decided by the network. We include an additional class that represents background, meaning no object present in that window. This is implemented as a softmax activation which produces a probability distribution over classes. The output class can then be selected by the one with highest probability. \end{itemize} Each output represents a different "task" in a multi-task learning framework \cite{ruder2017overview}. Objectness represents the task of object localization, while class decisions corresponds to the classification task. The basic network design that we propose is shown in Figure \ref{apps-detection:basicArchitecture}. A certain number of convolutional feature maps form the "trunk" of the network, which are feed directly from the input image. A 1D feature vector is produced by the network trunk, typically by a fully connected layer receiving input from the convolutional feature maps, but we give freedom to the network designer to set the right architecture for the problem. It should be noted that the shared feature vector does not need to be one-dimensional. There is the possibility to keep two-dimensional convolutional feature maps in order to exploit spatial structure in the features. In order to produce a one-dimensional feature vector, flattening is usually applied, and this could lose some spatial information. We mention this option but do not explore it further. Two output sub-networks are fed by the shared feature vector. One sub-network produces an objectness score, while the other sub-network produces a class decision. Once this network is built and trained, it can be used in a sliding window fashion over the input image to produce detections that also include class information, forming a complete object detection system. The use of a shared feature vector is based on the idea of information sharing. As objectness and object classification share some similarities, such as the concept of an object and variability between object classes, it makes sense to learn a feature vector that combine/fuses both kinds of information into a single source. This vector should encode both objectness and class information, allowing for a classifier and objectness regressor to extract useful information for each of the tasks. Another view of the shared feature vector is that of minimizing the amount of information required for both tasks. As both tasks require common information, a smaller feature vector can be learned instead of learning two feature vectors that might be forced to duplicate information. This should require less data and a simpler network architecture. There is also evidence \cite{caruana1997multitaskJournalML} that multi-task learning can improve the performance of each individual task . Rich Caruana's PhD thesis \cite{caruana1997multitask} was one of the first to study this topic, and his work found that performance improvements in multi-task learning come from extra information in the training signals of the additional tasks. There are different mechanisms that produce this effect: statistical data amplification, attribute selection, eavesdropping, and representation bias. Caruana also mentions that backpropagation automatically discovers how the tasks are related in a partially unsupervised way. \newpage State of the art object detection methods like Faster R-CNN \cite{ren2015faster} and YOLO \cite[1em]{redmon2016you} also use multi-task learning, and we recognize that we use similar ideas to build our object detector. Our method could be considered a simplification of Faster R-CNN without bounding box regression and only a single anchor box, which allows for one scale only. In comparison, our method is trained end-to end, while Faster R-CNN and YOLO can only be trained successfully with a pre-trained network on the ImageNet dataset. Figure \ref{apps-detection:classicNetRealization} represents our particular instantiation of the basic architecture fro Figure \ref{apps-detection:basicArchitecture}. This architecture is based on ClassicNet but with two "heads" for classification and object localization. We obtained this model by performing grid search on a validation set with a variation of number of layers, convolutional filters, and shared feature vector size. \begin{figure}[!htb] \centering \begin{tikzpicture}[style={align=center, minimum height=0.5cm, minimum width = 2.5cm}] \node[] (dummy) {}; \node[draw, left=0.0em of dummy] (objClassifier) {{\scriptsize Object Classifier}}; \node[above=1em of objClassifier] (objClass) {{\scriptsize Object Class}}; \node[draw, right=0.0em of dummy] (objDetector) {{\scriptsize Objectness Regressor}}; \node[above=1em of objDetector] (obj) {{\scriptsize Objectness}}; \node[draw, below=1em of dummy] (fc) {{\scriptsize Feature Vector}}; \node[draw, below=1em of fc](conv) {\scriptsize{Convolutional Features}}; \node[below=1em of conv](inputImage) {{\scriptsize Input Image}}; \draw[-latex] (inputImage) -- (conv); \draw[-latex] (conv) -- (fc); \draw[-latex] (fc) -- (objDetector); \draw[-latex] (fc) -- (objClassifier); \draw[-latex] (objClassifier) -- (objClass); \draw[-latex] (objDetector) -- (obj); \end{tikzpicture} \caption[Basic Object Detection Architecture]{Basic Object Detection Architecture. A single image is input to a neural network with two outputs. A shared set of convolutional features are computed, producing a feature vector that is used by both the object classifier and object detector to produce their decisions.} \label{apps-detection:basicArchitecture} \end{figure} \begin{figure}[!htb] \centering \begin{tikzpicture}[style={align=center, minimum height=0.5cm, minimum width = 2.0cm}] \node[] (dummy) {}; \node[draw, left=0.1em of dummy] (probsFc1) {{\scriptsize FC(96)}}; \node[draw, above=1em of probsFc1] (probsFcOut) {{\scriptsize FC(\# of classes)}}; \node[above=1em of probsFcOut] (probs) {{\scriptsize Class Probabilities}}; \node[draw, right=0.1em of dummy] (objFc1) {{\scriptsize FC(96)}}; \node[draw, above=1em of objFc1] (objFcOut) {{\scriptsize FC(1)}}; \node[above=1em of objFcOut] (obj) {{\scriptsize Objectness}}; \node[draw, below=1em of dummy] (fc1) {{\scriptsize FC(128)}}; \node[draw, below=1em of fc1] (mp2) {{\scriptsize MaxPooling(2, 2)}}; \node[draw, below=1em of mp2] (conv2) {{\scriptsize Conv($32$, $5 \times 5$)}};; \node[draw, below=1em of conv2] (mp1) {{\scriptsize MaxPooling(2, 2)}}; \node[draw, below=1em of mp1](conv1) {{\scriptsize Conv($32$, $5 \times 5$)}}; \node[below=1em of conv1](inputImage) {{\scriptsize $96 \times 96$ Input Image}}; \draw[-latex] (inputImage) -- (conv1); \draw[-latex] (conv1) -- (mp1); \draw[-latex] (mp1) -- (conv2); \draw[-latex] (conv2) -- (mp2); \draw[-latex] (mp2) -- (fc1); \draw[-latex] (fc1) -- (objFc1); \draw[-latex] (objFc1) -- (objFcOut); \draw[-latex] (fc1) -- (probsFc1); \draw[-latex] (probsFc1) -- (probsFcOut); \draw[-latex] (probsFcOut) -- (probs); \draw[-latex] (objFcOut) -- (obj); \end{tikzpicture} \caption[Realization of the proposed architecture as a Convolutional Neural Network]{Realization of the proposed architecture as a Convolutional Neural Network. This CNN has 1.8 Million trainable weights.} \label{apps-detection:classicNetRealization} \end{figure} The network is trained end-to-end with both tasks of detection and recognition at the same time. This process requires the minimization of a multi-task loss function. In our case we use a linear combination of two loss terms. For classification we use the categorical cross-entropy loss, while for objectness we use the mean squared error: \begin{equation} L(y, \hat{y}) = n^{-1} \sum (y_o - \hat{y}_o)^2 - \gamma \sum_i \sum_c y^c_i \log \hat{y}^c_i \label{apps-detection:multiTaskLoss} \end{equation} Where the $o$ subscript is used for objectness labels, and the $c$ superscript for class information. The factor $\gamma$ controls the importance of each sub-loss term into the overall loss value. Tuning an appropriate value is key to obtain good performance. We evaluate the effect of this parameter in our experiments.\\ Batch normalization \cite{ioffe2015batch} is used after every trainable layer to prevent overfitting and accelerate training. The network is trained with stochastic gradient descent with a batch size of $b = 128$ images and the ADAM optimizer \cite[1em]{kingma2014adam} with a starting learning rate of $\alpha = 0.01$. We train until the validation loss stops improving, normally after 20 epochs. \subsection{Experimental Evaluation} From the perspective of the Marine Debris task, an object detector has two main objectives: to detect debris objects with high recall, and to classify them with high accuracy. We evaluate recall instead of both precision and recall as the object detector has to generalize well outside of its training set, where it might detect novel objects but classify them incorrectly. To evaluate false positives, we measure the number of output proposals, as it correlates with the possibility of a false positive. We evaluate our object detection method in terms of three metrics: proposal recall, classification accuracy, and number of output proposals. We use proposal recall as defined in Chapter \ref{chapter:proposals}, while we define classification accuracy for this problem as the ratio between correctly classified bounding boxes over the number of ground truth bounding boxes. This kind of evaluation metrics allow for separate assessment of object localization (detection) and classification. For simplicity we only use objectness thresholding as a way to extract detections from objectness scores, as it was the best performing method when we evaluated it in Chapter \ref{chapter:proposals}. For many point-wise comparisons we use $T_o = 0.5$, as it makes sense since it is the middle value of the valid scale for $T_o$, and in general it produces a good trade-off between number of detection proposals and recall and accuracy. We have not yet defined a concrete value of the multi-task loss weight $\gamma$. Most papers that use multi-task learning tune this value on a validation set, but we have found out that setting the right value is critical for good performance and balance between the tasks. We take an empiric approach and evaluate a predefined set of values, namely $\gamma \in [0.5, 1, 2, 3, 4]$ and later determine which produces the best result using both recall and accuracy. This is not an exhaustive evaluation, but we found that it produces good results. Recent research by Kendall et al. \cite[-6em]{kendall2017multi} proposes a method to automatically tune multi-task weights using task uncertainty that could be used in the future. This paper also notes that multi-task weights have a great effect on overall system performance. Figure \ref{apps-detection:objectnessThreshVsAccuracyRecallAndNumberOfProposals} shows our principal results as the objectness threshold $T_o$ is varied and we also show the effect of different multi-task loss weight $\gamma$. Our detection proposals recall is good, close to $95$ \% at $T_o = 0.5$ for many values of $\gamma$, showing little variation between different choices of that parameter. Larger variations in recall are observed for bigger ($> 0.6$) values of $T_o$. Classification accuracy produced by our system shows a considerable variation across different values of the multi-task loss weight $\gamma$. The best performing value is $\gamma = 3$, but it is not clear why this value is optimal or how other values can be considered (other than trial and error). As mentioned before, setting multi-task loss weights is not trivial and has a large effect on the result. It is also counter-intuitive that a larger value of $gamma$ leads to lower classification performance. At $T_o = 0.5$, the best performing model produces $70$ \% accuracy. Looking at the number of proposals, again there is a considerable variation between different values of $gamma$, but the number of proposal reduces considerably with an increasing objectness threshold $T_o$. For $T_o = 0.5$ the best performing value $gamma = 3$ produces $112 \pm 62$ proposals per image. This is higher than the number of proposals that our non-classification methods produce (as shown in Chapter \ref{chapter:proposals}). From a multi-task learning point of view, learning the classification task seems to be considerably harder than the objectness regression task. This is probably due to the different task complexity (modeling class-agnostic objects seems to be easier than class-specific objects), and also we have to consider the limitations from our small training set. Other object detectors like Faster R-CNN are usually trained in much bigger datasets, also containing more object pose variability. \begin{figure*}[t] \centering \forcerectofloat \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.49\textwidth, xlabel={Objectness Threshold ($T_o$)}, ylabel={Detection Recall (\%)}, xmin=0, xmax=1.0, ymin=0, ymax=100.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south west] \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda0.5.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda1.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda2.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda4.csv}; \end{axis} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.49\textwidth, xlabel={Objectness Threshold ($T_o$)}, ylabel={Classification Accuracy (\%)}, xmin=0, xmax=1.0, ymin=0, ymax=100.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south west] \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda0.5.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda1.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda2.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda4.csv}; \end{axis} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.49\textwidth, xlabel={Objectness Threshold ($T_o$)}, ylabel={Number of Proposals}, xmin=0, xmax=1.0, ymin=0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = outer north east] \addplot+[mark=none] table[x = threshold, y = numberOfProposals, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda0.5.csv}; \addlegendentry{$\gamma = \frac{1}{2}$} \addplot+[mark=none] table[x = threshold, y = numberOfProposals, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda1.csv}; \addlegendentry{$\gamma = 1$} \addplot+[mark=none] table[x = threshold, y = numberOfProposals, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda2.csv}; \addlegendentry{$\gamma = 2$} \addplot+[mark=none] table[x = threshold, y = numberOfProposals, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \addlegendentry{$\gamma = 3$} \addplot+[mark=none] table[x = threshold, y = numberOfProposals, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda4.csv}; \addlegendentry{$\gamma = 4$} \end{axis} \end{tikzpicture} \caption[Detection Recall, Classification Accuracy and Number of Proposals as a function of Objectness Threshold $T_o$]{Detection Recall, Classification Accuracy and Number of Proposals as a function of Objectness Threshold $T_o$. Different combinations of the multi-task loss weight $\gamma$ are shown.} \label{apps-detection:objectnessThreshVsAccuracyRecallAndNumberOfProposals} \end{figure*} Figure \ref{apps-detection:accuracyRecallVsNumberOfProposals} shows the relation between recall/accuracy and the number of detection proposals. For detection proposal recall, our results show that only 100 to 150 proposals per image are required to achieve $95$ \% recall, and using more proposals only marginally increases performance. For classification accuracy, the pattern is different from proposal recall. As mentioned previously, there is a large variation in classification performance as the multi-task loss weight $\gamma$ is varied, and clearly $\gamma = 3$ performs best. But accuracy increases slowly as the number of proposals is increased, which shows that many proposals are being misclassified, indicating a problem with the classification branch of the network. We expected that classification performance will increase in a similar way as to proposal recall, if the network is performing well at both tasks, but it is likely that our implicit assumption that both tasks are approximately equally hard might not hold. \begin{figure*}[!htb] \forceversofloat \centering \begin{tikzpicture} \begin{customlegend}[legend columns = 5,legend style = {column sep=1ex}, legend cell align = left, legend entries={$\gamma = \frac{1}{2}$, $\gamma = 1$, $\gamma = 2$, $\gamma = 3$, $\gamma = 4$}] \addlegendimage{mark=none,red} \addlegendimage{mark=none,blue} \addlegendimage{mark=none,green} \addlegendimage{mark=none,violet} \addlegendimage{mark=none,orange} \end{customlegend} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.48\textwidth, xlabel={Number of Proposals}, ylabel={Detection Recall (\%)}, xmin=0, xmax=300, ymin=40, ymax=100.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south west, ytick = {40, 50, 60, 70, 80, 90, 100}] \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda0.5.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda1.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda2.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = recall, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda4.csv}; \end{axis} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.48\textwidth, xlabel={Number of Proposals}, ylabel={Classification Accuracy (\%)}, xmin=0, xmax=300, ymin=20, ymax=100.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south west, ytick = {20, 30, 40, 50, 60, 70, 80, 90, 100}] \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda0.5.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda1.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda2.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{#1*100}\pgfmathresult}] table[x = numberOfProposals, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda4.csv}; \end{axis} \end{tikzpicture} \caption[Detection Recall and Classification Accuracy as a function of the Number of Proposals]{Detection Recall and Classification Accuracy as a function of the Number of Proposals. Different combinations of the multi-task loss weight $\gamma$ are shown.} \label{apps-detection:accuracyRecallVsNumberOfProposals} \end{figure*} While our object detector has high proposal recall, the results we obtained in terms of classification are not satisfactory. \newpage Inspired by Sharif et al. \cite[5em]{sharif2014cnn}, we evaluated replacing the fully connected layers with a SVM classifier. This has the potential of performing better, as the number of neurons in the fully connected layers used for classification could not be optimal. Nonetheless these layers are required during training, in order to force the shared feature vector to learn a representation that is useful for both classification and objectness regression. We freeze model weights and compute the shared feature vectors for all images in the training set. Then we train a linear SVM with $C = 1$ (obtained from grid search in a validation set) and one-versus-one scheme for multi-class classification. We then replace the classification branch with this trained classifier. Results are shown in Figure \ref{apps-detection:finetuningResults}. Our results show that using a SVM classifier outperforms the fully connected one by a large margin. Performance is also more stable with respect to variation in the objectness threshold $T_o$. At $T_o = 0.5$, the SVM classifier produces $85$ \% recall, which is a $15$ \% absolute improvement over using a fully connected layer with a softmax activation. These results are more usable for real world applications, but still there is a large room for improvement. \begin{figure}[t] \forcerectofloat \centering \begin{tikzpicture} \begin{customlegend}[legend columns = 5,legend style = {column sep=1ex}, legend cell align = left, legend entries={SVM Classifier, FC Classifier}] \addlegendimage{mark=none,red} \addlegendimage{mark=none,blue} \end{customlegend} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.85\textwidth, xlabel={Objectness Threshold ($T_o$)}, ylabel={Classification Accuracy (\%)}, xmin=0, xmax=1.0, ymin=30, ymax=100.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, ytick = {30, 40, 50, 60, 70, 80, 90, 100}] \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/finetunedThresholdVsAccuracy.csv}; \addplot+[mark=none, y filter/.code={\pgfmathparse{\pgfmathresult*100.}\pgfmathresult}] table[x = threshold, y = accuracy, col sep = space] {chapters/data/applications/detection/thresholdVsRecallAndAccuracyAtIoU0.5Lambda3.csv}; \end{axis} \end{tikzpicture} \caption[Comparison of SVM and FC classifiers using features learned by model $\gamma = 3$]{Comparison of SVM and FC classifiers using features learned by model $\gamma = 3$. The SVM classifier produces a considerable improvement over the FC one. We did not evaluate past $T_o > 0.65$ as the number of available training samples was too low.} \label{apps-detection:finetuningResults} \end{figure} We believe that our results indicate that a big problem is mismatch between the training set and the test set. During inference, the model has to classify an image that is generated by a sliding window, and depending on the position of the object in the image, classification might be difficult or fail completely. We believe this problem can be alleviated by introducing a more fine sliding window stride $s$ and a larger training set, containing more object variability and object translations inside the image window. An alternative to the use of a multi-class SVM classifier is to fine-tune the classification layers with a ping-pong approach. First detection proposals are generated on the training set, and matched to correct bounding boxes. Then these matching detection proposals are used to fine-tune the classifier by including them into the classification training set and continue training the classification layers from previous weights (not randomly initialized) for a predefined number of epochs. Then this process is repeated, and feedback between object detection and classification should lead to convergence after a certain number of iterations. This process is costly as it requires a full evaluation cycle on the training set and multiple forward and backward passes to train specific parts of the network. In this thesis we only showcased the simple approach of a SVM classifier. We have also noticed a problem with the multiple detections that are generated for a single ground truth object. These can be reduced by applying non-maximum suppression, but also there is no guarantee that the highest scoring bounding box is classified as the correct object class. This problem is related to the previously mentioned one, as we found out that the top scoring window was consistently misclassified. As we do not reach $100$ \% detection recall, then it is not possible to achieve $100$ \% classification accuracy, and we have probably reached the best performance that this simple model can perform. We note that our model uses a single scale, and more complex output configurations could be used. For example, inspired on Faster R-CNN's anchor boxes \cite{ren2015faster}, multiple fixed-size bounding boxes could be output and a classifier may decide which one is the correct one for a given sliding window position. This would allow for multiple scales and/or aspect ratios to be decided by the system, but without introducing full bounding box regression, which he have found to be an issue in small training data scales. As future work, additional terms to the loss function could be added in order to ensure or force that high objectness scoring windows are more likely to be correctly classified. A more fine tuning of the multi-task loss weight $\gamma$ should be performed, and more training data, including more variability on object pose, should be used. \FloatBarrier \newpage \section{Tracking by Matching} \subsection{Introduction} Tracking is the process of first detecting an object of interest in an image, and then continually detect its position in subsequent frames. This operation is typically performed on video frames or equivalently on data that has a temporal dimension. Tracking is challenging due to the possible changes in object appearance as time moves forward. In general, tracking is performed by finding relevant features in the target object, and try to match them in subsequent frames \cite{yilmaz2006object}. This is called feature tracking. An alternative formulation is tracking by detection \cite[1em]{vcehovin2016visual}, which uses simple object detectors to detect the target in the current and subsequent frames, with additions in order to exploit temporal correlations. In this section we evaluate a tracker built with our matching function, as to showcase a real underwater robotics application. It should be noted that this section is not intended as a general tracking evaluation in sonar images, but to compare the use of similarity measures and matching for tracking. \subsection{Proposed Method} A popular option for tracking is tracking as object detection, where an object is tracked by first running an object detector on the input image, and then matching objects between frames by considering features like overlap, appearance and filter predictions. Our matching networks can also be used for tracking. We evaluate a tracker that is composed of two stages: \begin{itemize} \item \textbf{Detection Stage}. We detect objects in the input image using our detection proposal algorithm presented in Chapter \ref{chapter:proposals}. At tracker initialization, the proposal to be tracked is cropped from the input image and saved as template for matching. \item \textbf{Matching Stage}. Each proposal is matched to the template obtained during initialization, and the proposal with the highest matching score is output as the tracked object. \end{itemize} While this method is simple, it incorporates all the information that matching and detection proposal algorithms contain. Tracker performance completely depends on matching accuracy, and we will show that our tracker performs appropriately. \subsection{Experimental Evaluation} For the Marine Debris task, tracking is required as the AUV might experience underwater currents that result in the target object moving in the sonar image, and during object manipulation, the object must be tracked robustly. One way to measure robustness of the tracker is to measure the number of correctly tracked frames (CTF) \cite{vcehovin2016visual}, which is also human interpretable. To make a fair comparison, we constructed another tracker that uses a cross-correlation similarity (Eq \ref{ccSimilarityEq}) instead of our CNN matching function. If $S_{CC} > 0.01$, then we declare a match. This is a deliberate low threshold used to evaluate the difficulty of tracking objects in our dataset. The same detection proposal algorithm from Chapter \ref{chapter:proposals} is used. For both trackers we generate the top 10 proposals ranked by objectness score. \vspace*{1em} \begin{equation} S_{CC}(I, T) = \frac{\sum (I - \bar{I}) \sum (T - \bar{T})}{\sqrt{\sum (I - \bar{I})^2 \sum (T - \bar{T})^2}} \label{ccSimilarityEq} \end{equation} We have evaluated 3 sequences with one object each. The first sequence corresponds to 51 frames containing a can, the second sequence corresponds to 55 valve mockup frames, and the last sequence contains a glass bottle over 17 frames. We use network 2-Chan CNN Class as a matching function, as this is the best performing matcher that we have built. We report the CTF as a function of the overlap score threshold $O_t$ (Intersection over Union, Eq \ref{iouEquation}) between the predicted bounding box and ground truth. \vspace*{1em} \begin{equation} \text{iou}(A, B) = \frac{\text{area}(A \cap B)}{\text{area}(A \cup B)} \label{iouEquation} \end{equation} The CTF metric captures how well the tracker tracks the object as a function of $O_t$. Typically the CTF is only reported at $O_t = 0.5$, which is the most common value used for object detection. We report the CTF at this value in Table \ref{apps-track:trackingSummary}. \begin{table*}[t] \begin{tabular}{lllll} \hline Metric / Sequence & Method & Can & Valve & Glass Bottle\\ \hline \multirow{2}{*}{CTF at IoU $O_t = 0.5$} & Matching CNN & $\mathbf{74.0}$ \% & $\mathbf{100.0}$ \% & $\mathbf{81.3}$ \% \\ & CC TM & $6.0$ \% & $35.2$ \% & $50.0$ \% \\ \hline \end{tabular} \vspace*{0.5cm} \caption[Summary of tracking results]{Summary of tracking results. We compare our tracker built using a Matching CNN versus Cross-Correlation Template Matching using the correctly tracked frames ratio (CTF).} \label{apps-track:trackingSummary} \end{table*} Our tracker results are shown in Fig. \ref{apps-tracking:ctfPlots}. In all three sequences the matching CNN makes a better tracker, which can be seen from a higher correctly tracked frames ratio across different $O_t$ values. This may be due to variations in the background (insonification), reflections and small object rotations. If any of these conditions change, the CC between template and target drops close to zero, producing strong tracker failures. Our matching network is more robust to object rotations than plain CC. The CC tracker has a high failure rate, specially for the Can Sequence where it achieves the lowest correctly tracker frames ratio. The Can Sequence (Fig \ref{apps-tracking:ctfPlots}a) is interesting as our tracker can track the object well ($74.0 \%$ CTF at $O_t = 0.5$), but the CC tracker fails and cannot keep track of the object. This is due to strong reflections generated by the can's lid. Seems that our matching function is partially invariant to these reflections and performs better. This result shows that a CNN provides better generalization for matching than using other classic methods. It could be considered that initializing the tracker once, without re-initialization at failure, is extreme, but our tracker works well with single initialization. It can successfully track the object even as insonification or orientation changes. \begin{figure*}[!t] \forceversofloat \centering \subfloat[Can Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.32\textwidth, xlabel={IoU Threshold $O_t$}, ylabel={Correctly Tracked Frames}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend style={at={(0.5, 1.05)},anchor=south}] \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-can-CTFVsThreshold.csv}; \addlegendentry{Our Tracker} \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-can-CTFVsThreshold.csv}; \addlegendentry{CC Tracker} \end{axis} \end{tikzpicture} } \subfloat[Valve Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.32\textwidth, xlabel={IoU Threshold $O_t$}, ylabel={Correctly Tracked Frames}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south east] \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-valve-CTFVsThreshold.csv}; \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-valve-CTFVsThreshold.csv}; \end{axis} \end{tikzpicture} } \subfloat[Bottle Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.32\textwidth, xlabel={IoU Threshold $O_t$}, ylabel={Correctly Tracked Frames}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south east] \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-bottle-CTFVsThreshold.csv}; \addplot+[mark = none] table[x = threshold, y = ctf, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-bottle-CTFVsThreshold.csv}; \end{axis} \end{tikzpicture} } \vspace*{0.5cm} \caption{Number of correctly tracked frames as a function of the IoU overlap threshold $O_t$ for each sequence.} \label{apps-tracking:ctfPlots} \end{figure*} Figure \ref{apps-track:iouPlots} shows a comparison of IoU values as a function of the normalized frame number. These plots show how the cross-correlation tracker fails. For the Can sequence the CC-based tracker can only correctly track the object for a small number of frames, and it constantly confuses the object with background. A similar effect is seen for the Valve sequence, while the Bottle sequence has better tracking performance but completely fails after working for $40$ \% of the frames. CC tracking failures could be due to correlations between the sonar background and template background, which could be larger than the correlations induced by the actual object. This means that a CC-based tracker fails because it learns to track the background instead of the target object. As mentioned in Chapter \ref{chapter:sonar-classification}, many template matching methods first segment the image and the template in order to reduce the effect of background, but doing this requires additional background models. This result means that the matching network effectively learned to compare object features instead of concentrating on the background, which is highly desirable and could explain the generalization gap with other methods. \begin{figure*}[!t] \centering \subfloat[Can Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.29\textwidth, xlabel={Normalized Frame Number}, ylabel={IoU}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend style={at={(0.5, 1.05)},anchor=south}] \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-can-K3.csv}; \addlegendentry{Our Tracker} \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-can-K3.csv}; \addlegendentry{CC Tracker} \end{axis} \end{tikzpicture} } \subfloat[Valve Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.29\textwidth, xlabel={Normalized Frame Number}, ylabel={IoU}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south east] \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-valve-K3.csv}; \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-valve-K3.csv}; \end{axis} \end{tikzpicture} } \subfloat[Bottle Sequence]{ \begin{tikzpicture} \begin{axis}[height = 0.21\textheight, width = 0.29\textwidth, xlabel={Normalized Frame Number}, ylabel={IoU}, xmin=0, xmax=1.0, ymin=0, ymax=1.0, ymajorgrids=true, xmajorgrids=true, grid style=dashed, legend pos = south east] \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingBinaryMatcherPerformance-bottle-K3.csv}; \addplot+[mark = none] table[x = normFrame, y = iou, col sep = space] {chapters/data/applications/tracking/trackingTemplateMatcherPerformance-bottle-K3.csv}; \end{axis} \end{tikzpicture} } \vspace*{0.5cm} \caption{IoU score as a function of the frame numbers for each sequence.} \label{apps-track:iouPlots} \end{figure*} A small sample of tracked objects is shown in Fig. \ref{sampleTrackerFrames}. These images show the changes in insonification (seen as changes in background around the object) and object appearance that we previously mentioned. This effect is more noticeable in the Bottle sequence. The Can sequence also shows this effect, as the object does not change orientation significantly, but background varies, which confuses a cross-correlation based tracker. It should be mentioned that using cross-correlation is a commonly used as a simple tracking solution, but it has major issues, like a tendency to lose track of the object by correlating with spurious image features, which make it drift from the real tracked object. We have not observed such behaviour, but our results also show that template matching is not a good solution for patch matching and tracking. We believe our results show that the matching network can be successfully used for tracking. This is only a limited example with a template matching baseline, but it shows that a simple tracker that can easily be trained from labeled data (including the detection proposal and matching networks) without much effort. Comparing with other state of the art trackers in sonar images, they usually include a heavy probabilistic formulation that is hard to implement and tune. We do not believe that our tracker can outperform state of the art trackers that are based on CNNs. Other newer approaches are more likely to perform better but require considerable more data. For example, the deep regression networks for tracking by Held et al \cite{held2016learning} . The winners from the Visual Object Tracking (VOT) challenge (held each year) are strong candidates to outperform our method, but usually these methods are quite complex and are trained on considerably larger datasets. A big challenge in Machine Learning and Computer Vision is to solve tasks without requiring large training sets \cite{sun2017revisiting}. While large datasets are available for many computer vision tasks, their availability for robotics scenarios is smaller. Particularly for underwater environments the availability of public datasets is very scarce. Then our tracking technique is particularly valuable in contexts where large training sets are not available. Improvements in the matching function, either from better network models or data with more object variability, will immediately transfer into improvements in tracking. As we expect that detection proposals will be used in an AUV to find "interesting" objects, using the matching networks for tracking can be considered as a more streamlined architecture than just one network that performs tracking as a black box separately from object detection. \section{Summary of Results} In this chapter we have presented two applications of detection proposals. The first is object detection with an end-to-end pipeline which allows high recall ($95 \%$) and modest accuracy ($80 \%$) without making assumptions on object shape and not requiring pre-training on a classification dataset (thus end-to-end). Learning this way allows features to adapt to the problem, but it has the issue of not providing the best classification performance. After replacing the fully connected layers that do classification with a multi-class SVM, we see an improvement to $90 \%$ accuracy, which shows that there is room for improvement. We expect that more data and better techniques will further improve performance, specially with respect of reducing false positives. The second application was object tracking by combining our detection proposals algorithm with matching. By using the first detection as matching target, we can continuously track a desired object. In comparison with a template matching approach, using a neural network for matching provides a much better correctly tracked frames metric in the marine debris sequence dataset, with a higher IoU. The template matching tracker constantly loses track of the object and cannot correctly match it with the original object view. This shows that the matching CNNs are much more robust for real-world applications. \begin{figure*}[!tb] \centering \subfloat[Can Sequence]{ \centering \includegraphics[width=0.30\textwidth]{chapters/images/applications/tracking/2016-02-05_055052-frame02415-proposals.jpg} \includegraphics[width=0.30 \textwidth]{chapters/images/applications/tracking/2016-02-05_055052-frame02442-proposals.jpg} \includegraphics[width=0.30 \textwidth]{chapters/images/applications/tracking/2016-02-05_055052-frame02462-proposals.jpg} } \subfloat[Valve Sequence]{ \centering \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame16017-proposals.jpg} \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame16046-proposals.jpg} \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame16070-proposals.jpg} } \subfloat[Bottle Sequence]{ \centering \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame02632-proposals.jpg} \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame02640-proposals.jpg} \includegraphics[width=0.23\textwidth]{chapters/images/applications/tracking/2016-02-11_070611-frame02681-proposals.jpg} } \vspace*{0.5cm} \caption[Sample tracking results generated by our tracker]{Sample tracking results generated by our tracker. Green is the ground truth, while red is the bounding box generated by our tracker.} \label{sampleTrackerFrames} \end{figure*}
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef NOMPI #include <mpi.h> #endif #include <sys/types.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include "allvars.h" #include "proto.h" /*! \file begrun.c * \brief initial set-up of a simulation run * * This file contains various functions to initialize a simulation run. In * particular, the parameterfile is read in and parsed, the initial * conditions or restart files are read, and global variables are * initialized to their proper values. */ /*! This function performs the initial set-up of the simulation. First, the * parameterfile is set, then routines for setting units, reading * ICs/restart-files are called, auxialiary memory is allocated, etc. */ void begrun(void) { struct global_data_all_processes all; if(ThisTask == 0) { printf("\nThis is Gadget, version `%s'.\n", GADGETVERSION); printf("\nRunning on %d processors.\n", NTask); } read_parameter_file(ParameterFile); /* ... read in parameters for this run */ allocate_commbuffers(); /* ... allocate buffer-memory for particle exchange during force computation */ set_units(); #if defined(PERIODIC) && (!defined(PMGRID) || defined(FORCETEST)) ewald_init(); #endif open_outputfiles(); random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(random_generator, 42); /* start-up seed */ #ifdef PMGRID long_range_init(); #endif All.TimeLastRestartFile = CPUThisRun; if(RestartFlag == 0 || RestartFlag == 2) { set_random_numbers(); init(); /* ... read in initial model */ } else { all = All; /* save global variables. (will be read from restart file) */ restart(RestartFlag); /* ... read restart file. Note: This also resets all variables in the struct `All'. However, during the run, some variables in the parameter file are allowed to be changed, if desired. These need to copied in the way below. Note: All.PartAllocFactor is treated in restart() separately. */ All.MinSizeTimestep = all.MinSizeTimestep; All.MaxSizeTimestep = all.MaxSizeTimestep; All.BufferSize = all.BufferSize; All.BunchSizeForce = all.BunchSizeForce; All.BunchSizeDensity = all.BunchSizeDensity; All.BunchSizeHydro = all.BunchSizeHydro; All.BunchSizeDomain = all.BunchSizeDomain; All.TimeLimitCPU = all.TimeLimitCPU; All.ResubmitOn = all.ResubmitOn; All.TimeBetSnapshot = all.TimeBetSnapshot; All.TimeBetStatistics = all.TimeBetStatistics; All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile; All.ErrTolIntAccuracy = all.ErrTolIntAccuracy; All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac; All.ErrTolForceAcc = all.ErrTolForceAcc; All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion; All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion; All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel; All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency; All.SnapFormat = all.SnapFormat; All.NumFilesPerSnapshot = all.NumFilesPerSnapshot; All.MaxNumNgbDeviation = all.MaxNumNgbDeviation; All.ArtBulkViscConst = all.ArtBulkViscConst; All.ArtBulkViscBeta = 2*all.ArtBulkViscConst; All.OutputListOn = all.OutputListOn; All.CourantFac = all.CourantFac; All.OutputListLength = all.OutputListLength; memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength); strcpy(All.ResubmitCommand, all.ResubmitCommand); strcpy(All.OutputListFilename, all.OutputListFilename); strcpy(All.OutputDir, all.OutputDir); strcpy(All.RestartFile, all.RestartFile); strcpy(All.EnergyFile, all.EnergyFile); strcpy(All.InfoFile, all.InfoFile); strcpy(All.CpuFile, all.CpuFile); strcpy(All.TimingsFile, all.TimingsFile); strcpy(All.SnapshotFileBase, all.SnapshotFileBase); if(All.TimeMax != all.TimeMax) readjust_timebase(All.TimeMax, all.TimeMax); } #ifdef PMGRID long_range_init_regionsize(); #endif if(All.ComovingIntegrationOn) init_drift_table(); if(RestartFlag == 2) All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 1); else All.Ti_nextoutput = find_next_outputtime(All.Ti_Current); All.TimeLastRestartFile = CPUThisRun; } /*! Computes conversion factors between internal code units and the * cgs-system. */ void set_units(void) { double meanweight; All.UnitTime_in_s = All.UnitLength_in_cm / All.UnitVelocity_in_cm_per_s; All.UnitTime_in_Megayears = All.UnitTime_in_s / SEC_PER_MEGAYEAR; if(All.GravityConstantInternal == 0) All.G = GRAVITY / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g * pow(All.UnitTime_in_s, 2); else All.G = All.GravityConstantInternal; All.UnitDensity_in_cgs = All.UnitMass_in_g / pow(All.UnitLength_in_cm, 3); All.UnitPressure_in_cgs = All.UnitMass_in_g / All.UnitLength_in_cm / pow(All.UnitTime_in_s, 2); All.UnitCoolingRate_in_cgs = All.UnitPressure_in_cgs / All.UnitTime_in_s; All.UnitEnergy_in_cgs = All.UnitMass_in_g * pow(All.UnitLength_in_cm, 2) / pow(All.UnitTime_in_s, 2); /* convert some physical input parameters to internal units */ All.Hubble = HUBBLE * All.UnitTime_in_s; if(ThisTask == 0) { printf("\nHubble (internal units) = %g\n", All.Hubble); printf("G (internal units) = %g\n", All.G); printf("UnitMass_in_g = %g \n", All.UnitMass_in_g); printf("UnitTime_in_s = %g \n", All.UnitTime_in_s); printf("UnitVelocity_in_cm_per_s = %g \n", All.UnitVelocity_in_cm_per_s); printf("UnitDensity_in_cgs = %g \n", All.UnitDensity_in_cgs); printf("UnitEnergy_in_cgs = %g \n", All.UnitEnergy_in_cgs); printf("\n"); } meanweight = 4.0 / (1 + 3 * HYDROGEN_MASSFRAC); /* note: we assume neutral gas here */ #ifdef ISOTHERM_EQS All.MinEgySpec = 0; #else All.MinEgySpec = 1 / meanweight * (1.0 / GAMMA_MINUS1) * (BOLTZMANN / PROTONMASS) * All.MinGasTemp; All.MinEgySpec *= All.UnitMass_in_g / All.UnitEnergy_in_cgs; #endif } /*! This function opens various log-files that report on the status and * performance of the simulstion. On restart from restart-files * (start-option 1), the code will append to these files. */ void open_outputfiles(void) { char mode[2], buf[200]; if(ThisTask != 0) /* only the root processor writes to the log files */ return; if(RestartFlag == 0) strcpy(mode, "w"); else strcpy(mode, "a"); sprintf(buf, "%s%s", All.OutputDir, All.CpuFile); if(!(FdCPU = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.InfoFile); if(!(FdInfo = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.EnergyFile); if(!(FdEnergy = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.TimingsFile); if(!(FdTimings = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } #ifdef FORCETEST if(RestartFlag == 0) { sprintf(buf, "%s%s", All.OutputDir, "forcetest.txt"); if(!(FdForceTest = fopen(buf, "w"))) { printf("error in opening file '%s'\n", buf); endrun(1); } fclose(FdForceTest); } #endif } /*! This function closes the global log-files. */ void close_outputfiles(void) { if(ThisTask != 0) /* only the root processor writes to the log files */ return; fclose(FdCPU); fclose(FdInfo); fclose(FdEnergy); fclose(FdTimings); #ifdef FORCETEST fclose(FdForceTest); #endif } /*! This function parses the parameterfile in a simple way. Each paramater * is defined by a keyword (`tag'), and can be either of type double, int, * or character string. The routine makes sure that each parameter * appears exactly once in the parameterfile, otherwise error messages are * produced that complain about the missing parameters. */ void read_parameter_file(char *fname) { #define DOUBLE 1 #define STRING 2 #define INT 3 #define MAXTAGS 300 FILE *fd, *fdout; char buf[200], buf1[200], buf2[200], buf3[400]; int i, j, nt; int id[MAXTAGS]; void *addr[MAXTAGS]; char tag[MAXTAGS][50]; int errorFlag = 0; if(sizeof(long long) != 8) { if(ThisTask == 0) printf("\nType `long long' is not 64 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(int) != 4) { if(ThisTask == 0) printf("\nType `int' is not 32 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(float) != 4) { if(ThisTask == 0) printf("\nType `float' is not 32 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(double) != 8) { if(ThisTask == 0) printf("\nType `double' is not 64 bit on this platform. Stopping.\n\n"); endrun(0); } if(ThisTask == 0) /* read parameter file on process 0 */ { nt = 0; strcpy(tag[nt], "InitCondFile"); addr[nt] = All.InitCondFile; id[nt++] = STRING; strcpy(tag[nt], "OutputDir"); addr[nt] = All.OutputDir; id[nt++] = STRING; strcpy(tag[nt], "SnapshotFileBase"); addr[nt] = All.SnapshotFileBase; id[nt++] = STRING; strcpy(tag[nt], "EnergyFile"); addr[nt] = All.EnergyFile; id[nt++] = STRING; strcpy(tag[nt], "CpuFile"); addr[nt] = All.CpuFile; id[nt++] = STRING; strcpy(tag[nt], "InfoFile"); addr[nt] = All.InfoFile; id[nt++] = STRING; strcpy(tag[nt], "TimingsFile"); addr[nt] = All.TimingsFile; id[nt++] = STRING; strcpy(tag[nt], "RestartFile"); addr[nt] = All.RestartFile; id[nt++] = STRING; strcpy(tag[nt], "ResubmitCommand"); addr[nt] = All.ResubmitCommand; id[nt++] = STRING; strcpy(tag[nt], "OutputListFilename"); addr[nt] = All.OutputListFilename; id[nt++] = STRING; strcpy(tag[nt], "OutputListOn"); addr[nt] = &All.OutputListOn; id[nt++] = INT; strcpy(tag[nt], "Omega0"); addr[nt] = &All.Omega0; id[nt++] = DOUBLE; strcpy(tag[nt], "OmegaBaryon"); addr[nt] = &All.OmegaBaryon; id[nt++] = DOUBLE; strcpy(tag[nt], "OmegaLambda"); addr[nt] = &All.OmegaLambda; id[nt++] = DOUBLE; strcpy(tag[nt], "HubbleParam"); addr[nt] = &All.HubbleParam; id[nt++] = DOUBLE; strcpy(tag[nt], "BoxSize"); addr[nt] = &All.BoxSize; id[nt++] = DOUBLE; strcpy(tag[nt], "PeriodicBoundariesOn"); addr[nt] = &All.PeriodicBoundariesOn; id[nt++] = INT; strcpy(tag[nt], "TimeOfFirstSnapshot"); addr[nt] = &All.TimeOfFirstSnapshot; id[nt++] = DOUBLE; strcpy(tag[nt], "CpuTimeBetRestartFile"); addr[nt] = &All.CpuTimeBetRestartFile; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBetStatistics"); addr[nt] = &All.TimeBetStatistics; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBegin"); addr[nt] = &All.TimeBegin; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeMax"); addr[nt] = &All.TimeMax; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBetSnapshot"); addr[nt] = &All.TimeBetSnapshot; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitVelocity_in_cm_per_s"); addr[nt] = &All.UnitVelocity_in_cm_per_s; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitLength_in_cm"); addr[nt] = &All.UnitLength_in_cm; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitMass_in_g"); addr[nt] = &All.UnitMass_in_g; id[nt++] = DOUBLE; strcpy(tag[nt], "TreeDomainUpdateFrequency"); addr[nt] = &All.TreeDomainUpdateFrequency; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolIntAccuracy"); addr[nt] = &All.ErrTolIntAccuracy; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolTheta"); addr[nt] = &All.ErrTolTheta; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolForceAcc"); addr[nt] = &All.ErrTolForceAcc; id[nt++] = DOUBLE; strcpy(tag[nt], "MinGasHsmlFractional"); addr[nt] = &All.MinGasHsmlFractional; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxSizeTimestep"); addr[nt] = &All.MaxSizeTimestep; id[nt++] = DOUBLE; strcpy(tag[nt], "MinSizeTimestep"); addr[nt] = &All.MinSizeTimestep; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxRMSDisplacementFac"); addr[nt] = &All.MaxRMSDisplacementFac; id[nt++] = DOUBLE; strcpy(tag[nt], "ArtBulkViscConst"); addr[nt] = &All.ArtBulkViscConst; id[nt++] = DOUBLE; strcpy(tag[nt], "CourantFac"); addr[nt] = &All.CourantFac; id[nt++] = DOUBLE; strcpy(tag[nt], "DesNumNgb"); addr[nt] = &All.DesNumNgb; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxNumNgbDeviation"); addr[nt] = &All.MaxNumNgbDeviation; id[nt++] = DOUBLE; strcpy(tag[nt], "ComovingIntegrationOn"); addr[nt] = &All.ComovingIntegrationOn; id[nt++] = INT; strcpy(tag[nt], "ICFormat"); addr[nt] = &All.ICFormat; id[nt++] = INT; strcpy(tag[nt], "SnapFormat"); addr[nt] = &All.SnapFormat; id[nt++] = INT; strcpy(tag[nt], "NumFilesPerSnapshot"); addr[nt] = &All.NumFilesPerSnapshot; id[nt++] = INT; strcpy(tag[nt], "NumFilesWrittenInParallel"); addr[nt] = &All.NumFilesWrittenInParallel; id[nt++] = INT; strcpy(tag[nt], "ResubmitOn"); addr[nt] = &All.ResubmitOn; id[nt++] = INT; strcpy(tag[nt], "TypeOfTimestepCriterion"); addr[nt] = &All.TypeOfTimestepCriterion; id[nt++] = INT; strcpy(tag[nt], "TypeOfOpeningCriterion"); addr[nt] = &All.TypeOfOpeningCriterion; id[nt++] = INT; strcpy(tag[nt], "TimeLimitCPU"); addr[nt] = &All.TimeLimitCPU; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningHalo"); addr[nt] = &All.SofteningHalo; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningDisk"); addr[nt] = &All.SofteningDisk; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBulge"); addr[nt] = &All.SofteningBulge; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningGas"); addr[nt] = &All.SofteningGas; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningStars"); addr[nt] = &All.SofteningStars; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBndry"); addr[nt] = &All.SofteningBndry; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningHaloMaxPhys"); addr[nt] = &All.SofteningHaloMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningDiskMaxPhys"); addr[nt] = &All.SofteningDiskMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBulgeMaxPhys"); addr[nt] = &All.SofteningBulgeMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningGasMaxPhys"); addr[nt] = &All.SofteningGasMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningStarsMaxPhys"); addr[nt] = &All.SofteningStarsMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBndryMaxPhys"); addr[nt] = &All.SofteningBndryMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "BufferSize"); addr[nt] = &All.BufferSize; id[nt++] = INT; strcpy(tag[nt], "PartAllocFactor"); addr[nt] = &All.PartAllocFactor; id[nt++] = DOUBLE; strcpy(tag[nt], "TreeAllocFactor"); addr[nt] = &All.TreeAllocFactor; id[nt++] = DOUBLE; strcpy(tag[nt], "GravityConstantInternal"); addr[nt] = &All.GravityConstantInternal; id[nt++] = DOUBLE; strcpy(tag[nt], "InitGasTemp"); addr[nt] = &All.InitGasTemp; id[nt++] = DOUBLE; strcpy(tag[nt], "MinGasTemp"); addr[nt] = &All.MinGasTemp; id[nt++] = DOUBLE; if((fd = fopen(fname, "r"))) { sprintf(buf, "%s%s", fname, "-usedvalues"); if(!(fdout = fopen(buf, "w"))) { printf("error opening file '%s' \n", buf); errorFlag = 1; } else { while(!feof(fd)) { *buf = 0; fgets(buf, 200, fd); if(sscanf(buf, "%s%s%s", buf1, buf2, buf3) < 2) continue; if(buf1[0] == '%') continue; for(i = 0, j = -1; i < nt; i++) if(strcmp(buf1, tag[i]) == 0) { j = i; tag[i][0] = 0; break; } if(j >= 0) { switch (id[j]) { case DOUBLE: *((double *) addr[j]) = atof(buf2); fprintf(fdout, "%-35s%g\n", buf1, *((double *) addr[j])); break; case STRING: strcpy(addr[j], buf2); fprintf(fdout, "%-35s%s\n", buf1, buf2); break; case INT: *((int *) addr[j]) = atoi(buf2); fprintf(fdout, "%-35s%d\n", buf1, *((int *) addr[j])); break; } } else { fprintf(stdout, "Error in file %s: Tag '%s' not allowed or multiple defined.\n", fname, buf1); errorFlag = 1; } } fclose(fd); fclose(fdout); i = strlen(All.OutputDir); if(i > 0) if(All.OutputDir[i - 1] != '/') strcat(All.OutputDir, "/"); sprintf(buf1, "%s%s", fname, "-usedvalues"); sprintf(buf2, "%s%s", All.OutputDir, "parameters-usedvalues"); sprintf(buf3, "cp %s %s", buf1, buf2); system(buf3); } } else { printf("\nParameter file %s not found.\n\n", fname); errorFlag = 2; } if(errorFlag != 2) for(i = 0; i < nt; i++) { if(*tag[i]) { printf("Error. I miss a value for tag '%s' in parameter file '%s'.\n", tag[i], fname); errorFlag = 1; } } if(All.OutputListOn && errorFlag == 0) errorFlag += read_outputlist(All.OutputListFilename); else All.OutputListLength = 0; } #ifndef NOMPI MPI_Bcast(&errorFlag, 1, MPI_INT, 0, GADGET_WORLD); #endif if(errorFlag) { #ifndef NOMPI MPI_Finalize(); #endif exit(0); } /* now communicate the relevant parameters to the other processes */ #ifndef NOMPI MPI_Bcast(&All, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD); #endif if(All.NumFilesWrittenInParallel < 1) { if(ThisTask == 0) printf("NumFilesWrittenInParallel MUST be at least 1\n"); endrun(0); } if(All.NumFilesWrittenInParallel > NTask) { if(ThisTask == 0) printf("NumFilesWrittenInParallel MUST be smaller than number of processors\n"); endrun(0); } #ifdef PERIODIC if(All.PeriodicBoundariesOn == 0) { if(ThisTask == 0) { printf("Code was compiled with periodic boundary conditions switched on.\n"); printf("You must set `PeriodicBoundariesOn=1', or recompile the code.\n"); } endrun(0); } #else if(All.PeriodicBoundariesOn == 1) { if(ThisTask == 0) { printf("Code was compiled with periodic boundary conditions switched off.\n"); printf("You must set `PeriodicBoundariesOn=0', or recompile the code.\n"); } endrun(0); } #endif if(All.TypeOfTimestepCriterion >= 1) { if(ThisTask == 0) { printf("The specified timestep criterion\n"); printf("is not valid\n"); } endrun(0); } #if defined(LONG_X) || defined(LONG_Y) || defined(LONG_Z) #ifndef NOGRAVITY if(ThisTask == 0) { printf("Code was compiled with LONG_X/Y/Z, but not with NOGRAVITY.\n"); printf("Stretched periodic boxes are not implemented for gravity yet.\n"); } endrun(0); #endif #endif #undef DOUBLE #undef STRING #undef INT #undef MAXTAGS } /*! this function reads a table with a list of desired output times. The * table does not have to be ordered in any way, but may not contain more * than MAXLEN_OUTPUTLIST entries. */ int read_outputlist(char *fname) { FILE *fd; if(!(fd = fopen(fname, "r"))) { printf("can't read output list in file '%s'\n", fname); return 1; } All.OutputListLength = 0; do { if(fscanf(fd, " %lg ", &All.OutputListTimes[All.OutputListLength]) == 1) All.OutputListLength++; else break; } while(All.OutputListLength < MAXLEN_OUTPUTLIST); fclose(fd); printf("\nfound %d times in output-list.\n", All.OutputListLength); return 0; } /*! If a restart from restart-files is carried out where the TimeMax * variable is increased, then the integer timeline needs to be * adjusted. The approach taken here is to reduce the resolution of the * integer timeline by factors of 2 until the new final time can be * reached within TIMEBASE. */ void readjust_timebase(double TimeMax_old, double TimeMax_new) { int i; long long ti_end; if(ThisTask == 0) { printf("\nAll.TimeMax has been changed in the parameterfile\n"); printf("Need to adjust integer timeline\n\n\n"); } if(TimeMax_new < TimeMax_old) { if(ThisTask == 0) printf("\nIt is not allowed to reduce All.TimeMax\n\n"); endrun(556); } if(All.ComovingIntegrationOn) ti_end = log(TimeMax_new / All.TimeBegin) / All.Timebase_interval; else ti_end = (TimeMax_new - All.TimeBegin) / All.Timebase_interval; while(ti_end > TIMEBASE) { All.Timebase_interval *= 2.0; ti_end /= 2; All.Ti_Current /= 2; #ifdef PMGRID All.PM_Ti_begstep /= 2; All.PM_Ti_endstep /= 2; #endif for(i = 0; i < NumPart; i++) { P[i].Ti_begstep /= 2; P[i].Ti_endstep /= 2; } } All.TimeMax = TimeMax_new; }
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: GPL-2.0-only *) theory Example_Valid_State imports "Noninterference" "Lib.Distinct_Cmd" begin section \<open>Example\<close> (* This example is a classic 'one way information flow' example, where information is allowed to flow from Low to High, but not the reverse. We consider a typical scenario where shared memory and an notification for notifications are used to implement a ring-buffer. We consider the NTFN to be in the domain of High, and the shared memory to be in the domain of Low. *) (* basic machine-level declarations that need to happen outside the locale *) consts s0_context :: user_context (* define the irqs to come regularly every 10 *) axiomatization where irq_oracle_def: "ARM.irq_oracle \<equiv> \<lambda>pos. if pos mod 10 = 0 then 10 else 0" context begin interpretation Arch . (*FIXME: arch_split*) subsection \<open>We show that the authority graph does not let information flow from High to Low\<close> datatype auth_graph_label = High | Low | IRQ0 abbreviation partition_label where "partition_label x \<equiv> OrdinaryLabel x" definition Sys1AuthGraph :: "(auth_graph_label subject_label) auth_graph" where "Sys1AuthGraph \<equiv> { (partition_label High,Read,partition_label Low), (partition_label Low,Notify,partition_label High), (partition_label Low,Reset,partition_label High), (SilcLabel,Notify,partition_label High), (SilcLabel,Reset,partition_label High) } \<union> {(x, a, y). x = y}" lemma subjectReads_Low: "subjectReads Sys1AuthGraph (partition_label Low) = {partition_label Low}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+) done lemma Low_in_subjectReads_High: "partition_label Low \<in> subjectReads Sys1AuthGraph (partition_label High)" apply (simp add: Sys1AuthGraph_def reads_read) done lemma subjectReads_High: "subjectReads Sys1AuthGraph (partition_label High) = {partition_label High,partition_label Low}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+) apply(auto intro: Low_in_subjectReads_High) done lemma subjectReads_IRQ0: "subjectReads Sys1AuthGraph (partition_label IRQ0) = {partition_label IRQ0}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+) done lemma High_in_subjectAffects_Low: "partition_label High \<in> subjectAffects Sys1AuthGraph (partition_label Low)" apply(rule affects_ep) apply (simp add: Sys1AuthGraph_def) apply (rule disjI1, simp+) done lemma subjectAffects_Low: "subjectAffects Sys1AuthGraph (partition_label Low) = {partition_label Low, partition_label High}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+) apply(auto intro: affects_lrefl High_in_subjectAffects_Low) done lemma subjectAffects_High: "subjectAffects Sys1AuthGraph (partition_label High) = {partition_label High}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+) apply(auto intro: affects_lrefl) done lemma subjectAffects_IRQ0: "subjectAffects Sys1AuthGraph (partition_label IRQ0) = {partition_label IRQ0}" apply(rule equalityI) apply(rule subsetI) apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+) apply(auto intro: affects_lrefl) done lemmas subjectReads = subjectReads_High subjectReads_Low subjectReads_IRQ0 lemma partsSubjectAffects_Low: "partsSubjectAffects Sys1AuthGraph Low = {Partition Low, Partition High}" apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_Low | case_tac xa, rename_tac xa)+ done lemma partsSubjectAffects_High: "partsSubjectAffects Sys1AuthGraph High = {Partition High}" apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_High | rename_tac xa, case_tac xa)+ done lemma partsSubjectAffects_IRQ0: "partsSubjectAffects Sys1AuthGraph IRQ0 = {Partition IRQ0}" apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_IRQ0 | rename_tac xa, case_tac xa)+ done lemmas partsSubjectAffects = partsSubjectAffects_High partsSubjectAffects_Low partsSubjectAffects_IRQ0 definition example_policy where "example_policy \<equiv> {(PSched, d)|d. True} \<union> {(d,e). d = e} \<union> {(Partition Low, Partition High)}" lemma "policyFlows Sys1AuthGraph = example_policy" apply(rule equalityI) apply(rule subsetI) apply(clarsimp simp: example_policy_def) apply(erule policyFlows.cases) apply(case_tac l, auto simp: partsSubjectAffects)[1] apply assumption apply(rule subsetI) apply(clarsimp simp: example_policy_def) apply(elim disjE) apply(fastforce simp: partsSubjectAffects intro: policy_affects) apply(fastforce intro: policy_scheduler) apply(fastforce intro: policyFlows_refl refl_onD) done subsection \<open>We show there exists a valid initial state associated to the above authority graph\<close> text \<open> This example (modified from ../access-control/ExampleSystem) is a system Sys1 made of 2 main components Low and High, connected through an notification NTFN. Both Low and High contains: . one TCB . one vspace made up of one page directory . each pd contains a single page table, with access to a shared page in memory Low can read/write to this page, High can only read . one cspace made up of one cnode . each cspace contains 4 caps: one to the tcb one to the cnode itself one to the vspace one to the ntfn Low can send to the ntfn while High can receive from it. Attempt to ASCII art: -------- ---- ---- -------- | | | | | | | | V | | V S R | V | V Low_tcb(3079)-->Low_cnode(6)--->ntfn(9)<---High_cnode(7)<--High_tcb(3080) | | | | V | | V Low_pd(3063)<----- -------> High_pd(3065) | | V R/W R V Low_pt(3072)---------------->shared_page<-----------------High_pt(3077) (the references are derived from the dump of the SAC system) The aim is to be able to prove valid_initial_state s0_internal Sys1PAS timer_irq utf where Sys1PAS is the label graph defining the AC policy for Sys1 using the authority graph defined above and s0 is the state of Sys1 described above. \<close> subsubsection \<open>Defining the State\<close> definition "ntfn_ptr \<equiv> kernel_base + 0x10" definition "Low_tcb_ptr \<equiv> kernel_base + 0x200" definition "High_tcb_ptr = kernel_base + 0x400" definition "idle_tcb_ptr = kernel_base + 0x1000" definition "Low_pt_ptr = kernel_base + 0x800" definition "High_pt_ptr = kernel_base + 0xC00" (* init_globals_frame \<equiv> {kernel_base + 0x5000,... kernel_base + 0x5FFF} *) definition "shared_page_ptr = kernel_base + 0x6000" definition "Low_pd_ptr = kernel_base + 0x20000" definition "High_pd_ptr = kernel_base + 0x24000" definition "Low_cnode_ptr = kernel_base + 0x10000" definition "High_cnode_ptr = kernel_base + 0x14000" definition "Silc_cnode_ptr = kernel_base + 0x18000" definition "irq_cnode_ptr = kernel_base + 0x1C000" (* init_global_pd \<equiv> {kernel_base + 0x60000,... kernel_base + 0x603555} *) definition "timer_irq \<equiv> 10" (* not sure exactly how this fits in *) definition "Low_mcp \<equiv> 5 :: word8" definition "Low_prio \<equiv> 5 :: word8" definition "High_mcp \<equiv> 5 :: word8" definition "High_prio \<equiv> 5 :: word8" definition "Low_time_slice \<equiv> 0 :: nat" definition "High_time_slice \<equiv> 5 :: nat" definition "Low_domain \<equiv> 0 :: word8" definition "High_domain \<equiv> 1 :: word8" lemmas s0_ptr_defs = Low_cnode_ptr_def High_cnode_ptr_def Silc_cnode_ptr_def ntfn_ptr_def irq_cnode_ptr_def Low_pd_ptr_def High_pd_ptr_def Low_pt_ptr_def High_pt_ptr_def Low_tcb_ptr_def High_tcb_ptr_def idle_tcb_ptr_def timer_irq_def Low_prio_def High_prio_def Low_time_slice_def Low_domain_def High_domain_def init_irq_node_ptr_def init_globals_frame_def init_global_pd_def kernel_base_def shared_page_ptr_def (* Distinctness proof of kernel pointers. *) distinct ptrs_distinct [simp]: Low_tcb_ptr High_tcb_ptr idle_tcb_ptr Low_pt_ptr High_pt_ptr shared_page_ptr ntfn_ptr Low_pd_ptr High_pd_ptr Low_cnode_ptr High_cnode_ptr Silc_cnode_ptr irq_cnode_ptr init_globals_frame init_global_pd by (auto simp: s0_ptr_defs) text \<open>We need to define the asids of each pd and pt to ensure that the object is included in the right ASID-label\<close> text \<open>Low's ASID\<close> definition Low_asid :: machine_word where "Low_asid \<equiv> 1<<asid_low_bits" text \<open>High's ASID\<close> definition High_asid :: machine_word where "High_asid \<equiv> 2<<asid_low_bits" lemma "asid_high_bits_of High_asid \<noteq> asid_high_bits_of Low_asid" by (simp add: Low_asid_def asid_high_bits_of_def High_asid_def asid_low_bits_def) text \<open>converting a nat to a bool list of size 10 - for the cnodes\<close> 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: uint_nat le_def word_size) done 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 mod 2^sz))" abbreviation (input) the_nat_to_bl_10 :: "nat \<Rightarrow> bool list" where "the_nat_to_bl_10 n \<equiv> the_nat_to_bl 10 n" lemma len_the_nat_to_bl [simp]: "length (the_nat_to_bl x y) = x" apply (clarsimp simp: the_nat_to_bl_def nat_to_bl_def) apply safe apply (metis le_def mod_less_divisor nat_zero_less_power_iff zero_less_numeral) apply (clarsimp simp: len_bin_to_bl_aux not_le) done lemma tcb_cnode_index_nat_to_bl [simp]: "the_nat_to_bl_10 n \<noteq> tcb_cnode_index n" by (clarsimp simp: tcb_cnode_index_def intro!: length_neq) lemma mod_less_self [simp]: "a \<le> b mod a \<longleftrightarrow> ((a :: nat) = 0)" by (metis mod_less_divisor nat_neq_iff not_less not_less0) lemma split_div_mod: "a = (b::nat) \<longleftrightarrow> (a div k = b div k \<and> a mod k = b mod k)" by (metis mult_div_mod_eq) lemma nat_to_bl_eq: assumes "a < 2 ^ n \<or> b < 2 ^ n" shows "nat_to_bl n a = nat_to_bl n b \<longleftrightarrow> a = b" using assms apply - apply (erule disjE_R) apply (clarsimp simp: nat_to_bl_def) apply (case_tac "a \<ge> 2 ^ n") apply (clarsimp simp: nat_to_bl_def) apply (clarsimp simp: not_le) apply (induct n arbitrary: a b) apply (clarsimp simp: nat_to_bl_def) apply atomize apply (clarsimp simp: nat_to_bl_def) apply (erule_tac x="a div 2" in allE) apply (erule_tac x="b div 2" in allE) apply (erule impE) apply (metis power_commutes td_gal_lt zero_less_numeral) apply (clarsimp simp: bin_rest_def bin_last_def zdiv_int) apply (rule iffI [rotated], clarsimp) apply (subst (asm) (1 2 3 4) bin_to_bl_aux_alt) apply (clarsimp simp: mod_eq_dvd_iff) apply (subst split_div_mod [where k=2]) apply clarsimp apply (metis of_nat_numeral not_mod_2_eq_0_eq_1 of_nat_1 of_nat_eq_iff zmod_int) done lemma nat_to_bl_mod_n_eq [simp]: "nat_to_bl n a = nat_to_bl n b \<longleftrightarrow> ((a = b \<and> a < 2 ^ n) \<or> (a \<ge> 2 ^ n \<and> b \<ge> 2 ^ n))" apply (rule iffI) apply (clarsimp simp: not_le) apply (subst (asm) nat_to_bl_eq, simp) apply clarsimp apply (erule disjE) apply clarsimp apply (clarsimp simp: nat_to_bl_def) done lemma the_the_eq: "\<lbrakk> x \<noteq> None; y \<noteq> None \<rbrakk> \<Longrightarrow> (the x = the y) = (x = y)" by auto lemma the_nat_to_bl_eq [simp]: "(the_nat_to_bl n a = the_nat_to_bl m b) \<longleftrightarrow> (n = m \<and> (a mod 2 ^ n = b mod 2 ^ n))" apply (case_tac "n = m") apply (clarsimp simp: the_nat_to_bl_def) apply (subst the_the_eq) apply (clarsimp simp: nat_to_bl_def) apply (clarsimp simp: nat_to_bl_def) apply simp apply simp apply (metis len_the_nat_to_bl) done lemma empty_cnode_eq_Some [simp]: "(empty_cnode n x = Some y) = (length x = n \<and> y = NullCap)" by (clarsimp simp: empty_cnode_def, metis) lemma empty_cnode_eq_None [simp]: "(empty_cnode n x = None) = (length x \<noteq> n)" by (clarsimp simp: empty_cnode_def) text \<open>Low's CSpace\<close> definition Low_caps :: cnode_contents where "Low_caps \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap Low_tcb_ptr, (the_nat_to_bl_10 2) \<mapsto> CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2), (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid)), (the_nat_to_bl_10 318) \<mapsto> NotificationCap ntfn_ptr 0 {AllowSend} )" definition Low_cnode :: kernel_object where "Low_cnode \<equiv> CNode 10 Low_caps" lemma ran_empty_cnode [simp]: "ran (empty_cnode C) = {NullCap}" by (auto simp: empty_cnode_def ran_def Ex_list_of_length intro: set_eqI) lemma empty_cnode_app [simp]: "length x = n \<Longrightarrow> empty_cnode n x = Some NullCap" by (auto simp: empty_cnode_def) lemma in_ran_If [simp]: "(x \<in> ran (\<lambda>n. if P n then A n else B n)) \<longleftrightarrow> (\<exists>n. P n \<and> A n = Some x) \<or> (\<exists>n. \<not> P n \<and> B n = Some x)" by (auto simp: ran_def) lemma Low_caps_ran: "ran Low_caps = {ThreadCap Low_tcb_ptr, CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2), ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid)), NotificationCap ntfn_ptr 0 {AllowSend}, NullCap}" apply (rule equalityI) apply (clarsimp simp: Low_caps_def fun_upd_def empty_cnode_def split: if_split_asm) apply (clarsimp simp: Low_caps_def fun_upd_def empty_cnode_def split: if_split_asm cong: conj_cong) apply (rule exI [where x="the_nat_to_bl_10 0"]) apply simp done text \<open>High's Cspace\<close> definition High_caps :: cnode_contents where "High_caps \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 1) \<mapsto> ThreadCap High_tcb_ptr, (the_nat_to_bl_10 2) \<mapsto> CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2), (the_nat_to_bl_10 3) \<mapsto> ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid)), (the_nat_to_bl_10 318) \<mapsto> NotificationCap ntfn_ptr 0 {AllowRecv}) " definition High_cnode :: kernel_object where "High_cnode \<equiv> CNode 10 High_caps" lemma High_caps_ran: "ran High_caps = {ThreadCap High_tcb_ptr, CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2), ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid)), NotificationCap ntfn_ptr 0 {AllowRecv}, NullCap}" apply (rule equalityI) apply (clarsimp simp: High_caps_def ran_def empty_cnode_def split: if_split_asm) apply (clarsimp simp: High_caps_def ran_def empty_cnode_def split: if_split_asm cong: conj_cong) apply (rule exI [where x="the_nat_to_bl_10 0"]) apply simp done text \<open>We need a copy of boundary crossing caps owned by SilcLabel. The only such cap is Low's cap to the notification\<close> definition Silc_caps :: cnode_contents where "Silc_caps \<equiv> (empty_cnode 10) ( (the_nat_to_bl_10 2) \<mapsto> CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2), (the_nat_to_bl_10 318) \<mapsto> NotificationCap ntfn_ptr 0 {AllowSend} )" definition Silc_cnode :: kernel_object where "Silc_cnode \<equiv> CNode 10 Silc_caps" lemma Silc_caps_ran: "ran Silc_caps = {CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2), NotificationCap ntfn_ptr 0 {AllowSend}, NullCap}" apply (rule equalityI) apply (clarsimp simp: Silc_caps_def ran_def empty_cnode_def) apply (clarsimp simp: ran_def Silc_caps_def empty_cnode_def cong: conj_cong) apply (rule_tac x="the_nat_to_bl_10 0" in exI) apply simp done text \<open>notification between Low and High\<close> definition ntfn :: kernel_object where "ntfn \<equiv> Notification \<lparr>ntfn_obj = WaitingNtfn [High_tcb_ptr], ntfn_bound_tcb=None\<rparr>" text \<open>Low's VSpace (PageDirectory)\<close> definition Low_pt' :: "word8 \<Rightarrow> pte " where "Low_pt' \<equiv> (\<lambda>_. InvalidPTE) (0 := SmallPagePTE shared_page_ptr {} vm_read_write)" definition Low_pt :: kernel_object where "Low_pt \<equiv> ArchObj (PageTable Low_pt')" definition Low_pd' :: "12 word \<Rightarrow> pde " where "Low_pd' \<equiv> global_pd (0 := PageTablePDE (addrFromPPtr Low_pt_ptr) {} undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition Low_pd :: kernel_object where "Low_pd \<equiv> ArchObj (PageDirectory Low_pd')" text \<open>High's VSpace (PageDirectory)\<close> definition High_pt' :: "word8 \<Rightarrow> pte " where "High_pt' \<equiv> (\<lambda>_. InvalidPTE) (0 := SmallPagePTE shared_page_ptr {} vm_read_only)" definition High_pt :: kernel_object where "High_pt \<equiv> ArchObj (PageTable High_pt')" definition High_pd' :: "12 word \<Rightarrow> pde " where "High_pd' \<equiv> global_pd (0 := PageTablePDE (addrFromPPtr High_pt_ptr) {} undefined )" (* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check if it's right *) definition High_pd :: kernel_object where "High_pd \<equiv> ArchObj (PageDirectory High_pd')" text \<open>Low's tcb\<close> definition Low_tcb :: kernel_object where "Low_tcb \<equiv> TCB \<lparr> tcb_ctable = CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2), tcb_vtable = ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid)), tcb_reply = ReplyCap Low_tcb_ptr True {AllowGrant, AllowWrite}, \<comment> \<open>master reply cap\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = Running, tcb_fault_handler = replicate word_bits False, tcb_ipc_buffer = 0, tcb_fault = None, tcb_bound_notification = None, tcb_mcpriority = Low_mcp, tcb_arch = \<lparr> tcb_context = undefined \<rparr>\<rparr>" definition Low_etcb :: etcb where "Low_etcb \<equiv> \<lparr>tcb_priority = Low_prio, tcb_time_slice = Low_time_slice, tcb_domain = Low_domain\<rparr>" text \<open>High's tcb\<close> definition High_tcb :: kernel_object where "High_tcb \<equiv> TCB \<lparr> tcb_ctable = CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2) , tcb_vtable = ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid)), tcb_reply = ReplyCap High_tcb_ptr True {AllowGrant,AllowWrite}, \<comment> \<open>master reply cap to itself\<close> tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = BlockedOnNotification ntfn_ptr, tcb_fault_handler = replicate word_bits False, tcb_ipc_buffer = 0, tcb_fault = None, tcb_bound_notification = None, tcb_mcpriority = High_mcp, tcb_arch = \<lparr> tcb_context = undefined \<rparr>\<rparr>" definition High_etcb :: etcb where "High_etcb \<equiv> \<lparr>tcb_priority = High_prio, tcb_time_slice = High_time_slice, tcb_domain = High_domain\<rparr>" text \<open>idle's tcb\<close> definition idle_tcb :: kernel_object where "idle_tcb \<equiv> TCB \<lparr> tcb_ctable = NullCap, tcb_vtable = NullCap, tcb_reply = NullCap, tcb_caller = NullCap, tcb_ipcframe = NullCap, tcb_state = IdleThreadState, tcb_fault_handler = replicate word_bits False, tcb_ipc_buffer = 0, tcb_fault = None, tcb_bound_notification = None, tcb_mcpriority = default_priority, tcb_arch = \<lparr> tcb_context = empty_context \<rparr>\<rparr>" definition "irq_cnode \<equiv> CNode 0 (Map.empty([] \<mapsto> cap.NullCap))" definition kh0 :: kheap where "kh0 \<equiv> (\<lambda>x. if \<exists>irq::10 word. init_irq_node_ptr + (ucast irq << cte_level_bits) = x then Some (CNode 0 (empty_cnode 0)) else None) (Low_cnode_ptr \<mapsto> Low_cnode, High_cnode_ptr \<mapsto> High_cnode, Silc_cnode_ptr \<mapsto> Silc_cnode, ntfn_ptr \<mapsto> ntfn, irq_cnode_ptr \<mapsto> irq_cnode, Low_pd_ptr \<mapsto> Low_pd, High_pd_ptr \<mapsto> High_pd, Low_pt_ptr \<mapsto> Low_pt, High_pt_ptr \<mapsto> High_pt, Low_tcb_ptr \<mapsto> Low_tcb, High_tcb_ptr \<mapsto> High_tcb, idle_tcb_ptr \<mapsto> idle_tcb, init_globals_frame \<mapsto> ArchObj (DataPage False ARMSmallPage), init_global_pd \<mapsto> ArchObj (PageDirectory global_pd))" lemma irq_node_offs_min: "init_irq_node_ptr \<le> init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits)" apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def shiftl_t2n s0_ptr_defs cte_level_bits_def) apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) done lemma irq_node_offs_max: "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) < init_irq_node_ptr + 0x4000" apply (simp add: s0_ptr_defs cte_level_bits_def shiftl_t2n) apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt unat_word_ariths) done definition irq_node_offs_range where "irq_node_offs_range \<equiv> {x. init_irq_node_ptr \<le> x \<and> x < init_irq_node_ptr + 0x4000} \<inter> {x. is_aligned x cte_level_bits}" lemma irq_node_offs_in_range: "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<in> irq_node_offs_range" apply (clarsimp simp: irq_node_offs_min irq_node_offs_max irq_node_offs_range_def) apply (rule is_aligned_add[OF _ is_aligned_shift]) apply (simp add: is_aligned_def s0_ptr_defs cte_level_bits_def) done lemma irq_node_offs_range_correct: "x \<in> irq_node_offs_range \<Longrightarrow> \<exists>irq. x = init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits)" apply (clarsimp simp: irq_node_offs_min irq_node_offs_max irq_node_offs_range_def s0_ptr_defs cte_level_bits_def) apply (rule_tac x="ucast ((x - 0xE0008000) >> 4)" in exI) apply (clarsimp simp: ucast_ucast_mask) apply (subst aligned_shiftr_mask_shiftl) apply (rule aligned_sub_aligned) apply assumption apply (simp add: is_aligned_def) apply simp apply simp apply (rule_tac n=14 in mask_eqI) apply (subst mask_add_aligned) apply (simp add: is_aligned_def) apply (simp add: mask_twice) apply (simp add: diff_conv_add_uminus del: add_uminus_conv_diff) apply (subst add.commute[symmetric]) apply (subst mask_add_aligned) apply (simp add: is_aligned_def) apply simp apply (simp add: diff_conv_add_uminus del: add_uminus_conv_diff) apply (subst add_mask_lower_bits) apply (simp add: is_aligned_def) apply clarsimp apply (cut_tac x=x and y="0xE000BFFF" and n=14 in neg_mask_mono_le) apply (force dest: word_less_sub_1) apply (drule_tac n=14 in aligned_le_sharp) apply (simp add: is_aligned_def) apply (simp add: mask_def) done lemma irq_node_offs_range_distinct[simp]: "Low_cnode_ptr \<notin> irq_node_offs_range" "High_cnode_ptr \<notin> irq_node_offs_range" "Silc_cnode_ptr \<notin> irq_node_offs_range" "ntfn_ptr \<notin> irq_node_offs_range" "irq_cnode_ptr \<notin> irq_node_offs_range" "Low_pd_ptr \<notin> irq_node_offs_range" "High_pd_ptr \<notin> irq_node_offs_range" "Low_pt_ptr \<notin> irq_node_offs_range" "High_pt_ptr \<notin> irq_node_offs_range" "Low_tcb_ptr \<notin> irq_node_offs_range" "High_tcb_ptr \<notin> irq_node_offs_range" "idle_tcb_ptr \<notin> irq_node_offs_range" "init_globals_frame \<notin> irq_node_offs_range" "init_global_pd \<notin> irq_node_offs_range" by(simp add:irq_node_offs_range_def s0_ptr_defs)+ lemma irq_node_offs_distinct[simp]: "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_cnode_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_cnode_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Silc_cnode_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> ntfn_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> irq_cnode_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_pd_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_pd_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_pt_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_pt_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_tcb_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_tcb_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> idle_tcb_ptr" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> init_globals_frame" "init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> init_global_pd" by (simp add:not_inD[symmetric, OF _ irq_node_offs_in_range])+ lemma kh0_dom: "dom kh0 = {init_globals_frame, init_global_pd, idle_tcb_ptr, High_tcb_ptr, Low_tcb_ptr, High_pt_ptr, Low_pt_ptr, High_pd_ptr, Low_pd_ptr, irq_cnode_ptr, ntfn_ptr, Silc_cnode_ptr, High_cnode_ptr, Low_cnode_ptr} \<union> irq_node_offs_range" apply (rule equalityI) apply (simp add: kh0_def dom_def) apply (clarsimp simp: irq_node_offs_in_range) apply (clarsimp simp: dom_def) apply (rule conjI, clarsimp simp: kh0_def)+ apply (force simp: kh0_def cte_level_bits_def dest: irq_node_offs_range_correct) done lemmas kh0_SomeD' = set_mp[OF equalityD1[OF kh0_dom[simplified dom_def]], OF CollectI, simplified, OF exI] lemma kh0_SomeD: "kh0 x = Some y \<Longrightarrow> x = init_globals_frame \<and> y = ArchObj (DataPage False ARMSmallPage) \<or> x = init_global_pd \<and> y = ArchObj (PageDirectory global_pd) \<or> x = idle_tcb_ptr \<and> y = idle_tcb \<or> x = High_tcb_ptr \<and> y = High_tcb \<or> x = Low_tcb_ptr \<and> y = Low_tcb \<or> x = High_pt_ptr \<and> y = High_pt \<or> x = Low_pt_ptr \<and> y = Low_pt \<or> x = High_pd_ptr \<and> y = High_pd \<or> x = Low_pd_ptr \<and> y = Low_pd \<or> x = irq_cnode_ptr \<and> y = irq_cnode \<or> x = ntfn_ptr \<and> y = ntfn \<or> x = Silc_cnode_ptr \<and> y = Silc_cnode \<or> x = High_cnode_ptr \<and> y = High_cnode \<or> x = Low_cnode_ptr \<and> y = Low_cnode \<or> x \<in> irq_node_offs_range \<and> y = CNode 0 (empty_cnode 0)" apply (frule kh0_SomeD') apply (erule disjE, simp add: kh0_def | force simp: kh0_def split: if_split_asm)+ done lemmas kh0_obj_def = Low_cnode_def High_cnode_def Silc_cnode_def ntfn_def irq_cnode_def Low_pd_def High_pd_def Low_pt_def High_pt_def Low_tcb_def High_tcb_def idle_tcb_def definition exst0 :: "det_ext" where "exst0 \<equiv> \<lparr>work_units_completed_internal = undefined, scheduler_action_internal = resume_cur_thread, ekheap_internal = [Low_tcb_ptr \<mapsto> Low_etcb, High_tcb_ptr \<mapsto> High_etcb, idle_tcb_ptr \<mapsto> default_etcb], domain_list_internal = [(0, 10), (1, 10)], domain_index_internal = 0, cur_domain_internal = 0, domain_time_internal = 5, ready_queues_internal = (const (const [])), cdt_list_internal = const []\<rparr>" lemmas ekh0_obj_def = Low_etcb_def High_etcb_def default_etcb_def definition machine_state0 :: "machine_state" where "machine_state0 \<equiv> \<lparr>irq_masks = (\<lambda>irq. if irq = timer_irq then False else True), irq_state = 0, underlying_memory = const 0, device_state = Map.empty, exclusive_state = undefined, machine_state_rest = undefined \<rparr>" definition arch_state0 :: "arch_state" where "arch_state0 \<equiv> \<lparr>arm_asid_table = Map.empty, arm_hwasid_table = Map.empty, arm_next_asid = 0, arm_asid_map = Map.empty, arm_global_pd = init_global_pd, arm_global_pts = [], arm_kernel_vspace = \<lambda>ref. if ref \<in> {kernel_base..kernel_base + mask 20} then ArmVSpaceKernelWindow else ArmVSpaceInvalidRegion\<rparr>" definition s0_internal :: "det_ext state" where "s0_internal \<equiv> \<lparr> kheap = kh0, cdt = Map.empty, is_original_cap = (\<lambda>_. False) ((Low_tcb_ptr, tcb_cnode_index 2) := True, (High_tcb_ptr, tcb_cnode_index 2) := True), cur_thread = Low_tcb_ptr, idle_thread = idle_tcb_ptr, machine_state = machine_state0, interrupt_irq_node = (\<lambda>irq. init_irq_node_ptr + (ucast irq << cte_level_bits)), interrupt_states = (\<lambda>_. irq_state.IRQInactive) (timer_irq := irq_state.IRQTimer), arch_state = arch_state0, exst = exst0 \<rparr>" subsubsection \<open>Defining the policy graph\<close> (* FIXME: should incorporate SharedPage above *) (* There is an NTFN in the High label, a SharedPage in the Low label *) definition Sys1AgentMap :: "(auth_graph_label subject_label) agent_map" where "Sys1AgentMap \<equiv> (\<lambda>p. if ptrFromPAddr shared_page_ptr \<le> p \<and> p < ptrFromPAddr shared_page_ptr + 0x1000 then partition_label Low else partition_label IRQ0) \<comment> \<open>set the range of the shared_page to Low, default everything else to IRQ0\<close> (Low_cnode_ptr := partition_label Low, High_cnode_ptr := partition_label High, ntfn_ptr := partition_label High, irq_cnode_ptr := partition_label IRQ0, Silc_cnode_ptr := SilcLabel, Low_pd_ptr := partition_label Low, High_pd_ptr := partition_label High, Low_pt_ptr := partition_label Low, High_pt_ptr := partition_label High, Low_tcb_ptr := partition_label Low, High_tcb_ptr := partition_label High, idle_tcb_ptr := partition_label Low)" lemma Sys1AgentMap_simps: "Sys1AgentMap Low_cnode_ptr = partition_label Low" "Sys1AgentMap High_cnode_ptr = partition_label High" "Sys1AgentMap ntfn_ptr = partition_label High" "Sys1AgentMap irq_cnode_ptr = partition_label IRQ0" "Sys1AgentMap Silc_cnode_ptr = SilcLabel" "Sys1AgentMap Low_pd_ptr = partition_label Low" "Sys1AgentMap High_pd_ptr = partition_label High" "Sys1AgentMap Low_pt_ptr = partition_label Low" "Sys1AgentMap High_pt_ptr = partition_label High" "Sys1AgentMap Low_tcb_ptr = partition_label Low" "Sys1AgentMap High_tcb_ptr = partition_label High" "Sys1AgentMap idle_tcb_ptr = partition_label Low" "\<And>p. \<lbrakk>ptrFromPAddr shared_page_ptr \<le> p; p < ptrFromPAddr shared_page_ptr + 0x1000\<rbrakk> \<Longrightarrow> Sys1AgentMap p = partition_label Low" unfolding Sys1AgentMap_def apply simp_all by (auto simp: ptrFromPAddr_def physMappingOffset_def kernelBase_addr_def physBase_def s0_ptr_defs) definition Sys1ASIDMap :: "(auth_graph_label subject_label) agent_asid_map" where "Sys1ASIDMap \<equiv> (\<lambda>x. if (asid_high_bits_of x = asid_high_bits_of Low_asid) then partition_label Low else if (asid_high_bits_of x = asid_high_bits_of High_asid) then partition_label High else undefined)" (* We include 2 domains, Low is associated to domain 0, High to domain 1, we default the rest of the possible domains to High *) definition Sys1PAS :: "(auth_graph_label subject_label) PAS" where "Sys1PAS \<equiv> \<lparr> pasObjectAbs = Sys1AgentMap, pasASIDAbs = Sys1ASIDMap, pasIRQAbs = (\<lambda>_. partition_label IRQ0), pasPolicy = Sys1AuthGraph, pasSubject = partition_label Low, pasMayActivate = True, pasMayEditReadyQueues = True, pasMaySendIrqs = False, pasDomainAbs = ((\<lambda>_. {partition_label High})(0 := {partition_label Low})) \<rparr>" subsubsection \<open>Proof of pas_refined for Sys1\<close> lemma High_caps_well_formed: "well_formed_cnode_n 10 High_caps" by (auto simp: High_caps_def well_formed_cnode_n_def split: if_split_asm) lemma Low_caps_well_formed: "well_formed_cnode_n 10 Low_caps" by (auto simp: Low_caps_def well_formed_cnode_n_def split: if_split_asm) lemma Silc_caps_well_formed: "well_formed_cnode_n 10 Silc_caps" by (auto simp: Silc_caps_def well_formed_cnode_n_def split: if_split_asm) lemma s0_caps_of_state : "caps_of_state s0_internal p = Some cap \<Longrightarrow> cap = NullCap \<or> (p,cap) \<in> { ((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 1)), ThreadCap Low_tcb_ptr), ((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)), CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)), ((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))), ((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowSend}), ((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 1)), ThreadCap High_tcb_ptr), ((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)), CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)), ((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))), ((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowRecv}) , ((Silc_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)),CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2)), ((Silc_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowSend}), ((Low_tcb_ptr::obj_ref, (tcb_cnode_index 0)), CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)), ((Low_tcb_ptr::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))), ((Low_tcb_ptr::obj_ref, (tcb_cnode_index 2)), ReplyCap Low_tcb_ptr True {AllowGrant, AllowWrite}), ((Low_tcb_ptr::obj_ref, (tcb_cnode_index 3)), NullCap), ((Low_tcb_ptr::obj_ref, (tcb_cnode_index 4)), NullCap), ((High_tcb_ptr::obj_ref, (tcb_cnode_index 0)), CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)), ((High_tcb_ptr::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))), ((High_tcb_ptr::obj_ref, (tcb_cnode_index 2)), ReplyCap High_tcb_ptr True {AllowGrant, AllowWrite}), ((High_tcb_ptr::obj_ref, (tcb_cnode_index 3)), NullCap), ((High_tcb_ptr::obj_ref, (tcb_cnode_index 4)), NullCap)} " apply (insert High_caps_well_formed) apply (insert Low_caps_well_formed) apply (insert Silc_caps_well_formed) apply (simp add: caps_of_state_cte_wp_at cte_wp_at_cases s0_internal_def kh0_def kh0_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: Silc_caps_def split: if_splits) apply (clarsimp simp: High_caps_def split: if_splits) apply (clarsimp simp: Low_caps_def cte_wp_at_cases split: if_splits) done lemma tcb_states_of_state_s0: "tcb_states_of_state s0_internal = [High_tcb_ptr \<mapsto> thread_state.BlockedOnNotification ntfn_ptr, Low_tcb_ptr \<mapsto> thread_state.Running, idle_tcb_ptr \<mapsto> thread_state.IdleThreadState ]" unfolding s0_internal_def tcb_states_of_state_def apply (rule ext) apply (simp add: get_tcb_def) apply (simp add: kh0_def kh0_obj_def) done lemma thread_bounds_of_state_s0: "thread_bound_ntfns s0_internal = Map.empty" unfolding s0_internal_def thread_bound_ntfns_def apply (rule ext) apply (simp add: get_tcb_def) apply (simp add: kh0_def kh0_obj_def) done lemma Sys1_wellformed': "policy_wellformed (pasPolicy Sys1PAS) False irqs x" apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_simps policy_wellformed_def Sys1AuthGraph_def) done corollary Sys1_wellformed: "x \<in> range (pasObjectAbs Sys1PAS) \<union> \<Union>(range (pasDomainAbs Sys1PAS)) - {SilcLabel} \<Longrightarrow> policy_wellformed (pasPolicy Sys1PAS) False irqs x" by (rule Sys1_wellformed') lemma Sys1_pas_wellformed: "pas_wellformed Sys1PAS" apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_simps policy_wellformed_def Sys1AuthGraph_def) done lemma domains_of_state_s0[simp]: "domains_of_state s0_internal = {(High_tcb_ptr, High_domain), (Low_tcb_ptr, Low_domain), (idle_tcb_ptr, default_domain)}" apply(rule equalityI) apply(rule subsetI) apply clarsimp apply (erule domains_of_state_aux.cases) apply (clarsimp simp: s0_internal_def exst0_def ekh0_obj_def split: if_split_asm) apply clarsimp apply (force simp: s0_internal_def exst0_def ekh0_obj_def intro: domains_of_state_aux.domtcbs)+ done lemma Sys1_pas_refined: "pas_refined Sys1PAS s0_internal" apply (clarsimp simp: pas_refined_def) apply (intro conjI) apply (simp add: Sys1_pas_wellformed) apply (clarsimp simp: irq_map_wellformed_aux_def s0_internal_def Sys1AgentMap_simps Sys1PAS_def) apply (clarsimp simp: Sys1AgentMap_def) apply (clarsimp simp: ptrFromPAddr_def s0_ptr_defs cte_level_bits_def physMappingOffset_def kernelBase_addr_def physBase_def) apply (drule le_less_trans[OF irq_node_offs_min[simplified s0_ptr_defs cte_level_bits_def, simplified]]) apply simp apply (clarsimp simp: tcb_domain_map_wellformed_aux_def Sys1PAS_def Sys1AgentMap_def default_domain_def minBound_word High_domain_def Low_domain_def cte_level_bits_def) apply (clarsimp simp: auth_graph_map_def Sys1PAS_def state_objs_to_policy_def state_bits_to_policy_def) apply (erule state_bits_to_policyp.cases, simp_all, clarsimp) apply (drule s0_caps_of_state, clarsimp) apply (simp add: Sys1AuthGraph_def) apply (elim disjE conjE, auto simp: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def)[1] apply (drule s0_caps_of_state, clarsimp) apply (elim disjE, simp_all)[1] apply (clarsimp simp: state_refs_of_def thread_states_def tcb_states_of_state_s0 Sys1AuthGraph_def Sys1AgentMap_simps split: if_splits) apply (clarsimp simp: state_refs_of_def thread_states_def thread_bounds_of_state_s0) apply (simp add: s0_internal_def) (* this is OK because cdt is empty..*) apply (simp add: s0_internal_def) (* this is OK because cdt is empty..*) apply (clarsimp simp: state_vrefs_def vs_refs_no_global_pts_def s0_internal_def kh0_def Sys1AgentMap_simps kh0_obj_def comp_def Low_pt'_def High_pt'_def pte_ref_def pde_ref2_def Low_pd'_def High_pd'_def Sys1AuthGraph_def ptr_range_def vspace_cap_rights_to_auth_def vm_read_only_def vm_read_write_def dest!: graph_ofD split: if_splits) apply (rule Sys1AgentMap_simps(13)) apply simp apply (drule_tac x=ac in plus_one_helper2) apply (simp add: ptrFromPAddr_def physMappingOffset_def kernelBase_addr_def physBase_def shared_page_ptr_def kernel_base_def) apply (simp add: add.commute) apply (erule notE) apply (rule Sys1AgentMap_simps(13)[symmetric]) apply simp apply (drule_tac x=ac in plus_one_helper2) apply (simp add: ptrFromPAddr_def physMappingOffset_def kernelBase_addr_def physBase_def s0_ptr_defs) apply (simp add: add.commute) apply (rule subsetI, clarsimp) apply (erule state_asids_to_policy_aux.cases) apply clarsimp apply (drule s0_caps_of_state, clarsimp) apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def) apply (elim disjE conjE, simp_all add: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def Low_asid_def High_asid_def asid_low_bits_def asid_high_bits_of_def )[1] apply (clarsimp simp: state_vrefs_def vs_refs_no_global_pts_def s0_internal_def kh0_def Sys1AgentMap_simps kh0_obj_def comp_def Low_pt'_def High_pt'_def pte_ref_def pde_ref2_def Low_pd'_def High_pd'_def Sys1AuthGraph_def ptr_range_def dest!: graph_ofD split: if_splits) apply (clarsimp simp: s0_internal_def arch_state0_def) apply (rule subsetI, clarsimp) apply (erule state_irqs_to_policy_aux.cases) apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def) apply (drule s0_caps_of_state) apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def) apply (elim disjE conjE, simp_all add: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def Low_asid_def High_asid_def asid_low_bits_def asid_high_bits_of_def )[1] done lemma Sys1_pas_cur_domain: "pas_cur_domain Sys1PAS s0_internal" by (simp add: s0_internal_def exst0_def Sys1PAS_def) lemma Sys1_current_subject_idemp: "Sys1PAS\<lparr>pasSubject := the_elem (pasDomainAbs Sys1PAS (cur_domain s0_internal))\<rparr> = Sys1PAS" apply (simp add: Sys1PAS_def s0_internal_def exst0_def) done lemma pasMaySendIrqs_Sys1PAS[simp]: "pasMaySendIrqs Sys1PAS = False" by(auto simp: Sys1PAS_def) lemma Sys1_pas_domains_distinct: "pas_domains_distinct Sys1PAS" apply (clarsimp simp: Sys1PAS_def pas_domains_distinct_def) done lemma Sys1_pas_wellformed_noninterference: "pas_wellformed_noninterference Sys1PAS" apply (simp add: pas_wellformed_noninterference_def) apply (intro conjI ballI allI) apply (blast intro: Sys1_wellformed) apply (clarsimp simp: Sys1PAS_def policy_wellformed_def Sys1AuthGraph_def) apply (rule Sys1_pas_domains_distinct) done lemma silc_inv_s0: "silc_inv Sys1PAS s0_internal s0_internal" apply (clarsimp simp: silc_inv_def) apply (rule conjI, simp add: Sys1PAS_def) apply (rule conjI) apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_def s0_internal_def kh0_def obj_at_def kh0_obj_def is_cap_table_def Silc_caps_well_formed split: if_split_asm) apply (rule conjI) apply (clarsimp simp: Sys1PAS_def Sys1AuthGraph_def) apply (rule conjI) apply clarsimp apply (rule_tac x=Silc_cnode_ptr in exI) apply (rule conjI) apply (rule_tac x="the_nat_to_bl_10 318" in exI) apply (clarsimp simp: slots_holding_overlapping_caps_def2) apply (case_tac "cap = NullCap") apply clarsimp apply (simp add: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def) apply (case_tac a, clarsimp) apply (clarsimp split: if_splits) apply ((clarsimp simp: intra_label_cap_def cte_wp_at_cases tcb_cap_cases_def cap_points_to_label_def split: if_split_asm)+)[8] apply (clarsimp simp: intra_label_cap_def cap_points_to_label_def) apply (drule cte_wp_at_caps_of_state' s0_caps_of_state)+ apply ((erule disjE | clarsimp simp: Sys1PAS_def Sys1AgentMap_simps the_nat_to_bl_def nat_to_bl_def ctes_wp_at_def cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def Silc_caps_well_formed obj_refs_def | simp add: Silc_caps_def)+)[1] apply (simp add: Sys1PAS_def Sys1AgentMap_simps) apply (intro conjI) apply (clarsimp simp: all_children_def s0_internal_def silc_dom_equiv_def equiv_for_refl) apply (clarsimp simp: all_children_def s0_internal_def silc_dom_equiv_def equiv_for_refl) apply (clarsimp simp: Invariants_AI.cte_wp_at_caps_of_state ) by (auto simp:is_transferable.simps dest:s0_caps_of_state) lemma only_timer_irq_s0: "only_timer_irq timer_irq s0_internal" apply (clarsimp simp: only_timer_irq_def s0_internal_def irq_is_recurring_def is_irq_at_def irq_at_def Let_def irq_oracle_def machine_state0_def timer_irq_def) apply presburger done lemma domain_sep_inv_s0: "domain_sep_inv False s0_internal s0_internal" apply (clarsimp simp: domain_sep_inv_def) apply (force dest: cte_wp_at_caps_of_state' s0_caps_of_state | rule conjI allI | clarsimp simp: s0_internal_def)+ done lemma only_timer_irq_inv_s0: "only_timer_irq_inv timer_irq s0_internal s0_internal" by (simp add: only_timer_irq_inv_def only_timer_irq_s0 domain_sep_inv_s0) lemma Sys1_guarded_pas_domain: "guarded_pas_domain Sys1PAS s0_internal" by (clarsimp simp: guarded_pas_domain_def Sys1PAS_def s0_internal_def exst0_def Sys1AgentMap_simps) lemma s0_valid_domain_list: "valid_domain_list s0_internal" by (clarsimp simp: valid_domain_list_2_def s0_internal_def exst0_def) definition "s0 \<equiv> ((if ct_idle s0_internal then idle_context s0_internal else s0_context,s0_internal),KernelExit)" subsubsection \<open>einvs\<close> lemma well_formed_cnode_n_s0_caps[simp]: "well_formed_cnode_n 10 High_caps" "well_formed_cnode_n 10 Low_caps" "well_formed_cnode_n 10 Silc_caps" "\<not> well_formed_cnode_n 10 [[] \<mapsto> NullCap]" apply ((force simp: High_caps_def Low_caps_def Silc_caps_def well_formed_cnode_n_def the_nat_to_bl_def nat_to_bl_def dom_empty_cnode)+)[3] apply (clarsimp simp: well_formed_cnode_n_def) apply (drule eqset_imp_iff[where x="[]"]) apply simp done lemma valid_caps_s0[simp]: "s0_internal \<turnstile> ThreadCap Low_tcb_ptr" "s0_internal \<turnstile> ThreadCap High_tcb_ptr" "s0_internal \<turnstile> CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)" "s0_internal \<turnstile> CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)" "s0_internal \<turnstile> CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2)" "s0_internal \<turnstile> ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))" "s0_internal \<turnstile> ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))" "s0_internal \<turnstile> NotificationCap ntfn_ptr 0 {AllowWrite}" "s0_internal \<turnstile> NotificationCap ntfn_ptr 0 {AllowRead}" "s0_internal \<turnstile> ReplyCap Low_tcb_ptr True {AllowGrant,AllowWrite}" "s0_internal \<turnstile> ReplyCap High_tcb_ptr True {AllowGrant,AllowWrite}" by (simp_all add: valid_cap_def s0_internal_def s0_ptr_defs cap_aligned_def is_aligned_def word_bits_def cte_level_bits_def the_nat_to_bl_def nat_to_bl_def Low_asid_def High_asid_def asid_low_bits_def asid_bits_def obj_at_def kh0_def kh0_obj_def is_tcb_def is_cap_table_def a_type_def is_ntfn_def) lemma valid_obj_s0[simp]: "valid_obj Low_cnode_ptr Low_cnode s0_internal" "valid_obj High_cnode_ptr High_cnode s0_internal" "valid_obj Silc_cnode_ptr Silc_cnode s0_internal" "valid_obj ntfn_ptr ntfn s0_internal" "valid_obj irq_cnode_ptr irq_cnode s0_internal" "valid_obj Low_pd_ptr Low_pd s0_internal" "valid_obj High_pd_ptr High_pd s0_internal" "valid_obj Low_pt_ptr Low_pt s0_internal" "valid_obj High_pt_ptr High_pt s0_internal" "valid_obj Low_tcb_ptr Low_tcb s0_internal" "valid_obj High_tcb_ptr High_tcb s0_internal" "valid_obj idle_tcb_ptr idle_tcb s0_internal" "valid_obj init_global_pd (ArchObj (PageDirectory ((\<lambda>_. InvalidPDE) (ucast (kernel_base >> 20) := SectionPDE (addrFromPPtr kernel_base) {} 0 {})))) s0_internal" "valid_obj init_globals_frame (ArchObj (DataPage False ARMSmallPage)) s0_internal" apply (simp_all add: valid_obj_def kh0_obj_def) apply (simp add: valid_cs_def Low_caps_ran High_caps_ran Silc_caps_ran valid_cs_size_def word_bits_def cte_level_bits_def)+ apply (simp add: valid_ntfn_def obj_at_def s0_internal_def kh0_def High_tcb_def is_tcb_def) apply (simp add: valid_cs_def valid_cs_size_def word_bits_def cte_level_bits_def) apply (simp add: well_formed_cnode_n_def) apply (fastforce simp: Low_pd'_def High_pd'_def Low_pt'_def High_pt'_def Low_pt_ptr_def High_pt_ptr_def shared_page_ptr_def valid_vm_rights_def vm_kernel_only_def kernel_base_def pageBits_def pt_bits_def vmsz_aligned_def is_aligned_def[THEN meta_eq_to_obj_eq, THEN iffD2] is_aligned_addrFromPPtr_n)+ apply (clarsimp simp: valid_tcb_def tcb_cap_cases_def is_master_reply_cap_def valid_ipc_buffer_cap_def valid_tcb_state_def valid_arch_tcb_def | simp add: obj_at_def s0_internal_def kh0_def kh0_obj_def is_ntfn_def is_valid_vtable_root_def)+ apply (simp add: valid_vm_rights_def vm_kernel_only_def kernel_base_def pageBits_def vmsz_aligned_def is_aligned_def[THEN meta_eq_to_obj_eq, THEN iffD2] is_aligned_addrFromPPtr_n) done lemma valid_objs_s0: "valid_objs s0_internal" apply (clarsimp simp: valid_objs_def) apply (subst(asm) s0_internal_def kh0_def)+ apply (simp split: if_split_asm) apply force+ apply (clarsimp simp: valid_obj_def valid_cs_def empty_cnode_def valid_cs_size_def ran_def cte_level_bits_def word_bits_def well_formed_cnode_n_def dom_def) done lemma pspace_aligned_s0: "pspace_aligned s0_internal" apply (clarsimp simp: pspace_aligned_def s0_internal_def) apply (drule kh0_SomeD) apply (erule disjE | (subst is_aligned_def, fastforce simp: s0_ptr_defs cte_level_bits_def kh0_def kh0_obj_def))+ apply (clarsimp simp: cte_level_bits_def) apply (drule irq_node_offs_range_correct) apply (clarsimp simp: s0_ptr_defs cte_level_bits_def) apply (rule is_aligned_add[OF _ is_aligned_shift]) apply (simp add: is_aligned_def s0_ptr_defs cte_level_bits_def) done lemma pspace_distinct_s0: "pspace_distinct s0_internal" apply (clarsimp simp: pspace_distinct_def s0_internal_def) apply (drule kh0_SomeD)+ apply (case_tac "x \<in> irq_node_offs_range \<and> y \<in> irq_node_offs_range") apply clarsimp apply (drule irq_node_offs_range_correct)+ apply clarsimp apply (clarsimp simp: s0_ptr_defs cte_level_bits_def) apply (case_tac "(ucast irq << 4) < (ucast irqa << 4)") apply (frule udvd_decr'[where K="0x10::32 word" and ua=0, simplified]) apply (simp add: shiftl_t2n uint_word_ariths) apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified]) apply simp apply (simp add: shiftl_t2n uint_word_ariths) apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified]) apply simp apply (frule_tac y="ucast irq << 4" in word_plus_mono_right[where x="0xE000800F"]) apply (simp add: shiftl_t2n) apply (case_tac "(1::32 word) \<le> ucast irqa") apply (drule_tac i=1 and k="0x10" in word_mult_le_mono1) apply simp apply (cut_tac x=irqa and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: mult.commute) apply (drule_tac y="0x10" and x="0xE0007FFF" in word_plus_mono_right) apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def) apply (cut_tac x=irqa and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply (simp add: lt1_neq0) apply (drule(1) order_trans_rules(23)) apply clarsimp apply (drule_tac a="0xE0008000 + (ucast irqa << 4)" and b="ucast irqa << 4" and c="0xE0007FFF + (ucast irqa << 4)" and d="ucast irqa << 4" in word_sub_mono) apply simp apply simp apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def shiftl_t2n) apply (cut_tac x=irqa and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def shiftl_t2n) apply (cut_tac x=irqa and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply (case_tac "(ucast irq << 4) > (ucast irqa << 4)") apply (frule udvd_decr'[where K="0x10::32 word" and ua=0, simplified]) apply (simp add: shiftl_t2n uint_word_ariths) apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified]) apply simp apply (simp add: shiftl_t2n uint_word_ariths) apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified]) apply simp apply (frule_tac y="ucast irqa << 4" in word_plus_mono_right[where x="0xE000800F"]) apply (simp add: shiftl_t2n) apply (case_tac "(1::32 word) \<le> ucast irq") apply (drule_tac i=1 and k="0x10" in word_mult_le_mono1) apply simp apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: mult.commute) apply (drule_tac y="0x10" and x="0xE0007FFF" in word_plus_mono_right) apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def) apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply (simp add: lt1_neq0) apply (drule(1) order_trans_rules(23)) apply clarsimp apply (drule_tac a="0xE0008000 + (ucast irq << 4)" and b="ucast irq << 4" and c="0xE0007FFF + (ucast irq << 4)" and d="ucast irq << 4" in word_sub_mono) apply simp apply simp apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def shiftl_t2n) apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply (rule_tac sz=28 in machine_word_plus_mono_right_split) apply (simp add: unat_word_ariths mask_def shiftl_t2n) apply (cut_tac x=irq and 'a=32 in ucast_less) apply simp apply (simp add: word_less_nat_alt) apply (simp add: word_bits_def) apply simp apply simp by ((simp | erule disjE | clarsimp simp: kh0_obj_def cte_level_bits_def s0_ptr_defs | clarsimp simp: irq_node_offs_range_def s0_ptr_defs, drule_tac x="0xF" in word_plus_strict_mono_right, simp, simp add: add.commute, drule(1) notE[rotated, OF less_trans, OF _ _ leD, rotated 2] | drule(1) notE[rotated, OF le_less_trans, OF _ _ leD, rotated 2], simp, assumption)+) lemma valid_pspace_s0[simp]: "valid_pspace s0_internal" apply (simp add: valid_pspace_def pspace_distinct_s0 pspace_aligned_s0 valid_objs_s0) apply (rule conjI) apply (clarsimp simp: if_live_then_nonz_cap_def) apply (subst(asm) s0_internal_def) apply (clarsimp simp: live_def hyp_live_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs split: if_split_asm) apply (clarsimp simp: ex_nonz_cap_to_def) apply (rule_tac x="High_cnode_ptr" in exI) apply (rule_tac x="the_nat_to_bl_10 1" in exI) apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def High_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode) apply (clarsimp simp: ex_nonz_cap_to_def) apply (rule_tac x="Low_cnode_ptr" in exI) apply (rule_tac x="the_nat_to_bl_10 1" in exI) apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def Low_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode) apply (clarsimp simp: ex_nonz_cap_to_def) apply (rule_tac x="High_cnode_ptr" in exI) apply (rule_tac x="the_nat_to_bl_10 318" in exI) apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def High_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode) apply (rule conjI) apply (simp add: Invariants_AI.cte_wp_at_caps_of_state zombies_final_def) apply (force dest: s0_caps_of_state simp: is_zombie_def) apply (rule conjI) apply (clarsimp simp: sym_refs_def state_refs_of_def state_hyp_refs_of_def s0_internal_def) apply (subst(asm) kh0_def) apply (clarsimp split: if_split_asm) apply (simp add: refs_of_def kh0_def s0_ptr_defs kh0_obj_def)+ apply (clarsimp simp: sym_refs_def state_hyp_refs_of_def s0_internal_def) apply (subst(asm) kh0_def) apply (clarsimp split: if_split_asm) by (simp add: refs_of_def kh0_def s0_ptr_defs kh0_obj_def)+ lemma descendants_s0[simp]: "descendants_of (a, b) (cdt s0_internal) = {}" apply (rule set_eqI) apply clarsimp apply (drule descendants_of_NoneD[rotated]) apply (simp add: s0_internal_def)+ done lemma valid_mdb_s0[simp]: "valid_mdb s0_internal" apply (simp add: valid_mdb_def reply_mdb_def) apply (intro conjI) apply (clarsimp simp: mdb_cte_at_def s0_internal_def) apply (force dest: s0_caps_of_state simp: untyped_mdb_def) apply (clarsimp simp: descendants_inc_def) apply (clarsimp simp: no_mloop_def s0_internal_def cdt_parent_defs) apply (clarsimp simp: untyped_inc_def) apply (drule s0_caps_of_state)+ apply ((simp | erule disjE)+)[1] apply (force dest: s0_caps_of_state simp: ut_revocable_def) apply (force dest: s0_caps_of_state simp: irq_revocable_def) apply (clarsimp simp: reply_master_revocable_def) apply (drule s0_caps_of_state) apply ((simp add: is_master_reply_cap_def s0_internal_def s0_ptr_defs | erule disjE)+)[1] apply (force dest: s0_caps_of_state simp: reply_caps_mdb_def) apply (clarsimp simp: reply_masters_mdb_def) apply (simp add: s0_internal_def) done lemma valid_ioc_s0[simp]: "valid_ioc s0_internal" by (clarsimp simp: cte_wp_at_cases tcb_cap_cases_def valid_ioc_def s0_internal_def kh0_def kh0_obj_def split: if_split_asm)+ lemma valid_idle_s0[simp]: "valid_idle s0_internal" apply (clarsimp simp: valid_idle_def st_tcb_at_tcb_states_of_state_eq thread_bounds_of_state_s0 identity_eq[symmetric] tcb_states_of_state_s0 valid_arch_idle_def) by (simp add: s0_ptr_defs s0_internal_def idle_thread_ptr_def pred_tcb_at_def obj_at_def kh0_def idle_tcb_def) lemma only_idle_s0[simp]: "only_idle s0_internal" apply (clarsimp simp: only_idle_def st_tcb_at_tcb_states_of_state_eq identity_eq[symmetric] tcb_states_of_state_s0) apply (simp add: s0_ptr_defs s0_internal_def) done lemma if_unsafe_then_cap_s0[simp]: "if_unsafe_then_cap s0_internal" apply (clarsimp simp: if_unsafe_then_cap_def ex_cte_cap_wp_to_def) apply (drule s0_caps_of_state) apply (case_tac "a=Low_cnode_ptr") apply (rule_tac x=Low_tcb_ptr in exI, rule_tac x="tcb_cnode_index 0" in exI) apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def Low_caps_def | erule disjE)+)[1] apply (case_tac "a=High_cnode_ptr") apply (rule_tac x=High_tcb_ptr in exI, rule_tac x="tcb_cnode_index 0" in exI) apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def High_caps_def | erule disjE)+)[1] apply (case_tac "a=Low_tcb_ptr") apply (rule_tac x=Low_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 1" in exI) apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def Low_caps_def well_formed_cnode_n_def dom_empty_cnode | erule disjE | force)+)[1] apply (case_tac "a=High_tcb_ptr") apply (rule_tac x=High_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 1" in exI) apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def High_caps_def well_formed_cnode_n_def dom_empty_cnode | erule disjE | force)+)[1] apply (rule_tac x=Silc_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 2" in exI) apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def Silc_caps_def well_formed_cnode_n_def dom_empty_cnode | erule disjE | force)+)[1] done lemma valid_reply_caps_s0[simp]: "valid_reply_caps s0_internal" apply (clarsimp simp: valid_reply_caps_def) apply (rule conjI) apply (force dest: s0_caps_of_state simp: Invariants_AI.cte_wp_at_caps_of_state has_reply_cap_def is_reply_cap_to_def) apply (clarsimp simp: unique_reply_caps_def) apply (drule s0_caps_of_state)+ apply (erule disjE | simp add: is_reply_cap_def)+ done lemma valid_reply_masters_s0[simp]: "valid_reply_masters s0_internal" apply (clarsimp simp: valid_reply_masters_def) apply (force dest: s0_caps_of_state simp: Invariants_AI.cte_wp_at_caps_of_state is_master_reply_cap_to_def) done lemma valid_global_refs_s0[simp]: "valid_global_refs s0_internal" apply (clarsimp simp: valid_global_refs_def valid_refs_def) apply (simp add: Invariants_AI.cte_wp_at_caps_of_state) apply clarsimp apply (drule s0_caps_of_state) apply (clarsimp simp: global_refs_def s0_internal_def arch_state0_def) apply (erule disjE | simp add: cap_range_def | clarsimp simp: irq_node_offs_distinct[symmetric] | simp only: s0_ptr_defs, force)+ done lemma valid_arch_state_s0[simp]: "valid_arch_state s0_internal" apply (clarsimp simp: valid_arch_state_def s0_internal_def arch_state0_def) apply (intro conjI) apply (clarsimp simp: obj_at_def kh0_def) apply (simp add: valid_asid_table_def) apply (clarsimp simp: obj_at_def kh0_def a_type_def) apply (simp add: valid_global_pts_def) apply (simp add: is_inv_def) done lemma valid_irq_node_s0[simp]: "valid_irq_node s0_internal" apply (clarsimp simp: valid_irq_node_def) apply (rule conjI) apply (simp add: s0_internal_def) apply (rule injI) apply simp apply (rule ccontr) apply (rule_tac bnd="0x400" and 'a=32 in shift_distinct_helper[rotated 3]) apply assumption apply (simp add: cte_level_bits_def) apply (simp add: cte_level_bits_def) apply (rule ucast_less[where 'b=10, simplified]) apply simp apply (rule ucast_less[where 'b=10, simplified]) apply simp apply (rule notI) apply (drule ucast_up_inj) apply simp apply simp apply (clarsimp simp: obj_at_def s0_internal_def) apply (force simp: kh0_def is_cap_table_def well_formed_cnode_n_def dom_empty_cnode) done lemma valid_irq_handlers_s0[simp]: "valid_irq_handlers s0_internal" apply (clarsimp simp: valid_irq_handlers_def ran_def) apply (force dest: s0_caps_of_state) done lemma valid_irq_state_s0[simp]: "valid_irq_states s0_internal" apply (clarsimp simp: valid_irq_states_def valid_irq_masks_def s0_internal_def machine_state0_def) done lemma valid_machine_state_s0[simp]: "valid_machine_state s0_internal" apply (clarsimp simp: valid_machine_state_def s0_internal_def machine_state0_def in_user_frame_def obj_at_def const_def) done lemma valid_arch_objs_s0[simp]: "valid_vspace_objs s0_internal" apply (clarsimp simp: valid_vspace_objs_def obj_at_def s0_internal_def) apply (drule kh0_SomeD) apply (erule disjE | clarsimp simp: pageBits_def addrFromPPtr_def physMappingOffset_def kernelBase_addr_def physBase_def is_aligned_def obj_at_def kh0_def kh0_obj_def kernel_mapping_slots_def High_pt'_def Low_pt'_def High_pd'_def Low_pd'_def ptrFromPAddr_def | erule vs_lookupE, force simp: vs_lookup_def arch_state0_def vs_asid_refs_def)+ done lemma valid_arch_caps_s0[simp]: "valid_arch_caps s0_internal" apply (clarsimp simp: valid_arch_caps_def) apply (intro conjI) apply (clarsimp simp: valid_vs_lookup_def vs_lookup_pages_def vs_asid_refs_def s0_internal_def arch_state0_def) apply (clarsimp simp: valid_table_caps_def is_pd_cap_def is_pt_cap_def) apply (drule s0_caps_of_state) apply (erule disjE | simp)+ apply (clarsimp simp: unique_table_caps_def is_pd_cap_def is_pt_cap_def) apply (drule s0_caps_of_state)+ apply (erule disjE | simp)+ apply (clarsimp simp: unique_table_refs_def table_cap_ref_def) apply (drule s0_caps_of_state)+ by auto lemma valid_global_objs_s0[simp]: "valid_global_objs s0_internal" apply (clarsimp simp: valid_global_objs_def s0_internal_def arch_state0_def) by (force simp: valid_vso_at_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs addrFromPPtr_def physMappingOffset_def kernelBase_addr_def physBase_def is_aligned_def pageBits_def kernel_mapping_slots_def empty_table_def pde_ref_def valid_pde_mappings_def)+ lemma valid_kernel_mappings_s0[simp]: "valid_kernel_mappings s0_internal" apply (clarsimp simp: valid_kernel_mappings_def s0_internal_def ran_def valid_kernel_mappings_if_pd_def split: kernel_object.splits arch_kernel_obj.splits) apply (drule kh0_SomeD) apply (clarsimp simp: arch_state0_def kernel_mapping_slots_def) apply (erule disjE | simp add: pde_ref_def s0_ptr_defs kh0_obj_def High_pd'_def Low_pd'_def split: if_split_asm pde.splits)+ done lemma equal_kernel_mappings_s0[simp]: "equal_kernel_mappings s0_internal" apply (clarsimp simp: equal_kernel_mappings_def obj_at_def s0_internal_def) apply (drule kh0_SomeD)+ by (erule disjE | force simp: kh0_obj_def High_pd'_def Low_pd'_def s0_ptr_defs kernel_mapping_slots_def addrFromPPtr_def physMappingOffset_def kernelBase_addr_def physBase_def)+ lemma valid_asid_map_s0[simp]: "valid_asid_map s0_internal" apply (clarsimp simp: valid_asid_map_def s0_internal_def arch_state0_def) done lemma valid_global_pd_mappings_s0[simp]: "valid_global_vspace_mappings s0_internal" apply (clarsimp simp: valid_global_vspace_mappings_def s0_internal_def arch_state0_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs valid_pd_kernel_mappings_def valid_pde_kernel_mappings_def pde_mapping_bits_def mask_def) apply (rule conjI) apply force apply clarsimp apply (subgoal_tac "xa - 0xFFFFF \<le> ucast x << 20") apply (case_tac "ucast x << 20 > (0xE0000000::32 word)") apply (subgoal_tac "(0xE0100000::32 word) \<le> ucast x << 20") apply ((drule(1) order_trans_rules(23))+, force) apply (simp add: shiftl_t2n) apply (cut_tac p="0xE0000000::32 word" and n=20 and m=20 and q="0x100000 * ucast x" in word_plus_power_2_offset_le) apply (simp add: is_aligned_def) apply (simp add: is_aligned_def unat_word_ariths) apply (subst mod_mult_mult1[where c="2^20" and b="2^12", simplified]) apply simp apply simp apply simp apply simp apply simp apply (case_tac "ucast x << 20 < (0xE0000000::32 word)") apply (subgoal_tac "(0xE0000000::32 word) - 0x100000 \<ge> ucast x << 20") apply (subgoal_tac "0xFFFFF + (ucast x << 20) \<le> 0xDFFFFFFF") apply (drule_tac y="0xFFFFF + (ucast x << 20)" and z="0xDFFFFFFF::32 word" in order_trans_rules(23)) apply simp apply ((drule(1) order_trans_rules(23))+, force) apply (simp add: add.commute word_plus_mono_left[where x="0xFFFFF" and z="0xDFF00000", simplified]) apply (simp add: shiftl_t2n) apply (rule udvd_decr'[where K="0x100000" and q="0xE0000000" and ua=0, simplified]) apply simp apply (simp add: uint_word_ariths) apply (subst mod_mult_mult1[where c="2^20" and b="2^12", simplified]) apply simp apply simp apply simp apply (erule notE) apply (cut_tac x="ucast x::32 word" and n=20 in shiftl_shiftr_id) apply simp apply (simp add: ucast_less[where 'b=12, simplified]) apply simp apply (rule ucast_up_inj[where 'b=32]) apply simp apply simp apply (drule_tac c="0xFFFFF + (ucast x << 20)" and d="0xFFFFF" and b="0xFFFFF" in word_sub_mono) apply simp apply (rule word_sub_le) apply (rule order_trans_rules(23)[rotated], assumption) apply simp apply (simp add: add.commute) apply (rule no_plus_overflow_neg) apply simp apply (drule_tac x="ucast x << 20" in order_trans_rules(23), assumption) apply (simp add: le_less_trans) apply simp done lemma pspace_in_kernel_window_s0[simp]: "pspace_in_kernel_window s0_internal" apply (clarsimp simp: pspace_in_kernel_window_def s0_internal_def) apply (drule kh0_SomeD) apply (erule disjE | simp add: arch_state0_def kh0_obj_def s0_ptr_defs mask_def irq_node_offs_range_def cte_level_bits_def | rule conjI | rule order_trans_rules(23)[rotated] order_trans_rules(23), force, force)+ apply (force intro: order_trans_rules(23)[rotated]) apply clarsimp apply (drule_tac x=y in le_less_trans) apply (rule neq_le_trans[rotated]) apply (rule word_plus_mono_right) apply (rule less_imp_le) apply simp+ apply (force intro: less_imp_le less_le_trans) done lemma cap_refs_in_kernel_window_s0[simp]: "cap_refs_in_kernel_window s0_internal" apply (clarsimp simp: cap_refs_in_kernel_window_def valid_refs_def cap_range_def Invariants_AI.cte_wp_at_caps_of_state) apply (drule s0_caps_of_state) apply (erule disjE | simp add: arch_state0_def s0_internal_def s0_ptr_defs mask_def)+ done lemma cur_tcb_s0[simp]: "cur_tcb s0_internal" by (simp add: cur_tcb_def s0_ptr_defs s0_internal_def kh0_def kh0_obj_def obj_at_def is_tcb_def) lemma valid_list_s0[simp]: "valid_list s0_internal" apply (simp add: valid_list_2_def s0_internal_def exst0_def const_def) done lemma valid_sched_s0[simp]: "valid_sched s0_internal" apply (simp add: valid_sched_def s0_internal_def exst0_def) apply (intro conjI) apply (clarsimp simp: valid_etcbs_def s0_ptr_defs kh0_def kh0_obj_def is_etcb_at'_def st_tcb_at_kh_def obj_at_kh_def obj_at_def) apply (clarsimp simp: const_def) apply (clarsimp simp: const_def) apply (clarsimp simp: valid_sched_action_def is_activatable_def st_tcb_at_kh_def obj_at_kh_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs) apply (clarsimp simp: ct_in_cur_domain_def in_cur_domain_def etcb_at'_def ekh0_obj_def s0_ptr_defs) apply (clarsimp simp: const_def valid_blocked_def st_tcb_at_kh_def obj_at_kh_def obj_at_def kh0_def kh0_obj_def split: if_split_asm) apply (clarsimp simp: valid_idle_etcb_def etcb_at'_def ekh0_obj_def s0_ptr_defs idle_thread_ptr_def) done lemma respects_device_trivial: "pspace_respects_device_region s0_internal" "cap_refs_respects_device_region s0_internal" apply (clarsimp simp: s0_internal_def pspace_respects_device_region_def machine_state0_def device_mem_def in_device_frame_def kh0_obj_def obj_at_kh_def obj_at_def kh0_def split: if_splits)[1] apply fastforce apply (clarsimp simp: cap_refs_respects_device_region_def Invariants_AI.cte_wp_at_caps_of_state cap_range_respects_device_region_def machine_state0_def) apply (intro conjI impI) apply (drule s0_caps_of_state) apply fastforce apply (clarsimp simp: s0_internal_def machine_state0_def) done lemma einvs_s0: "einvs s0_internal" apply (simp add: valid_state_def invs_def respects_device_trivial) done lemma obj_valid_pdpt_kh0: "x \<in> ran kh0 \<Longrightarrow> obj_valid_pdpt x" by (auto simp: kh0_def valid_entries_def obj_valid_pdpt_def idle_tcb_def High_tcb_def Low_tcb_def High_pt_def High_pt'_def entries_align_def Low_pt_def High_pd_def Low_pt'_def High_pd'_def Low_pd_def irq_cnode_def ntfn_def Silc_cnode_def High_cnode_def Low_cnode_def Low_pd'_def) subsubsection \<open>Haskell state\<close> text \<open>One invariant we need on s0 is that there exists an associated Haskell state satisfying the invariants. This does not yet exist.\<close> lemma Sys1_valid_initial_state_noenabled: assumes extras_s0: "step_restrict s0" assumes utf_det: "\<forall>pl pr pxn tc um ds es s. det_inv InUserMode tc s \<and> einvs s \<and> context_matches_state pl pr pxn um ds es s \<and> ct_running s \<longrightarrow> (\<exists>x. utf (cur_thread s) pl pr pxn (tc, um, ds, es) = {x})" assumes utf_non_empty: "\<forall>t pl pr pxn tc um ds es. utf t pl pr pxn (tc, um, ds, es) \<noteq> {}" assumes utf_non_interrupt: "\<forall>t pl pr pxn tc um ds es e f g. (e,f,g) \<in> utf t pl pr pxn (tc, um, ds, es) \<longrightarrow> e \<noteq> Some Interrupt" assumes det_inv_invariant: "invariant_over_ADT_if det_inv utf" assumes det_inv_s0: "det_inv KernelExit (cur_context s0_internal) s0_internal" shows "valid_initial_state_noenabled det_inv utf s0_internal Sys1PAS timer_irq s0_context" apply (unfold_locales, simp_all only: pasMaySendIrqs_Sys1PAS) apply (insert det_inv_invariant)[9] apply (erule(2) invariant_over_ADT_if.det_inv_abs_state) apply ((erule invariant_over_ADT_if.det_inv_abs_state invariant_over_ADT_if.check_active_irq_if_Idle_det_inv invariant_over_ADT_if.check_active_irq_if_User_det_inv invariant_over_ADT_if.do_user_op_if_det_inv invariant_over_ADT_if.handle_preemption_if_det_inv invariant_over_ADT_if.kernel_entry_if_Interrupt_det_inv invariant_over_ADT_if.kernel_entry_if_det_inv invariant_over_ADT_if.kernel_exit_if_det_inv invariant_over_ADT_if.schedule_if_det_inv)+)[8] apply (rule Sys1_pas_cur_domain) apply (rule Sys1_pas_wellformed_noninterference) apply (simp only: einvs_s0) apply (simp add: Sys1_current_subject_idemp) apply (simp add: only_timer_irq_inv_s0 silc_inv_s0 Sys1_pas_cur_domain domain_sep_inv_s0 Sys1_pas_refined Sys1_guarded_pas_domain idle_equiv_refl) apply (clarsimp simp: obj_valid_pdpt_kh0 valid_domain_list_2_def s0_internal_def exst0_def) apply (simp add: det_inv_s0) apply (simp add: s0_internal_def exst0_def) apply (simp add: ct_in_state_def st_tcb_at_tcb_states_of_state_eq identity_eq[symmetric] tcb_states_of_state_s0) apply (simp add: s0_ptr_defs s0_internal_def) apply (simp add: s0_internal_def exst0_def) apply (simp add: num_domains_def) apply (rule utf_det) apply (rule utf_non_empty) apply (rule utf_non_interrupt) apply (simp add: extras_s0[simplified s0_def]) done text \<open>the extra assumptions in valid_initial_state of being enabled, and a serial system, follow from ADT_IF_Refine\<close> end end
#redirect Repro Graphics
[STATEMENT] lemma dickson_less_pD2: assumes "dickson_less_p d m p q" shows "q \<in> dgrad_p_set d m" [PROOF STATE] proof (prove) goal (1 subgoal): 1. q \<in> dgrad_p_set d m [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: dickson_less_p d m p q goal (1 subgoal): 1. q \<in> dgrad_p_set d m [PROOF STEP] by (simp add: dickson_less_p_def)
import tactic.cache meta def assert_frozen_instances : tactic unit := do frozen ← tactic.frozen_local_instances, when frozen.is_none $ tactic.fail "instances are not frozen" example (α) (a : α) := begin haveI h : inhabited α := ⟨a⟩, assert_frozen_instances, exact (default : α) end example (α) (a : α) := begin haveI h := inhabited.mk a, assert_frozen_instances, exact (default : α) end example (α) (a : α) := begin letI h : inhabited α := ⟨a⟩, assert_frozen_instances, exact (default : α) end example (α) (a : α) := begin letI h : inhabited α, all_goals { assert_frozen_instances }, exact ⟨a⟩, exact (default : α) end example (α) (a : α) := begin letI h := inhabited.mk a, exact (default : α) end example (α) : inhabited α → α := by intro a; exactI default example (α) : inhabited α → α := begin introsI a, assert_frozen_instances, exact default end example (α β) (h : α = β) [inhabited α] : β := begin substI h, assert_frozen_instances, exact default end example (α β) (h : α = β) [inhabited α] : β := begin unfreezingI { cases _inst_1 }, assert_frozen_instances, subst h, assumption end example (α β) (h : α = β) [inhabited α] : β := begin casesI _inst_1, assert_frozen_instances, subst h, assumption end
""" Модуль содержаший базовые апроксиматоры """ from warnings import warn import numpy as np import scipy.fftpack import scipy.optimize from ..utils import round_to_n, format_monoid class Approximator: """ Базовый класс апроксиматор. Классы нужны, чтобы сохранять разные данные, во время аппроксимации. Например коэффициенты, ошибки. Возможно когда-нибудь будет сделан класс для результата аппроксимации Для некоторых позволяют генерировать формулу в латехе """ def __init__(self, points=100, left_offset=5, right_offset=5): """ :param points: количество точек, которые будут на выходе :param left_offset: отступ от левой гриницы диапозона :param right_offset: отступ от правой гриницы диапозона """ self.left_offset = left_offset / 100 self.right_offset = right_offset / 100 self.points = points self.meta = [] # Данные self._x = np.array([]) self._y = np.array([]) self._xerr = np.array([]) self._yerr = np.array([]) # Коэффициенты апроксимации self.koefs = np.array([]) # Стандартное отклонение параметров self.sigmas = np.array([]) # Наиболее правдоподобная функция self._function = None def __init_subclass__(cls, **kwargs): """ Костыльное добавление документации к классам наследникам """ super().__init_subclass__(**kwargs) if not cls.__init__.__doc__: return if not cls.__doc__: cls.__doc__ = cls.__init__.__doc__ return # для совместимости со старыми питонами def remove_pref(s: str, pref: str): if s.startswith(pref): return s[len(pref):] return s cls.__doc__ = '{}\n{}'.format( cls.__doc__, '\n'.join( [ remove_pref(remove_pref(line, '\t'), ' ' * 4) for line in cls.__init__.__doc__.split('\n') ] ) ) def _gen_x_axis_with_offset(self, start, end): """ Генерирует набор точек по оси абсцисс в заданом диапозоне с учетом отступов. Функция нужна для внутрених нужд :param start: начало диапозона :param end: конец диапозона :return: """ delta = end - start return np.linspace(start - delta * self.left_offset, end + delta * self.right_offset, self.points) def gen_x_axis(self, start, end): """ Генерирует набор точек по оси абсцисс в заданом диапозоне :param start: начало диапозона :param end: конец диапозона :return: """ return np.linspace(start, end, self.points) def _prepare_before_approximation(self, x, y, xerr, yerr): xerr = np.ones_like(x) * xerr if not isinstance(yerr, np.ndarray): yerr = np.ones_like(y) * yerr self._x = np.array(x) self._y = np.array(y) self._xerr = xerr self._yerr = yerr return self._x, self._y, self._xerr, self._yerr def approximate(self, x, y, xerr=0, yerr=0): """ Функция апроксимации :param x: набор параметров оси x :param y: набор параметров оси y :param xerr: погрешность параметров оси x :param yerr: погрешность параметров оси y :return: набор точек на кривой апроксимации """ self._x = np.array(x) self._y = np.array(y) self._xerr = xerr self._yerr = yerr return x, y def get_function(self): """Возвращает полученную после аппроксимации функцию""" return self._function def label(self, xvar='x', yvar='y'): """ Генерирует формулу для латеха :param xvar: буква перемонной по оси x :param yvar: буква перемонной по оси y :return: сгенерированная формулу """ return f'[{self.__class__.__name__}] function with params: {self.meta}' def calc_hi_square(self): """ Вычисляет chi^2 """ if not self._yerr.all(): return None return np.sum(np.square((self._y - self.get_function()(self._x)) / self._yerr)) def calc_quality_of_approximation(self): """ Вычисляет chi^2 / (n - p) - n - количество точек в данных - p - количество степеней свободы (кол-во параметров в функции, которой аппроксимируем) """ if not self._yerr.all(): return None return self.calc_hi_square() / (len(self._x) - len(self.koefs)) def is_approximation_good(self): """ Делает оценочное суждение по поводу качества измерений quality_of_approximation = calc_quality_of_approximation = chi^2 / (n - p) - 0 < quality_of_approximation <= 0.5: Качество ваших измерений составляется quality_of_approximation <= 0.5. Это слишком мало, скорее всего это свидетельствуют о завышенных погрешностях - 0.5 < quality_of_approximation < 2: Качество ваших измерений составляется quality_of_approximation ~ 1. Это хороший результат. Ваша теоретическая модель хорошо сходится с экспериментом. - 2 <= quality_of_approximation: Качество ваших измерений составляется quality_of_approximation >= 2. Это слишком много. Это свидетельствуют либо о плохом соответствии теории и результатов измерений, либо о заниженных погрешностях. """ if not self._yerr.all(): return 'У ваших измерений по вертикальной оси нет погрешности, ' \ 'поэтому невозможно пользоваться методом хи-квадрат' if len(self._x) - len(self.koefs) <= 0: return 'Слишком мало точек для аппроксимации, воспользуйтесь интерполяцией' quality_of_approximation = self.calc_quality_of_approximation() if 0 < quality_of_approximation <= 0.5: return f'Качество ваших измерений составляется {round(quality_of_approximation, 2)} <= 0.5.\n' \ f'Это слишком мало, скорее всего это свидетельствуют о завышенных погрешностях.' if 0.5 < quality_of_approximation < 2: return f'Качество ваших измерений составляется {round(quality_of_approximation, 2)} ~ 1.\n' \ f'Это хороший результат. Ваша теоретическая модель хорошо сходится с экспериментом.' if 2 <= quality_of_approximation: return f'Качество ваших измерений составляется {round(quality_of_approximation, 2)} >= 2.\n' \ f'Это слишком много. Это свидетельствуют либо о плохом соответствии \n' \ f'теории и результатов измерений, либо о заниженных погрешностях.' class MultiLinearMixin: """ Добавляет возможность получить функции, которая считает значения между двумя точками на прямой в результирующей аппроксимации Полезно для аппроксиматоров, которые только двигают точки, например Lowess """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._res_x = None self._res_y = None def get_function(self): def scalar_func(x): # При выходе за область определения возбуждаем исключение if x < np.min(self._x) or x > np.max(self._x): raise AttributeError( f'Значение x={x} выходит за область определения [{np.min(self._x)}, {np.max(self._x)}]') # Если есть значение в точке idx = np.where(np.isclose(self._x, x))[0] if len(idx) != 0: return self._res_y[idx[0]] # Ищем значение на прямой между двумя ближайшими по оси x точками upper_bound = np.where(self._x > x)[0][0] # lower_bound = np.where(self._x < x)[0][-1] lower_bound = upper_bound - 1 x1 = self._res_x[lower_bound] x2 = self._res_x[upper_bound] y1 = self._res_y[lower_bound] y2 = self._res_y[upper_bound] k = (y2 - y1) / (x2 - x1) return k * x + y1 - k * x1 def vector_func(x): # При выходе за область определения возбуждаем исключение if np.any(x < np.min(self._x)) or np.any(x > np.max(self._x)): raise AttributeError( f'Одна из координат x={x} выходит за область определения [{np.min(self._x)}, {np.max(self._x)}]') return np.array([scalar_func(_x_comp) for _x_comp in x]) def inner(x): if isinstance(x, np.ndarray): return vector_func(x) else: return scalar_func(x) return inner class Polynomial(Approximator): """ Аппроксимация с помощью полинома. Использует numpy.polyfit """ def __init__(self, deg=1, points=100, left_offset=5, right_offset=5): """ :param deg: степень апроскимируещего полинома :param points: количество точек, которые будут на выходе :param left_offset: отступ от левой гриницы диапозона :param right_offset: отступ от правой гриницы диапозона """ super(Polynomial, self).__init__(points, left_offset, right_offset) self.deg = deg def approximate(self, x, y, xerr=0, yerr=0): x, y, xerr, yerr = self._prepare_before_approximation(x, y, xerr, yerr) result = np.polyfit(x, y, deg=self.deg, cov=True) popt = result[0] pcov = result[-1] self.meta = self.meta = { 'popt': popt, 'pcov': pcov } self.koefs = popt self.sigmas = np.sqrt(np.diag(pcov)) self._function = np.poly1d(popt) poly = np.poly1d(popt) xs = self._gen_x_axis_with_offset(min(x), max(x)) return xs, poly(xs) def label(self, xvar='x', yvar='y'): # если степень равна 0, то возвращаем эту константу if self.deg == 0: return f'${yvar} = {format_monoid(self.koefs[0], True)}$' # списисок моноидов monoids = [] # форматируем коэффициент при каждой степени, кроме первой и нулевой for i in range(self.deg - 1): monoid = f'{format_monoid(self.koefs[i])}{xvar}^{{{self.deg - i}}}' monoids.append(monoid) # форматируем коэффициент при первой степени monoids.append(f'{format_monoid(self.koefs[self.deg - 1])}{xvar}') # форматируем коэффициент при нулевой степени monoids.append(f'{format_monoid(self.koefs[self.deg])}') # объединяем в один полином res = ''.join(monoids) # убираем плюс при максимальной степени # FIXME неоптимизированный костыль с копирование строк if self.koefs[0] >= 0: res = res[1:] return f"${yvar} = {res}$" class Functional(Approximator): """ Аппроксимация с помощью пользовательской функции. Использует scipy.optimize.curve_fit Функция должна иметь следующую сигнатуру: .. code:: python def function_for_fit(x, param1, param2, ..., paramn): ... x - переменная param1, param2, ..., paramn - параметры, которые будут искаться Например: .. code:: python def exp(x, a, b, c): return a * np.exp(b * x) + c У этой функции будут определяться параметры a, b, c """ def __init__(self, function, points=100, left_offset=5, right_offset=5): """ :param function: функция для аппроксимации :param points: количество точек, которые будут на выходе :param left_offset: отступ от левой границы диапазона :param right_offset: отступ от правой границы диапазона """ super(Functional, self).__init__(points, left_offset, right_offset) self._function_for_fit = function def approximate(self, x, y, xerr=0, yerr=0): x, y, xerr, yerr = self._prepare_before_approximation(x, y, xerr, yerr) # пытаемся аппроксимировать. если у scipy не получается, то оно выбрасывает исключение RuntimeError try: popt, pcov = scipy.optimize.curve_fit( f=self._function_for_fit, xdata=x, ydata=y, sigma=yerr) perr = np.sqrt(np.diag(pcov)) self.meta = { 'popt': popt, 'pcov': pcov } self.koefs = popt self.sigmas = perr def fff(*params): def inner(xx): return self._function_for_fit(xx, *params) return inner self._function = fff(*self.koefs) xs = self._gen_x_axis_with_offset(min(x), max(x)) ys = self._function_for_fit(xs, *self.koefs) return xs, ys except RuntimeError: # Если вызывается исключение, то возвращаем исходные данные warn(f"Точки плохо подходят под апроксимацию выбранной функцией {self._function.__name__}") return x, y def label(self, xvar='x', yvar='y'): try: return f'function with params: {[round_to_n(param, 3) for param in self.koefs]}' except IndexError: return f'Функция {self._function.__name__}, которая плохо подходит'
SUBROUTINE zcatalogfile6 (IFLTAB, CFILE, ISTAT) C C IMPLICIT NONE C INTEGER IFLTAB(*) CHARACTER CFILE*(*) INTEGER ISTAT, j, k C INTEGER IFPOS, NPATH, ICOUNT CHARACTER CPATH*392, CINSTR*1 C OPEN (UNIT=123, FILE=CFILE, ERR=900) C IFPOS = 0 ICOUNT = 0 CINSTR = ' ' CPATH = ' ' 10 CONTINUE CALL zplist6 (IFLTAB, CINSTR, IFPOS, CPATH, NPATH, ISTAT) IF (ISTAT.LT.0) THEN CLOSE (UNIT=123) RETURN ENDIF IF (ISTAT.GT.0) GO TO 100 ICOUNT = ICOUNT + 1 j = icount/5000 k = j *5000 if (k.eq.icount) then write (*,*)'count = ',icount,', path = ',CPATH(1:NPATH) endif WRITE (123, 20) CPATH(1:NPATH) 20 FORMAT (A) GO TO 10 C C 100 CONTINUE CLOSE (UNIT=123) ISTAT = ICOUNT RETURN C 900 CONTINUE ISTAT = -2 RETURN END
% Generate samples from the HHMM with the true params. seed = 1; rand('state', seed); randn('state', seed); discrete_obs = 0; bnet = mk_square_hhmm(discrete_obs, 1); Q1 = 1; Q2 = 2; Q3 = 3; F3 = 4; F2 = 5; Onode = 6; Qnodes = [Q1 Q2 Q3]; Fnodes = [F2 F3]; for seqi=1:1 evidence = sample_dbn(bnet, 'stop_test', 'is_F2_true_D3'); clf plot_square_hhmm(evidence); %pretty_print_hhmm_parse(evidence, Qnodes, Fnodes, Onode, []); fprintf('sequence %d has length %d; press key to continue\n', seqi, size(evidence,2)) pause end
function yourReturns = fName(arguments) %Initialize a new vista function % % fName(arguments) % % % INPUTS % % RETURNS % % Web Resources % % Example: % vistaEditFunction('writeMe'); % % Copyright Stanford team, mrVista, 2011 %% Check inputs
(*<*) theory Slicing imports Abstract_Monitor MFOTL begin (*>*) section \<open>Slicing framework\<close> text \<open>This section formalizes the abstract slicing framework and the joint data slicer presented in the article~\cite[Sections 4.2 and~4.3]{SchneiderBBKT-STTT20}.\<close> subsection \<open>Abstract slicing\<close> subsubsection \<open>Definition 1\<close> text \<open>Corresponds to locale @{locale monitor} defined in theory @{theory MFOTL_Monitor_Devel.Abstract_Monitor}.\<close> subsubsection \<open>Definition 2\<close> locale slicer = monitor _ _ UNIV _ _ + fixes submonitor :: "'k :: finite \<Rightarrow> 'a prefix \<Rightarrow> (nat \<times> 'b option list) set" and splitter :: "'a prefix \<Rightarrow> 'k \<Rightarrow> 'a prefix" and joiner :: "('k \<Rightarrow> (nat \<times> 'b option list) set) \<Rightarrow> (nat \<times> 'b option list) set" assumes mono_splitter: "\<pi> \<le> \<pi>' \<Longrightarrow> splitter \<pi> k \<le> splitter \<pi>' k" and correct_slicer: "joiner (\<lambda>k. submonitor k (splitter \<pi> k)) = M \<pi>" begin lemmas sound_slicer = equalityD1[OF correct_slicer] lemmas complete_slicer = equalityD2[OF correct_slicer] end locale self_slicer = slicer nfv fv sat M "\<lambda>_. M" splitter joiner for nfv fv sat M splitter joiner subsubsection \<open>Definition 3\<close> locale event_separable_splitter = fixes event_splitter :: "'a \<Rightarrow> 'k :: finite set" begin lift_definition splitter :: "'a set prefix \<Rightarrow> 'k \<Rightarrow> 'a set prefix" is "\<lambda>\<pi> k. map (\<lambda>(D, t). ({e \<in> D. k \<in> event_splitter e}, t)) \<pi>" by (auto simp: o_def split_beta) subsubsection \<open>Lemma 1\<close> lemma mono_splitter: "\<pi> \<le> \<pi>' \<Longrightarrow> splitter \<pi> k \<le> splitter \<pi>' k" by transfer auto end subsection \<open>Joint data slicer\<close> abbreviation (input) "ok \<phi> v \<equiv> wf_tuple (MFOTL.nfv \<phi>) (MFOTL.fv \<phi>) v" locale splitting_strategy = fixes \<phi> :: "'a MFOTL.formula" and strategy :: "'a option list \<Rightarrow> 'k :: finite set" assumes strategy_nonempty: "ok \<phi> v \<Longrightarrow> strategy v \<noteq> {}" begin abbreviation slice_set where "slice_set k \<equiv> {v. \<exists>v'. map the v' = v \<and> ok \<phi> v' \<and> k \<in> strategy v'}" end subsubsection \<open>Definition 4\<close> locale MFOTL_monitor = monitor "MFOTL.nfv \<phi>" "MFOTL.fv \<phi>" UNIV "\<lambda>\<sigma> v i. MFOTL.sat \<sigma> v i \<phi>" M for \<phi> M lemma (in MFOTL_monitor) prefixesI[simp, intro]: "\<pi> \<in> prefixes" by (simp add: prefixes_def ex_prefix_of) locale joint_data_slicer = MFOTL_monitor \<phi> M + splitting_strategy \<phi> strategy for \<phi> M strategy begin definition event_splitter where "event_splitter e = (\<Union>(strategy ` {v. ok \<phi> v \<and> MFOTL.matches (map the v) \<phi> e}))" sublocale event_separable_splitter where event_splitter = event_splitter . definition joiner where "joiner = (\<lambda>s. \<Union>k. s k \<inter> (UNIV :: nat set) \<times> {v. k \<in> strategy v})" lemma splitter_pslice: "splitter \<pi> k = MFOTL_slicer.pslice \<phi> (slice_set k) \<pi>" by transfer (auto simp: event_splitter_def) subsubsection \<open>Lemma 2\<close> text \<open>Corresponds to the following theorem @{thm[source] sat_slice_strong} proved in theory @{theory MFOTL_Monitor_Devel.Abstract_Monitor}: @{thm sat_slice_strong[no_vars]}\<close> subsubsection \<open>Theorem 1\<close> sublocale joint_monitor: MFOTL_monitor \<phi> "\<lambda>\<pi>. joiner (\<lambda>k. M (splitter \<pi> k))" proof (unfold_locales, goal_cases mono wf sound complete) case (mono \<pi> \<pi>') show ?case using mono_monitor[OF _ mono_splitter, OF _ mono(2)] by (auto simp: joiner_def) next case (wf \<pi> i v) then obtain k where in_M: "(i, v) \<in> M (splitter \<pi> k)" and k: "k \<in> strategy v" unfolding joiner_def by (auto split: if_splits) then show ?case using wf_monitor[OF _ in_M] by auto next case (sound \<sigma> i v \<pi>) then obtain k where in_M: "(i, v) \<in> M (splitter \<pi> k)" and k: "k \<in> strategy v" unfolding joiner_def by (auto split: if_splits) have wf: "ok \<phi> v" and sat: "\<And>\<sigma>. prefix_of (splitter \<pi> k) \<sigma> \<Longrightarrow> MFOTL.sat \<sigma> (map the v) i \<phi>" using sound_monitor[OF _ in_M] wf_monitor[OF _ in_M] by auto then have "MFOTL.sat \<sigma> (map the v) i \<phi>" if "prefix_of \<pi> \<sigma>" for \<sigma> using that k by (intro iffD2[OF sat_slice_iff[of "map the v" "slice_set k" \<sigma> i \<phi>]]) (auto simp: wf_tuple_def fvi_less_nfv splitter_pslice intro!: exI[of _ v] prefix_of_pmap_\<Gamma>) then show ?case using sound(3) by blast next case (complete \<sigma> \<pi> v i) with strategy_nonempty obtain k where k: "k \<in> strategy v" by blast have "MFOTL.sat \<sigma>' (map the v) i \<phi>" if "prefix_of (MFOTL_slicer.pslice \<phi> (slice_set k) \<pi>) \<sigma>'" for \<sigma>' proof - have "MFOTL.sat \<sigma>' (map the v) i \<phi> = MFOTL.sat (MFOTL_slicer.slice \<phi> (slice_set k) \<sigma>') (map the v) i \<phi>" using complete(3) k by (auto intro!: sat_slice_iff) also have "\<dots> = MFOTL.sat (MFOTL_slicer.slice \<phi> (slice_set k) (replace_prefix \<pi> \<sigma>')) (map the v) i \<phi>" using that complete k by (subst slice_replace_prefix[symmetric]; simp) also have "\<dots> = MFOTL.sat (replace_prefix \<pi> \<sigma>') (map the v) i \<phi>" using complete(3) k by (auto intro!: sat_slice_iff[symmetric]) also have "\<dots>" by (rule complete(4)[OF UNIV_I, rule_format], rule prefix_of_replace_prefix[OF that]) finally show ?thesis . qed with complete(1-3) obtain \<pi>' where \<pi>': "prefix_of \<pi>' (MFOTL_slicer.slice \<phi> (slice_set k) \<sigma>)" "(i, v) \<in> M \<pi>'" by (atomize_elim, intro complete_monitor[where \<pi>="MFOTL_slicer.pslice \<phi> (slice_set k) \<pi>"]) (auto simp: splitter_pslice intro!: prefix_of_pmap_\<Gamma>) from \<pi>'(1) obtain \<pi>'' where "\<pi>' = MFOTL_slicer.pslice \<phi> (slice_set k) \<pi>''" "prefix_of \<pi>'' \<sigma>" by (atomize_elim, rule prefix_of_map_\<Gamma>_D) with \<pi>' k show ?case by (intro exI[of _ \<pi>'']) (auto simp: joiner_def splitter_pslice intro!: exI[of _ k]) qed subsubsection \<open>Corollary 1\<close> sublocale joint_slicer: slicer "MFOTL.nfv \<phi>" "MFOTL.fv \<phi>" "\<lambda>\<sigma> v i. MFOTL.sat \<sigma> v i \<phi>" "\<lambda>\<pi>. joiner (\<lambda>k. M (splitter \<pi> k))" "\<lambda>_. M" splitter joiner by standard (auto simp: mono_splitter) end subsubsection \<open>Definition 5\<close> text \<open>Corresponds to locale @{locale sliceable_monitor} defined in theory @{theory MFOTL_Monitor_Devel.Abstract_Monitor}.\<close> locale slicable_joint_data_slicer = sliceable_monitor "MFOTL.nfv \<phi>" "MFOTL.fv \<phi>" UNIV "relevant_events \<phi>" "\<lambda>\<sigma> v i. MFOTL.sat \<sigma> v i \<phi>" M + joint_data_slicer \<phi> M strategy for \<phi> M strategy begin lemma monitor_split: "ok \<phi> v \<Longrightarrow> k \<in> strategy v \<Longrightarrow> (i, v) \<in> M (splitter \<pi> k) \<longleftrightarrow> (i, v) \<in> M \<pi>" unfolding splitter_pslice by (rule sliceable_M) (auto simp: wf_tuple_def fvi_less_nfv intro!: mem_restrI[rotated 2, where y="map the v"]) subsubsection \<open>Theorem 2\<close> sublocale self_slicer "MFOTL.nfv \<phi>" "MFOTL.fv \<phi>" "\<lambda>\<sigma> v i. MFOTL.sat \<sigma> v i \<phi>" M splitter joiner proof (standard, erule mono_splitter, safe, goal_cases sound complete) case (sound \<pi> i v) have "ok \<phi> v" using joint_monitor.wf_monitor[OF _ sound] by auto from sound obtain k where "(i, v) \<in> M (splitter \<pi> k)" "k \<in> strategy v" unfolding joiner_def by blast with \<open>ok \<phi> v\<close> show ?case by (simp add: monitor_split) next case (complete \<pi> i v) have "ok \<phi> v" using wf_monitor[OF _ complete] by auto with complete strategy_nonempty obtain k where k: "k \<in> strategy v" by blast then have "(i, v) \<in> M (splitter \<pi> k)" using complete \<open>ok \<phi> v\<close> by (simp add: monitor_split) with k show ?case unfolding joiner_def by blast qed end subsubsection \<open>Towards Theorem 3\<close> fun names :: "'a MFOTL.formula \<Rightarrow> MFOTL.name set" where "names (MFOTL.Pred e _) = {e}" | "names (MFOTL.Eq _ _) = {}" | "names (MFOTL.Neg \<psi>) = names \<psi>" | "names (MFOTL.Or \<alpha> \<beta>) = names \<alpha> \<union> names \<beta>" | "names (MFOTL.Exists \<psi>) = names \<psi>" | "names (MFOTL.Prev I \<psi>) = names \<psi>" | "names (MFOTL.Next I \<psi>) = names \<psi>" | "names (MFOTL.Since \<alpha> I \<beta>) = names \<alpha> \<union> names \<beta>" | "names (MFOTL.Until \<alpha> I \<beta>) = names \<alpha> \<union> names \<beta>" fun gen_unique :: "'a MFOTL.formula \<Rightarrow> bool" where "gen_unique (MFOTL.Pred _ _) = True" | "gen_unique (MFOTL.Eq (MFOTL.Var _) (MFOTL.Const _)) = False" | "gen_unique (MFOTL.Eq (MFOTL.Const _) (MFOTL.Var _)) = False" | "gen_unique (MFOTL.Eq _ _) = True" | "gen_unique (MFOTL.Neg \<psi>) = gen_unique \<psi>" | "gen_unique (MFOTL.Or \<alpha> \<beta>) = (gen_unique \<alpha> \<and> gen_unique \<beta> \<and> names \<alpha> \<inter> names \<beta> = {})" | "gen_unique (MFOTL.Exists \<psi>) = gen_unique \<psi>" | "gen_unique (MFOTL.Prev I \<psi>) = gen_unique \<psi>" | "gen_unique (MFOTL.Next I \<psi>) = gen_unique \<psi>" | "gen_unique (MFOTL.Since \<alpha> I \<beta>) = (gen_unique \<alpha> \<and> gen_unique \<beta> \<and> names \<alpha> \<inter> names \<beta> = {})" | "gen_unique (MFOTL.Until \<alpha> I \<beta>) = (gen_unique \<alpha> \<and> gen_unique \<beta> \<and> names \<alpha> \<inter> names \<beta> = {})" lemma sat_inter_names_cong: "(\<And>e. e \<in> names \<phi> \<Longrightarrow> {xs. (e, xs) \<in> E} = {xs. (e, xs) \<in> F}) \<Longrightarrow> MFOTL.sat (map_\<Gamma> (\<lambda>D. D \<inter> E) \<sigma>) v i \<phi> \<longleftrightarrow> MFOTL.sat (map_\<Gamma> (\<lambda>D. D \<inter> F) \<sigma>) v i \<phi>" by (induction \<phi> arbitrary: v i) (auto split: nat.splits) lemma matches_in_names: "MFOTL.matches v \<phi> x \<Longrightarrow> fst x \<in> names \<phi>" by (induction \<phi> arbitrary: v) (auto) lemma unique_names_matches_absorb: "fst x \<in> names \<alpha> \<Longrightarrow> names \<alpha> \<inter> names \<beta> = {} \<Longrightarrow> MFOTL.matches v \<alpha> x \<or> MFOTL.matches v \<beta> x \<longleftrightarrow> MFOTL.matches v \<alpha> x" "fst x \<in> names \<beta> \<Longrightarrow> names \<alpha> \<inter> names \<beta> = {} \<Longrightarrow> MFOTL.matches v \<alpha> x \<or> MFOTL.matches v \<beta> x \<longleftrightarrow> MFOTL.matches v \<beta> x" by (auto dest: matches_in_names) definition mergeable_envs where "mergeable_envs n S \<longleftrightarrow> (\<forall>v1\<in>S. \<forall>v2\<in>S. (\<forall>A B f. (\<forall>x\<in>A. x < n \<and> v1 ! x = f x) \<and> (\<forall>x\<in>B. x < n \<and> v2 ! x = f x) \<longrightarrow> (\<exists>v\<in>S. \<forall>x\<in>A \<union> B. v ! x = f x)))" lemma mergeable_envsI: assumes "\<And>v1 v2 v. v1 \<in> S \<Longrightarrow> v2 \<in> S \<Longrightarrow> length v = n \<Longrightarrow> \<forall>x < n. v ! x = v1 ! x \<or> v ! x = v2 ! x \<Longrightarrow> v \<in> S" shows "mergeable_envs n S" unfolding mergeable_envs_def proof (safe, goal_cases mergeable) case [simp]: (mergeable v1 v2 A B f) let ?v = "tabulate (\<lambda>x. if x \<in> A \<union> B then f x else v1 ! x) 0 n" from assms[of v1 v2 ?v, simplified] show ?case by (auto intro!: bexI[of _ ?v]) qed lemma in_listset_nth: "x \<in> listset As \<Longrightarrow> i < length As \<Longrightarrow> x ! i \<in> As ! i" by (induction As arbitrary: x i) (auto simp: set_Cons_def nth_Cons split: nat.split) lemma all_nth_in_listset: "length x = length As \<Longrightarrow> (\<And>i. i < length As \<Longrightarrow> x ! i \<in> As ! i) \<Longrightarrow> x \<in> listset As" by (induction x As rule: list_induct2) (fastforce simp: set_Cons_def nth_Cons)+ lemma mergeable_envs_listset: "mergeable_envs (length As) (listset As)" by (rule mergeable_envsI) (auto intro!: all_nth_in_listset elim!: in_listset_nth) lemma mergeable_envs_Ex: "mergeable_envs n S \<Longrightarrow> MFOTL.nfv \<alpha> \<le> n \<Longrightarrow> MFOTL.nfv \<beta> \<le> n \<Longrightarrow> (\<exists>v'\<in>S. \<forall>x\<in>fv \<alpha>. v' ! x = v ! x) \<Longrightarrow> (\<exists>v'\<in>S. \<forall>x\<in>fv \<beta>. v' ! x = v ! x) \<Longrightarrow> (\<exists>v'\<in>S. \<forall>x\<in>fv \<alpha> \<union> fv \<beta>. v' ! x = v ! x)" proof (clarify, goal_cases mergeable) case (mergeable v1 v2) then show ?case by (auto intro: order.strict_trans2[OF fvi_less_nfv[rule_format]] elim!: mergeable_envs_def[THEN iffD1, rule_format, of _ _ v1 v2]) qed lemma in_set_ConsE: "xs \<in> set_Cons A As \<Longrightarrow> (\<And>y ys. xs = y # ys \<Longrightarrow> y \<in> A \<Longrightarrow> ys \<in> As \<Longrightarrow> P) \<Longrightarrow> P" unfolding set_Cons_def by blast lemma mergeable_envs_set_Cons: "mergeable_envs n S \<Longrightarrow> mergeable_envs (Suc n) (set_Cons UNIV S)" unfolding mergeable_envs_def proof (clarify, elim in_set_ConsE, goal_cases mergeable) case (mergeable v1 v2 A B f y1 ys1 y2 ys2) let ?A = "(\<lambda>x. x - 1) ` (A - {0})" let ?B = "(\<lambda>x. x - 1) ` (B - {0})" from mergeable(4-9) have "\<exists>v \<in> S. \<forall>x\<in>?A \<union> ?B. v ! x = f (Suc x)" by (auto dest!: mergeable(2,3)[rule_format] intro!: mergeable(1)[rule_format, of ys1 ys2]) then obtain v where "v \<in> S" "\<forall>x\<in>?A \<union> ?B. v ! x = f (Suc x)" by blast then show ?case by (intro bexI[of _ "f 0 # v"]) (auto simp: nth_Cons' set_Cons_def) qed lemma slice_Exists: "MFOTL_slicer.slice (MFOTL.Exists \<phi>) S \<sigma> = MFOTL_slicer.slice \<phi> (set_Cons UNIV S) \<sigma>" by (auto simp: set_Cons_def intro: map_\<Gamma>_cong) lemma image_Suc_fvi: "Suc ` MFOTL.fvi (Suc b) \<phi> = MFOTL.fvi b \<phi> - {0}" by (auto simp: image_def Bex_def MFOTL.fvi_Suc dest: gr0_implies_Suc) lemma nfv_Exists: "MFOTL.nfv (MFOTL.Exists \<phi>) = MFOTL.nfv \<phi> - 1" unfolding MFOTL.nfv_def by (cases "fv \<phi> = {}") (auto simp add: image_Suc_fvi mono_Max_commute[symmetric] mono_def) lemma set_Cons_empty_iff[simp]: "set_Cons A Xs = {} \<longleftrightarrow> A = {} \<or> Xs = {}" unfolding set_Cons_def by auto lemma unique_sat_slice_mem: "safe_formula \<phi> \<Longrightarrow> gen_unique \<phi> \<Longrightarrow> S \<noteq> {} \<Longrightarrow> mergeable_envs n S \<Longrightarrow> MFOTL.nfv \<phi> \<le> n \<Longrightarrow> MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v i \<phi> \<Longrightarrow> \<exists>v'\<in>S. \<forall>x\<in>fv \<phi>. v' ! x = v ! x" proof (induction arbitrary: v i S n rule: safe_formula_induct) case (1 t1 t2) then show ?case by (cases "t2") (auto simp: MFOTL.is_Const_def) next case (2 t1 t2) then show ?case by (cases "t1") (auto simp: MFOTL.is_Const_def) next case (3 x y) then show ?case by auto next case (4 x y) then show ?case by simp next case (5 e ts) then obtain v' where "v' \<in> S" and eq: "\<forall>t\<in>set ts. MFOTL.eval_trm v' t = MFOTL.eval_trm v t" by auto have "\<forall>t\<in>set ts. \<forall>x\<in>fv_trm t. v' ! x = v ! x" proof fix t assume "t \<in> set ts" with eq have "MFOTL.eval_trm v' t = MFOTL.eval_trm v t" .. then show "\<forall>x\<in>fv_trm t. v' ! x = v ! x" by (cases t) (simp_all) qed with \<open>v' \<in> S\<close> show ?case by auto next case (6 \<phi> \<psi>) from \<open>gen_unique (MFOTL.And \<phi> \<psi>)\<close> have "MFOTL.sat (MFOTL_slicer.slice (MFOTL.And \<phi> \<psi>) S \<sigma>) v i \<phi> = MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v i \<phi>" "MFOTL.sat (MFOTL_slicer.slice (MFOTL.And \<phi> \<psi>) S \<sigma>) v i \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v i \<psi>" unfolding MFOTL.And_def by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong)+ with 6(1,4-) 6(2,3)[where S=S] show ?case unfolding MFOTL.And_def by (auto intro!: mergeable_envs_Ex) next case (7 \<phi> \<psi>) from \<open>gen_unique (MFOTL.And_Not \<phi> \<psi>)\<close> have "MFOTL.sat (MFOTL_slicer.slice (MFOTL.And_Not \<phi> \<psi>) S \<sigma>) v i \<phi> = MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v i \<phi>" unfolding MFOTL.And_Not_def by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong) with 7(1,2,5-) 7(3)[where S=S] have "\<exists>v'\<in>S. \<forall>x\<in>fv \<phi>. v' ! x = v ! x" unfolding MFOTL.And_Not_def by auto with \<open>fv \<psi> \<subseteq> fv \<phi>\<close> show ?case by (auto simp: MFOTL.fvi_And_Not) next case (8 \<phi> \<psi>) from \<open>gen_unique (MFOTL.Or \<phi> \<psi>)\<close> have "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Or \<phi> \<psi>) S \<sigma>) v i \<phi> = MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v i \<phi>" "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Or \<phi> \<psi>) S \<sigma>) v i \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v i \<psi>" by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong)+ with 8(1,4-) 8(2,3)[where S=S] have "\<exists>v'\<in>S. \<forall>x\<in>fv \<phi>. v' ! x = v ! x" by (auto simp: \<open>fv \<psi> = fv \<phi>\<close>) then show ?case by (auto simp: \<open>fv \<psi> = fv \<phi>\<close>) next case (9 \<phi>) then obtain z where sat_\<phi>: "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Exists \<phi>) S \<sigma>) (z # v) i \<phi>" by auto from "9.prems" sat_\<phi> have "\<exists>v'\<in>set_Cons UNIV S. \<forall>x\<in>fv \<phi>. v' ! x = (z # v) ! x" unfolding slice_Exists by (intro "9.IH") (auto simp: nfv_Exists intro!: mergeable_envs_set_Cons) then show ?case by (auto simp: set_Cons_def fvi_Suc Ball_def nth_Cons split: nat.splits) next case (10 I \<phi>) then obtain j where "MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v j \<phi>" by (auto split: nat.splits) with 10 show ?case by simp next case (11 I \<phi>) then obtain j where "MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v j \<phi>" by (auto split: nat.splits) with 11 show ?case by simp next case (12 \<phi> I \<psi>) from \<open>gen_unique (MFOTL.Since \<phi> I \<psi>)\<close> have *: "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Since \<phi> I \<psi>) S \<sigma>) v j \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v j \<psi>" for j by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong) from 12 obtain j where "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Since \<phi> I \<psi>) S \<sigma>) v j \<psi>" by auto with 12 have "\<exists>v'\<in>S. \<forall>x\<in>fv \<psi>. v' ! x = v ! x" using * by auto with \<open>fv \<phi> \<subseteq> fv \<psi>\<close> show ?case by auto next case (13 \<phi> I \<psi>) from \<open>gen_unique (MFOTL.Since (MFOTL.Neg \<phi>) I \<psi>)\<close> have *: "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Since (MFOTL.Neg \<phi>) I \<psi>) S \<sigma>) v j \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v j \<psi>" for j by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong) from 13 obtain j where "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Since (MFOTL.Neg \<phi>) I \<psi>) S \<sigma>) v j \<psi>" by auto with 13 have "\<exists>v'\<in>S. \<forall>x\<in>fv \<psi>. v' ! x = v ! x" using * by auto with \<open>fv (MFOTL.Neg \<phi>) \<subseteq> fv \<psi>\<close> show ?case by auto next case (14 \<phi> I \<psi>) from \<open>gen_unique (MFOTL.Until \<phi> I \<psi>)\<close> have *: "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Until \<phi> I \<psi>) S \<sigma>) v j \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v j \<psi>" for j by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong) from 14 obtain j where "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Until \<phi> I \<psi>) S \<sigma>) v j \<psi>" by auto with 14 have "\<exists>v'\<in>S. \<forall>x\<in>fv \<psi>. v' ! x = v ! x" using * by auto with \<open>fv \<phi> \<subseteq> fv \<psi>\<close> show ?case by auto next case (15 \<phi> I \<psi>) from \<open>gen_unique (MFOTL.Until (MFOTL.Neg \<phi>) I \<psi>)\<close> have *: "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Until (MFOTL.Neg \<phi>) I \<psi>) S \<sigma>) v j \<psi> = MFOTL.sat (MFOTL_slicer.slice \<psi> S \<sigma>) v j \<psi>" for j by (fastforce simp: unique_names_matches_absorb intro!: sat_inter_names_cong) from 15 obtain j where "MFOTL.sat (MFOTL_slicer.slice (MFOTL.Until (MFOTL.Neg \<phi>) I \<psi>) S \<sigma>) v j \<psi>" by auto with 15 have "\<exists>v'\<in>S. \<forall>x\<in>fv \<psi>. v' ! x = v ! x" using * by auto with \<open>fv (MFOTL.Neg \<phi>) \<subseteq> fv \<psi>\<close> show ?case by auto qed lemma unique_sat_slice: assumes formula: "safe_formula \<phi>" "gen_unique \<phi>" and restr: "S \<noteq> {}" "mergeable_envs (MFOTL.nfv \<phi>) S" and sat_slice: "MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v i \<phi>" shows "MFOTL.sat \<sigma> v i \<phi>" proof - obtain v' where "v' \<in> S" and fv_eq: "\<forall>x\<in>fv \<phi>. v' ! x = v ! x" using unique_sat_slice_mem[OF formula restr order_refl sat_slice] .. with sat_slice have "MFOTL.sat (MFOTL_slicer.slice \<phi> S \<sigma>) v' i \<phi>" by (auto iff: sat_fvi_cong) then have "MFOTL.sat \<sigma> v' i \<phi>" unfolding sat_slice_iff[OF \<open>v' \<in> S\<close>, symmetric] . with fv_eq show ?thesis by (auto iff: sat_fvi_cong) qed subsubsection \<open>Lemma 3\<close> lemma (in splitting_strategy) unique_sat_strategy: "safe_formula \<phi> \<Longrightarrow> gen_unique \<phi> \<Longrightarrow> slice_set k \<noteq> {} \<Longrightarrow> mergeable_envs (MFOTL.nfv \<phi>) (slice_set k) \<Longrightarrow> MFOTL.sat (MFOTL_slicer.slice \<phi> (slice_set k) \<sigma>) (map the v) i \<phi> \<Longrightarrow> ok \<phi> v \<Longrightarrow> k \<in> strategy v" by (drule (3) unique_sat_slice_mem) (auto dest: wf_tuple_cong) locale skip_inter = joint_data_slicer + assumes nonempty: "slice_set k \<noteq> {}" and mergeable: "mergeable_envs (MFOTL.nfv \<phi>) (slice_set k)" begin subsubsection \<open>Definition of J'\<close> definition "skip_joiner = (\<lambda>s. \<Union>k. s k)" subsubsection \<open>Theorem 3\<close> lemma skip_joiner: assumes "safe_formula \<phi>" "gen_unique \<phi>" shows "joiner (\<lambda>k. M (splitter \<pi> k)) = skip_joiner (\<lambda>k. M (splitter \<pi> k))" (is "?L = ?R") proof safe fix i v assume "(i, v) \<in> ?R" then obtain k where in_M: "(i, v) \<in> M (splitter \<pi> k)" unfolding skip_joiner_def by blast from ex_prefix_of obtain \<sigma> where "prefix_of \<pi> \<sigma>" by blast with wf_monitor[OF _ in_M] sound_monitor[OF _ in_M] have "MFOTL.sat (MFOTL_slicer.slice \<phi> (slice_set k) \<sigma>) (map the v) i \<phi>" "ok \<phi> v" by (auto simp: splitter_pslice intro!: prefix_of_pmap_\<Gamma>) note unique_sat_strategy[OF assms nonempty mergeable this] with in_M show "(i, v) \<in> ?L" unfolding joiner_def by blast qed (auto simp: joiner_def skip_joiner_def) sublocale skip_joint_monitor: MFOTL_monitor \<phi> "\<lambda>\<pi>. (if safe_formula \<phi> \<and> gen_unique \<phi> then skip_joiner else joiner) (\<lambda>k. M (splitter \<pi> k))" using joint_monitor.mono_monitor joint_monitor.wf_monitor joint_monitor.sound_monitor joint_monitor.complete_monitor by unfold_locales (auto simp: skip_joiner[symmetric] split: if_splits) end (*<*) end (*>*)
-- Andreas, 2019-08-18, issue #1346 -- Allow fixity in renaming directive, but not for modules. module _ where open import Agda.Builtin.Equality using () renaming (module _≡_ to infix 4 _~_) -- Expected warning: -- Modules do not have fixity -- when scope checking the declaration -- open import Agda.Builtin.Equality -- using () -- renaming (module _≡_ to infix 4 _~_)
module Data.HList %default total public export data HList : List Type -> Type where Nil : HList [] (::) : (a : x) -> HList xs -> HList (x :: xs)
# Intial data generation trials in 2D ```python import sys # isort:skip sys.path.insert(0, "../") # isort:skip import pickle from math import pi import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import sympy from sympy import cos, sin, symbols from synthetic_data.synthetic_data import make_tabular_data ``` ### Without correlation ```python # define symbols x1, x2 = symbols("x1 x2") # define expression expr = cos(x1 ** 2 * pi / 180.0) - sin(x2 * pi / 180.0) + x1 * x2 # define mapping from symbols to column of X - clunky TODO - make it better col_map = {x1: 0, x2: 1} ``` ```python # define correlations via covariance matrix cov = np.array([[1.0, 0.0], [0.0, 1.0]]) ``` ```python n_samples = 1000 p_thresh = 0.5 # probability threshold to divide class 0 from class 1 # every other parameter is going to use the default - check docstring for completion ``` ```python X, y_reg, y_prob, y_label = make_tabular_data(n_samples=n_samples, cov=cov, col_map=col_map, expr=expr, p_thresh=p_thresh) ``` ### With correlation ```python cov_c = np.array([[1.0, 0.5], [0.5, 1.0]]) ``` ```python X_c, y_reg_c, y_prob_c, y_label_c = make_tabular_data(n_samples=n_samples, cov=cov_c, col_map=col_map, expr=expr, p_thresh=p_thresh) ``` ### Let's see what we got! #### Uncorrelated inputs ```python h = sns.jointplot(X[:, 0], X[:, 1], kind="hex", stat_func=None) h.set_axis_labels("x1", "x2", fontsize=16) ``` #### Correlated inputs ```python h = sns.jointplot(X_c[:, 0], X_c[:, 1], kind="hex", stat_func=None) h.set_axis_labels("x1", "x2", fontsize=16) ``` ## Let's check the impact on y_reg ```python levels = np.arange(0, 2.2, 0.2) fig, ax = plt.subplots(nrows = 1, ncols=2, figsize=(16, 7)) tri1 = ax[0].tricontourf(X[:, 0], X[:, 1], y_reg, levels=levels) scatter = ax[0].scatter(X[:, 0], X[:, 1], c='k', label=y_label, marker=".") leg1 = ax[0].legend(*scatter.legend_elements(), loc="lower right", title="class") #cbar1 = fig.colorbar(tri1, ax=ax) ax[0].set_title("No correlation") ax[0].set_xlabel("x1") ax[0].set_ylabel("x2") ax[0].axis('equal') #cbar1.formatter.set_powerlimits((0, 0)) #cbar1.update_ticks() tri1 = ax[1].tricontourf(X_c[:, 0], X_c[:, 1], y_reg_c, levels=levels) scatter = ax[1].scatter(X_c[:, 0], X_c[:, 1], c='k', label=y_label, marker=".") leg1 = ax[1].legend(*scatter.legend_elements(), loc="lower right", title="class") cbar1 = fig.colorbar(tri1, ax=ax) ax[1].set_title("With correlation") ax[1].set_xlabel("x1") ax[1].axis('equal') #ax[1].set_ylabel("x2") #cbar1.formatter.set_powerlimits((0, 0)) cbar1.update_ticks() ``` You can see that the positive correlation has shifted density to the lower left and upper right. But the contours remain in the same location (which is intended - the function f(X) doesn't change because we have correlation). ## Similar plots but with y_prob = sigmoid(y_reg) This is the last step in the creation of our binary class labels. ```python levels = np.arange(0, 2.2, 0.2) fig, ax = plt.subplots(nrows = 1, ncols=2, figsize=(16, 7)) tri1 = ax[0].tricontourf(X[:, 0], X[:, 1], y_prob, levels=levels) scatter = ax[0].scatter(X[:, 0], X[:, 1], c=y_label, label=y_label, marker=".") leg1 = ax[0].legend(*scatter.legend_elements(), loc="lower right", title="class") #cbar1 = fig.colorbar(tri1, ax=ax) ax[0].set_title("No correlation") ax[0].set_xlabel("x1") ax[0].set_ylabel("x2") ax[0].axis('equal') #cbar1.formatter.set_powerlimits((0, 0)) #cbar1.update_ticks() tri1 = ax[1].tricontourf(X_c[:, 0], X_c[:, 1], y_prob_c, levels=levels) scatter = ax[1].scatter(X_c[:, 0], X_c[:, 1], c=y_label_c, label=y_label, marker=".") leg1 = ax[1].legend(*scatter.legend_elements(), loc="lower right", title="class") cbar1 = fig.colorbar(tri1, ax=ax) ax[1].set_title("With correlation") ax[1].set_xlabel("x1") ax[1].axis('equal') #ax[1].set_ylabel("x2") #cbar1.formatter.set_powerlimits((0, 0)) cbar1.update_ticks() ``` ### Wot? Why don't our probabilities (and our labels) agree between the two plots? Answer: the sigmoid function has a parameter x_0 that 'centers' the sigmoid. The default choice is `x_0 = np.mean(<some y_reg type vector here>)` ```python np.mean(y_reg) ``` 0.9909529 ```python np.mean(y_reg_c) ``` 1.1620378 Those means are not the same, so the sigmoid won't be 'centered' the same way between the two datasets. ### Q: Are we generating balanced classes? ```python np.unique(y_label, return_counts=True) ``` (array([False, True]), array([501, 499])) ```python np.unique(y_label_c, return_counts=True) ``` (array([False, True]), array([583, 417])) The baseline case with no correlation is balanced. But the correlated case is skewed toward class 0. So let's fix the value we use to center the sigmoid and recalculate...maybe that will rebalance the classes? ```python x_0_baseline = np.mean(y_reg) ``` ```python X_3, y_reg_3, y_prob_3, y_label_3 = make_tabular_data(n_samples=n_samples, cov=cov_c, col_map=col_map, expr=expr, sig_x0=x_0_baseline, p_thresh=p_thresh) ``` ```python levels = np.arange(0, 2.2, 0.2) fig, ax = plt.subplots(nrows = 1, ncols=2, figsize=(16, 7)) tri1 = ax[0].tricontourf(X[:, 0], X[:, 1], y_prob, levels=levels) scatter = ax[0].scatter(X[:, 0], X[:, 1], c=y_label, label=y_label, marker=".") leg1 = ax[0].legend(*scatter.legend_elements(), loc="lower right", title="class") #cbar1 = fig.colorbar(tri1, ax=ax) ax[0].set_title("No correlation") ax[0].set_xlabel("x1") ax[0].set_ylabel("x2") ax[0].axis('equal') #cbar1.formatter.set_powerlimits((0, 0)) #cbar1.update_ticks() tri1 = ax[1].tricontourf(X_3[:, 0], X_3[:, 1], y_prob_3, levels=levels) scatter = ax[1].scatter(X_3[:, 0], X_3[:, 1], c=y_label_3, label=y_label, marker=".") leg1 = ax[1].legend(*scatter.legend_elements(), loc="lower right", title="class") cbar1 = fig.colorbar(tri1, ax=ax) ax[1].set_title("With correlation - and fixed sig_x0") ax[1].set_xlabel("x1") ax[1].axis('equal') #ax[1].set_ylabel("x2") #cbar1.formatter.set_powerlimits((0, 0)) cbar1.update_ticks() ``` ### TADA! ```python np.unique(y_label, return_counts=True) ``` (array([False, True]), array([501, 499])) ```python np.unique(y_label_3, return_counts=True) ``` (array([False, True]), array([305, 695])) ...but now we have significantly unbalanced the classes.... ```python ```
module Presentation import Control.Linear.LIO import Utils -- dup : (1 _ : Int) -> (Int,Int) -- dup x = (x,x) -- greetAudience : (1 _ : String) -> String -- greetAudience city = "Hello Sydney" picture : (url : String) -> Image picture url = fetchImage url $ \image => let croppedImage = cropImage image transposedImage = transposeImage croppedImage in transposedImage readFile : (1 _ : String) -> IO String readFile filename = let (>>=) = myBind in do file <- openFile filename (content # filehandler) <- read file closeFile filehandler `seq` pure (utf8Decode content) -- Local Variables: -- idris-load-packages: ("support" "prelude" "network" "lib" "base" "contrib") -- End:
-- {-# OPTIONS --verbose tc.proj.like:100 #-} -- Apparently, there can be projection like functions working on arguments of type Axiom. module Issue558c where data ⊤ : Set where tt : ⊤ data V : Set where aV : ⊤ → V postulate D : ⊤ → Set zero : D tt suc : ∀ {t} → D t → V test : {{v : V}} → ⊤ test {{v}} = tt module test {t : ⊤} {d : D t} where inst : V inst = aV tt someT : ⊤ someT = test
(* Title: SIFUM-Type-Systems Authors: Sylvia Grewe, Heiko Mantel, Daniel Schoepe *) header {* Definition of the SIFUM-Security Property *} theory Security imports Main Preliminaries begin context sifum_security begin subsection {* Evaluation of Concurrent Programs *} abbreviation eval_abv :: "('Com, 'Var, 'Val) LocalConf \<Rightarrow> (_, _, _) LocalConf \<Rightarrow> bool" (infixl "\<leadsto>" 70) where "x \<leadsto> y \<equiv> (x, y) \<in> eval" abbreviation conf_abv :: "'Com \<Rightarrow> 'Var Mds \<Rightarrow> ('Var, 'Val) Mem \<Rightarrow> (_,_,_) LocalConf" ("\<langle>_, _, _\<rangle>" [0, 0, 0] 1000) where "\<langle> c, mds, mem \<rangle> \<equiv> ((c, mds), mem)" (* Evaluation of global configurations: *) inductive_set meval :: "(_,_,_) GlobalConf rel" and meval_abv :: "_ \<Rightarrow> _ \<Rightarrow> bool" (infixl "\<rightarrow>" 70) where "conf \<rightarrow> conf' \<equiv> (conf, conf') \<in> meval" | meval_intro [iff]: "\<lbrakk> (cms ! n, mem) \<leadsto> (cm', mem'); n < length cms \<rbrakk> \<Longrightarrow> ((cms, mem), (cms [n := cm'], mem')) \<in> meval" inductive_cases meval_elim [elim!]: "((cms, mem), (cms', mem')) \<in> meval" (* Syntactic sugar for the reflexive-transitive closure of meval: *) abbreviation meval_clos :: "_ \<Rightarrow> _ \<Rightarrow> bool" (infixl "\<rightarrow>\<^sup>*" 70) where "conf \<rightarrow>\<^sup>* conf' \<equiv> (conf, conf') \<in> meval\<^sup>*" fun lc_set_var :: "(_, _, _) LocalConf \<Rightarrow> 'Var \<Rightarrow> 'Val \<Rightarrow> (_, _, _) LocalConf" where "lc_set_var (c, mem) x v = (c, mem (x := v))" fun meval_k :: "nat \<Rightarrow> ('Com, 'Var, 'Val) GlobalConf \<Rightarrow> (_, _, _) GlobalConf \<Rightarrow> bool" where "meval_k 0 c c' = (c = c')" | "meval_k (Suc n) c c' = (\<exists> c''. meval_k n c c'' \<and> c'' \<rightarrow> c')" (* k steps of evaluation (for global configurations: *) abbreviation meval_k_abv :: "nat \<Rightarrow> (_, _, _) GlobalConf \<Rightarrow> (_, _, _) GlobalConf \<Rightarrow> bool" ("_ \<rightarrow>\<index> _" [100, 100] 80) where "gc \<rightarrow>\<^bsub>k \<^esub>gc' \<equiv> meval_k k gc gc'" subsection {* Low-equivalence and Strong Low Bisimulations *} (* Low-equality between memory states: *) definition low_eq :: "('Var, 'Val) Mem \<Rightarrow> (_, _) Mem \<Rightarrow> bool" (infixl "=\<^sup>l" 80) where "mem\<^sub>1 =\<^sup>l mem\<^sub>2 \<equiv> (\<forall> x. dma x = Low \<longrightarrow> mem\<^sub>1 x = mem\<^sub>2 x)" (* Low-equality modulo a given mode state: *) definition low_mds_eq :: "'Var Mds \<Rightarrow> ('Var, 'Val) Mem \<Rightarrow> (_, _) Mem \<Rightarrow> bool" ("_ =\<index>\<^sup>l _" [100, 100] 80) where "(mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2) \<equiv> (\<forall> x. dma x = Low \<and> x \<notin> mds AsmNoRead \<longrightarrow> mem\<^sub>1 x = mem\<^sub>2 x)" (* Initial mode state: *) definition "mds\<^sub>s" :: "'Var Mds" where "mds\<^sub>s x = {}" lemma [simp]: "(\<forall> mds. mem =\<^bsub>mds\<^esub>\<^sup>l mem') \<Longrightarrow> mem =\<^sup>l mem'" by (auto simp: low_mds_eq_def low_eq_def) (* Closedness under globally consistent changes: *) definition closed_glob_consistent :: "(('Com, 'Var, 'Val) LocalConf) rel \<Rightarrow> bool" where "closed_glob_consistent \<R> = (\<forall> c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2. (\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>) \<in> \<R> \<longrightarrow> (\<forall> x. ((dma x = High \<and> x \<notin> mds AsmNoWrite) \<longrightarrow> (\<forall> v\<^sub>1 v\<^sub>2. (\<langle> c\<^sub>1, mds, mem\<^sub>1 (x := v\<^sub>1) \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 (x := v\<^sub>2) \<rangle>) \<in> \<R>)) \<and> ((dma x = Low \<and> x \<notin> mds AsmNoWrite) \<longrightarrow> (\<forall> v. (\<langle> c\<^sub>1, mds, mem\<^sub>1 (x := v) \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 (x := v) \<rangle>) \<in> \<R>))))" (* Strong low bisimulations modulo modes: *) definition strong_low_bisim_mm :: "(('Com, 'Var, 'Val) LocalConf) rel \<Rightarrow> bool" where "strong_low_bisim_mm \<R> \<equiv> sym \<R> \<and> closed_glob_consistent \<R> \<and> (\<forall> c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2. (\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>) \<in> \<R> \<longrightarrow> (mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2) \<and> (\<forall> c\<^sub>1' mds' mem\<^sub>1'. \<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle> \<leadsto> \<langle> c\<^sub>1', mds', mem\<^sub>1' \<rangle> \<longrightarrow> (\<exists> c\<^sub>2' mem\<^sub>2'. \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle> \<leadsto> \<langle> c\<^sub>2', mds', mem\<^sub>2' \<rangle> \<and> (\<langle> c\<^sub>1', mds', mem\<^sub>1' \<rangle>, \<langle> c\<^sub>2', mds', mem\<^sub>2' \<rangle>) \<in> \<R>)))" inductive_set mm_equiv :: "(('Com, 'Var, 'Val) LocalConf) rel" and mm_equiv_abv :: "('Com, 'Var, 'Val) LocalConf \<Rightarrow> ('Com, 'Var, 'Val) LocalConf \<Rightarrow> bool" (infix "\<approx>" 60) where "mm_equiv_abv x y \<equiv> (x, y) \<in> mm_equiv" | mm_equiv_intro [iff]: "\<lbrakk> strong_low_bisim_mm \<R> ; (lc\<^sub>1, lc\<^sub>2) \<in> \<R> \<rbrakk> \<Longrightarrow> (lc\<^sub>1, lc\<^sub>2) \<in> mm_equiv" inductive_cases mm_equiv_elim [elim]: "\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle> \<approx> \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>" definition low_indistinguishable :: "'Var Mds \<Rightarrow> 'Com \<Rightarrow> 'Com \<Rightarrow> bool" ("_ \<sim>\<index> _" [100, 100] 80) where "c\<^sub>1 \<sim>\<^bsub>mds\<^esub> c\<^sub>2 = (\<forall> mem\<^sub>1 mem\<^sub>2. mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2 \<longrightarrow> \<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle> \<approx> \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>)" subsection {* SIFUM-Security *} (* SIFUM-security for commands: *) definition com_sifum_secure :: "'Com \<Rightarrow> bool" where "com_sifum_secure c = c \<sim>\<^bsub>mds\<^sub>s\<^esub> c" definition add_initial_modes :: "'Com list \<Rightarrow> ('Com \<times> 'Var Mds) list" where "add_initial_modes cmds = zip cmds (replicate (length cmds) mds\<^sub>s)" definition no_assumptions_on_termination :: "'Com list \<Rightarrow> bool" where "no_assumptions_on_termination cmds = (\<forall> mem mem' cms'. (add_initial_modes cmds, mem) \<rightarrow>\<^sup>* (cms', mem') \<and> list_all (\<lambda> c. c = stop) (map fst cms') \<longrightarrow> (\<forall> mds' \<in> set (map snd cms'). mds' AsmNoRead = {} \<and> mds' AsmNoWrite = {}))" (* SIFUM-security for programs: *) definition prog_sifum_secure :: "'Com list \<Rightarrow> bool" where "prog_sifum_secure cmds = (no_assumptions_on_termination cmds \<and> (\<forall> mem\<^sub>1 mem\<^sub>2. mem\<^sub>1 =\<^sup>l mem\<^sub>2 \<longrightarrow> (\<forall> k cms\<^sub>1' mem\<^sub>1'. (add_initial_modes cmds, mem\<^sub>1) \<rightarrow>\<^bsub>k\<^esub> (cms\<^sub>1', mem\<^sub>1') \<longrightarrow> (\<exists> cms\<^sub>2' mem\<^sub>2'. (add_initial_modes cmds, mem\<^sub>2) \<rightarrow>\<^bsub>k\<^esub> (cms\<^sub>2', mem\<^sub>2') \<and> map snd cms\<^sub>1' = map snd cms\<^sub>2' \<and> length cms\<^sub>2' = length cms\<^sub>1' \<and> (\<forall> x. dma x = Low \<and> (\<forall> i < length cms\<^sub>1'. x \<notin> snd (cms\<^sub>1' ! i) AsmNoRead) \<longrightarrow> mem\<^sub>1' x = mem\<^sub>2' x)))))" subsection {* Sound Mode Use *} definition doesnt_read :: "'Com \<Rightarrow> 'Var \<Rightarrow> bool" where "doesnt_read c x = (\<forall> mds mem c' mds' mem'. \<langle> c, mds, mem \<rangle> \<leadsto> \<langle> c', mds', mem' \<rangle> \<longrightarrow> ((\<forall> v. \<langle> c, mds, mem (x := v) \<rangle> \<leadsto> \<langle> c', mds', mem' (x := v) \<rangle>) \<or> (\<forall> v. \<langle> c, mds, mem (x := v) \<rangle> \<leadsto> \<langle> c', mds', mem' \<rangle>)))" definition doesnt_modify :: "'Com \<Rightarrow> 'Var \<Rightarrow> bool" where "doesnt_modify c x = (\<forall> mds mem c' mds' mem'. (\<langle> c, mds, mem \<rangle> \<leadsto> \<langle> c', mds', mem' \<rangle>) \<longrightarrow> mem x = mem' x)" (* Local reachability of local configurations: *) inductive_set loc_reach :: "('Com, 'Var, 'Val) LocalConf \<Rightarrow> ('Com, 'Var, 'Val) LocalConf set" for lc :: "(_, _, _) LocalConf" where refl : "\<langle>fst (fst lc), snd (fst lc), snd lc\<rangle> \<in> loc_reach lc" | step : "\<lbrakk> \<langle>c', mds', mem'\<rangle> \<in> loc_reach lc; \<langle>c', mds', mem'\<rangle> \<leadsto> \<langle>c'', mds'', mem''\<rangle> \<rbrakk> \<Longrightarrow> \<langle>c'', mds'', mem''\<rangle> \<in> loc_reach lc" | mem_diff : "\<lbrakk> \<langle> c', mds', mem' \<rangle> \<in> loc_reach lc; (\<forall> x \<in> mds' AsmNoWrite. mem' x = mem'' x) \<rbrakk> \<Longrightarrow> \<langle> c', mds', mem'' \<rangle> \<in> loc_reach lc" definition locally_sound_mode_use :: "(_, _, _) LocalConf \<Rightarrow> bool" where "locally_sound_mode_use lc = (\<forall> c' mds' mem'. \<langle> c', mds', mem' \<rangle> \<in> loc_reach lc \<longrightarrow> (\<forall> x. (x \<in> mds' GuarNoRead \<longrightarrow> doesnt_read c' x) \<and> (x \<in> mds' GuarNoWrite \<longrightarrow> doesnt_modify c' x)))" definition compatible_modes :: "('Var Mds) list \<Rightarrow> bool" where "compatible_modes mdss = (\<forall> (i :: nat) x. i < length mdss \<longrightarrow> (x \<in> (mdss ! i) AsmNoRead \<longrightarrow> (\<forall> j < length mdss. j \<noteq> i \<longrightarrow> x \<in> (mdss ! j) GuarNoRead)) \<and> (x \<in> (mdss ! i) AsmNoWrite \<longrightarrow> (\<forall> j < length mdss. j \<noteq> i \<longrightarrow> x \<in> (mdss ! j) GuarNoWrite)))" definition reachable_mode_states :: "('Com, 'Var, 'Val) GlobalConf \<Rightarrow> (('Var Mds) list) set" where "reachable_mode_states gc = {mdss. (\<exists> cms' mem'. gc \<rightarrow>\<^sup>* (cms', mem') \<and> map snd cms' = mdss)}" definition globally_sound_mode_use :: "('Com, 'Var, 'Val) GlobalConf \<Rightarrow> bool" where "globally_sound_mode_use gc = (\<forall> mdss. mdss \<in> reachable_mode_states gc \<longrightarrow> compatible_modes mdss)" primrec sound_mode_use :: "(_, _, _) GlobalConf \<Rightarrow> bool" where "sound_mode_use (cms, mem) = (list_all (\<lambda> cm. locally_sound_mode_use (cm, mem)) cms \<and> globally_sound_mode_use (cms, mem))" (* We now show that mm_equiv itself forms a strong low bisimulation modulo modes: *) lemma mm_equiv_sym: assumes equivalent: "\<langle>c\<^sub>1, mds\<^sub>1, mem\<^sub>1\<rangle> \<approx> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>" shows "\<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle> \<approx> \<langle>c\<^sub>1, mds\<^sub>1, mem\<^sub>1\<rangle>" proof - from equivalent obtain \<R> where \<R>_bisim: "strong_low_bisim_mm \<R> \<and> (\<langle>c\<^sub>1, mds\<^sub>1, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>) \<in> \<R>" by (metis mm_equiv.simps) hence "sym \<R>" by (auto simp: strong_low_bisim_mm_def) hence "(\<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>, \<langle>c\<^sub>1, mds\<^sub>1, mem\<^sub>1\<rangle>) \<in> \<R>" by (metis \<R>_bisim symE) thus ?thesis by (metis \<R>_bisim mm_equiv.intros) qed lemma low_indistinguishable_sym: "lc \<sim>\<^bsub>mds\<^esub> lc' \<Longrightarrow> lc' \<sim>\<^bsub>mds\<^esub> lc" by (auto simp: mm_equiv_sym low_indistinguishable_def low_mds_eq_def) lemma mm_equiv_glob_consistent: "closed_glob_consistent mm_equiv" unfolding closed_glob_consistent_def apply clarify apply (erule mm_equiv_elim) by (auto simp: strong_low_bisim_mm_def closed_glob_consistent_def) lemma mm_equiv_strong_low_bisim: "strong_low_bisim_mm mm_equiv" unfolding strong_low_bisim_mm_def proof (auto) show "closed_glob_consistent mm_equiv" by (rule mm_equiv_glob_consistent) next fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 x assume "\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle> \<approx> \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>" then obtain \<R> where "strong_low_bisim_mm \<R> \<and> (\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>) \<in> \<R>" by blast thus "mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" by (auto simp: strong_low_bisim_mm_def) next fix c\<^sub>1 :: 'Com fix mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 c\<^sub>1' mds' mem\<^sub>1' let ?lc\<^sub>1 = "\<langle> c\<^sub>1, mds, mem\<^sub>1 \<rangle>" and ?lc\<^sub>1' = "\<langle> c\<^sub>1', mds', mem\<^sub>1' \<rangle>" and ?lc\<^sub>2 = "\<langle> c\<^sub>2, mds, mem\<^sub>2 \<rangle>" assume "?lc\<^sub>1 \<approx> ?lc\<^sub>2" then obtain \<R> where "strong_low_bisim_mm \<R> \<and> (?lc\<^sub>1, ?lc\<^sub>2) \<in> \<R>" by (rule mm_equiv_elim, blast) moreover assume "?lc\<^sub>1 \<leadsto> ?lc\<^sub>1'" ultimately show "\<exists> c\<^sub>2' mem\<^sub>2'. ?lc\<^sub>2 \<leadsto> \<langle> c\<^sub>2', mds', mem\<^sub>2' \<rangle> \<and> ?lc\<^sub>1' \<approx> \<langle> c\<^sub>2', mds', mem\<^sub>2' \<rangle>" by (simp add: strong_low_bisim_mm_def mm_equiv_sym, blast) next show "sym mm_equiv" by (auto simp: sym_def mm_equiv_sym) qed end end
""" Implement Bao, S., Xu, S., Zhang, L., Yan, R., Su, Z., Han, D. and Yu, Y., 2012. Mining social emotions from affective text. IEEE transactions on knowledge and data engineering, 24(9), pp.1658-1670. """ import numpy as np from scipy.sparse import csr_matrix from datetime import datetime from datetime import timedelta from tqdm import tqdm import cPickle from functions import probNormalize, multinomial class ETM(object): def __init__(self, K): """ :param K: # topics """ # model hyperparameters # self.alpha = 0.1 # emotion-topic distribution prior self.beta = 0.01 # topic-word distribution prior # data dimensions # self.E = 0 # number of emotions self.K = K # number of topics self.D = 0 # number of documents self.Nd = [] # number of words of documents (varying over docs) self.V = 0 # size of vocabulary # model latent variables # self.theta = None # emotion-topic distribution [self.E, self.K] self.phi = None # topic-word distribution [self.K, self.V] self.esp = None # word-level emotion "[self.D, self.Nd]" self.z = None # word-level topic "[self.D, self.Nd]" # intermediate variables for fitting # self.TE = None # count of topic-emotion cooccurrence [self.K, self.E] self.TV = None # count of topic-word cooccurrence [self.K, self.V] self.TI = None # count of topic [self.K], np.sum(self.TV, axis=1) self.IE = None # count of emotions [self.E], np.sum(self.TE, axis=0) # save & restore # self.checkpoint_file = "ckpt/ETM" def fit(self, dataE, dataW, corpus=None, alpha=0.1, beta=0.01, max_iter = 500, resume = None): """ Collapsed Gibbs sampler :param dataE: Emotion distribution of each document np.ndarray([self.D, self.E]) :param dataW: Indexed corpus np.ndarray([self.D, self.V]) scipy.sparse.csr_matrix """ self._setHyperparameters(alpha=alpha, beta=beta) if corpus is None: dataToken = self._matrix2corpus(dataW=dataW) else: dataToken = corpus self._setDataDimension(dataE=dataE, dataW=dataW, dataToken=dataToken) if resume is None: self._initialize(dataE=dataE, dataW=dataW, dataToken=dataToken) else: self._restoreCheckPoint(filename=resume) ppl_initial = self._ppl(dataE=dataE, dataW=dataW, dataToken=dataToken) print "before training, ppl: %s" % str(ppl_initial) ## Gibbs Sampling ## for epoch in range(max_iter): self._GibbsSamplingLocal(dataE=dataE, dataW=dataW, dataToken=dataToken, epoch=epoch) self._estimateGlobal(dataE) ppl = self._ppl(dataE=dataE, dataW=dataW, dataToken=dataToken) print "epoch: %d, ppl: %s" % (epoch, str(ppl)) self._saveCheckPoint(epoch, ppl) def _setHyperparameters(self, alpha, beta): self.alpha = alpha self.beta = beta def _matrix2corpus(self, dataW): start = datetime.now() dataToken = [] for d in range(dataW.shape[0]): docW = dataW.getrow(d) docToken = [] for w_id in docW.indices: w_freq = docW[0, w_id] for i in range(w_freq): docToken.append(w_id) dataToken.append(docToken) duration = datetime.now() - start print "_matrix2corpus() takes %fs" % duration.total_seconds() return dataToken def _setDataDimension(self, dataE, dataW, dataToken): self.E = dataE.shape[1] self.D = dataE.shape[0] self.Nd = map(lambda x: len(x), dataToken) self.V = dataW.shape[1] def _initialize(self, dataE, dataW, dataToken): start = datetime.now() self.theta = probNormalize(np.random.random([self.E, self.K])) self.phi = probNormalize(np.random.random([self.K, self.V])) self.esp = [] self.z = [] z_dist = np.sum(self.theta, axis=0) / self.E for d in range(self.D): Nd = self.Nd[d] gamma = dataE[d] self.esp.append(multinomial(gamma, Nd)) self.z.append(multinomial(z_dist, Nd)) self.TE = np.zeros([self.K, self.E], dtype=np.int32) self.TV = np.zeros([self.K, self.V], dtype=np.int32) for d in range(self.D): docToken = dataToken[d] doc_z = self.z[d] doc_esp = self.esp[d] for n in range(self.Nd[d]): w = docToken[n] w_z = doc_z[n] w_esp = doc_esp[n] self.TE[w_z, w_esp] += 1 self.TV[w_z, w] += 1 self.TI = np.sum(self.TV, axis=1) self.IE = np.sum(self.TE, axis=0) duration = datetime.now() - start print "_initialize() takes %fs" % duration.total_seconds() def _GibbsSamplingLocal(self, dataE, dataW, dataToken, epoch): """ Gibbs sampling word-level emotion and topic """ pbar = tqdm(range(self.D), total = self.D, desc='({0:^3})'.format(epoch)) for d in pbar: # sequentially sampling doc_Nd = self.Nd[d] docE = dataE[d] docToken = dataToken[d] for n in range(doc_Nd): w = docToken[n] w_z = self.z[d][n] w_esp = self.esp[d][n] ## sampling ## # calculate leave-one out statistics # TE_no_dn, TV_no_dn, TI_no_dn, IE_no_dn, = self.TE, self.TV, self.TI, self.IE TE_no_dn[w_z, w_esp] += -1 TV_no_dn[w_z, w] += -1 TI_no_dn[w_z] += -1 IE_no_dn[w_esp] += -1 # conditional probability # prob_w_esp = np.divide(np.multiply((self.alpha + TE_no_dn[w_z]), docE), (self.K * self.alpha + IE_no_dn)) prob_w_esp = probNormalize(prob_w_esp) prob_w_z = np.divide(np.multiply((self.alpha + TE_no_dn[:, w_esp]), (self.beta + TV_no_dn[:, w])), (self.V * self.beta + TI_no_dn)) prob_w_z = probNormalize(prob_w_z) # new sampled result # w_esp_new = multinomial(prob_w_esp) w_z_new = multinomial(prob_w_z) # update # self.z[d][n] = w_z_new self.esp[d][n] = w_esp_new TE_no_dn[w_z_new, w_esp_new] += 1 TV_no_dn[w_z_new, w] += 1 TI_no_dn[w_z_new] += 1 IE_no_dn[w_esp_new] += 1 self.TE, self.TV, self.TI, self.IE = TE_no_dn, TV_no_dn, TI_no_dn, IE_no_dn def _estimateGlobal(self, dataE): self.theta = probNormalize(self.alpha + np.transpose(self.TE)) self.phi = probNormalize(self.beta + self.TV) def _ppl(self, dataE, dataW, dataToken): prob_dw = probNormalize(np.tensordot(np.tensordot(dataE, self.theta, axes=(-1,0)), self.phi, axes=(-1,0))) ppl = - np.sum(dataW.multiply(np.log(prob_dw)))/sum(self.Nd) return ppl, np.exp(ppl) def _saveCheckPoint(self, epoch, ppl = None, filename = None): if filename is None: filename = self.checkpoint_file state = { "theta": self.theta, "phi": self.phi, "alpha": self.alpha, "beta": self.beta, "esp": self.esp, "z": self.z, "TE": self.TE, "TV": self.TV, "TI": self.TI, "IE": self.IE, "epoch": epoch, "ppl": ppl } with open(filename, "w") as f_ckpt: cPickle.dump(state, f_ckpt) def _restoreCheckPoint(self, filename = None): if filename is None: filename = self.checkpoint_file state = cPickle.load(open(filename, "r")) # restore # self.theta = state["theta"] self.phi = state["phi"] self.alpha = state["alpha"] self.beta = state["beta"] self.esp = state["esp"] self.z = state["z"] self.TE = state["TE"] self.TV = state["TV"] self.TI = state["TI"] self.IE = state["IE"] epoch = state["epoch"] ppl = state["ppl"] print "restore state from file '%s' on epoch %d with ppl: %s" % (filename, epoch, str(ppl)) if __name__ == "__main__": a = np.arange(6).reshape([2,3]).astype(np.float32) print np.sum(a, axis=1, keepdims=True) print probNormalize(a)
function T_plotting = CalculatePlottingMatrix(T_new,x_intervals,y_intervals) a = 1; for x_index = 2:1:(x_intervals-1) b = 1; for y_index = 2:1:(y_intervals-1) T_plotting(a,b) = T_new(x_index,y_index); b = b+1; end a = a+1; end end
[STATEMENT] lemma fin_chain_on_path3: assumes "[f\<leadsto>X]" "finite X" "a\<in>X" "b\<in>X" "a\<noteq>b" shows "X \<subseteq> path_of a b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] let ?ab = "path_of a b" [PROOF STATE] proof (state) goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] obtain P where P: "P\<in>\<P>" "X\<subseteq>P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>P. \<lbrakk>P \<in> \<P>; X \<subseteq> P\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using fin_chain_on_path2[OF assms(1,2)] [PROOF STATE] proof (prove) using this: \<exists>P\<in>\<P>. X \<subseteq> P goal (1 subgoal): 1. (\<And>P. \<lbrakk>P \<in> \<P>; X \<subseteq> P\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: P \<in> \<P> X \<subseteq> P goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] have "path P a b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. path P a b [PROOF STEP] using P assms(3-5) [PROOF STATE] proof (prove) using this: P \<in> \<P> X \<subseteq> P a \<in> X b \<in> X a \<noteq> b goal (1 subgoal): 1. path P a b [PROOF STEP] by auto [PROOF STATE] proof (state) this: path P a b goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: path P a b [PROOF STEP] have "path ?ab a b" [PROOF STATE] proof (prove) using this: path P a b goal (1 subgoal): 1. path (THE ab. path ab a b) a b [PROOF STEP] using path_of_ex [PROOF STATE] proof (prove) using this: path P a b path (THE ab. path ab ?a ?b) ?a ?b = (\<exists>Q. path Q ?a ?b) goal (1 subgoal): 1. path (THE ab. path ab a b) a b [PROOF STEP] by blast [PROOF STATE] proof (state) this: path (THE ab. path ab a b) a b goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] hence "?ab = P" [PROOF STATE] proof (prove) using this: path (THE ab. path ab a b) a b goal (1 subgoal): 1. (THE ab. path ab a b) = P [PROOF STEP] using eq_paths \<open>path P a b\<close> [PROOF STATE] proof (prove) using this: path (THE ab. path ab a b) a b \<lbrakk>?P \<in> \<P>; ?Q \<in> \<P>; ?a \<in> ?P; ?b \<in> ?P; ?a \<in> ?Q; ?b \<in> ?Q; ?a \<noteq> ?b\<rbrakk> \<Longrightarrow> ?P = ?Q path P a b goal (1 subgoal): 1. (THE ab. path ab a b) = P [PROOF STEP] by auto [PROOF STATE] proof (state) this: (THE ab. path ab a b) = P goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] thus "X \<subseteq> path_of a b" [PROOF STATE] proof (prove) using this: (THE ab. path ab a b) = P goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] using P [PROOF STATE] proof (prove) using this: (THE ab. path ab a b) = P P \<in> \<P> X \<subseteq> P goal (1 subgoal): 1. X \<subseteq> (THE ab. path ab a b) [PROOF STEP] by simp [PROOF STATE] proof (state) this: X \<subseteq> (THE ab. path ab a b) goal: No subgoals! [PROOF STEP] qed
program ex21 implicit none integer, parameter :: rk = selected_real_kind(15,300) real(rk), allocatable :: A(:,:) real(rk), allocatable :: B(:,:) integer :: i, j allocate(A(20,20), B(20,20)) A = 42.0_rk B = 84.0_rk call swap(A, B) deallocate(A, B) contains elemental subroutine swap(a, b) real(rk), intent(out) :: a, b real(rk) :: work work = a a = b b = work end subroutine swap end program ex21
The legal representatives of The Law Office of Benjamin Hartford are regarded as professional and experienced criminal defense attorneys in the Boulder area. We have been providing counsel to our clients throughout the Boulder area for over 15 years. In this time, we have developed a unique view on the way we handle vehicular assault cases. Our firm will not sleep until our client in the Boulder area is receiving deserved representation in his or her vehicular assault case. Whatever charges you are facing, trust the advisors at The Law Office of Benjamin Hartford. Here at The Law Office of Benjamin Hartford, a defense attorney will earnestly and aggressively defend your rights. With many of our lawyers holding 15 years of experience, your rights will be properly considered, and your case will be treated with the professional focus it deserves. Our firm has helped dozens of Boulder area clients in their vehicular assault cases. What sets our vehicular assault representation apart from the herd is our talented ability to efficiently negotiate deals with Boulder area prosecutors. At The Law Office of Benjamin Hartford, our savvy vehicular assault approach chips away at the case of the Boulder prosecution; finding their weaknesses can leave the courts open to dropping or reducing your criminal charges and recommending a lighter sentence. You need a law firm that is entirely committed to its clients' vehicular assault case and that is what you will receive from The Law Office of Benjamin Hartford. We are trained to provide you with the highest level of customer service and confidentiality in the Boulder community. No questions you have, big or small, will ever go unanswered with The Law Office of Benjamin Hartford. Throughout our 15 years of practicing defense law, we have learned that honest, direct, and discrete client service does not end with the law. The Law Office of Benjamin Hartford will be with you as counselors and fierce legal advocates at every step of your legal proceedings. Please feel free to contact us today using the information below to discuss any aspect of your case.
--------------------------------------------------------------------- -- This file contains the definition of heterogenous equality and -- -- related facts. A lot of this code is old, and could be written -- -- better. This equality is mainly used for object equivalence. -- -- -- -- Some of it came from the paper: -- -- "Monads Need Not Be Endofunctors" by Altenkirch et al. -- -- -- -- See: http://www.cs.nott.ac.uk/~txa/publ/Relative_Monads.pdf -- --------------------------------------------------------------------- module Equality.Eq where open import Level open import Relation.Relation open import Relation.Binary.PropositionalEquality public renaming (sym to prop-sym ; trans to prop-trans; refl to prop-refl) data _≅_ {l : Level} {A : Set l} (a : A) : {A' : Set l} → A' → Set l where refl : a ≅ a postulate ext : ∀{i j}{A : Set i}{B B' : A → Set j}{f : ∀ a → B a}{g : ∀ a → B' a} → (∀ a → f a ≅ g a) → f ≅ g postulate prop-ext : ∀{i j}{A : Set i}{B : A → Set j}{f : ∀ a → B a}{g : ∀ a → B a} → (∀ a → f a ≡ g a) → f ≡ g ≅-to-≡ : ∀{l : Level}{A : Set l}{a b : A} → a ≅ b → a ≡ b ≅-to-≡ refl = prop-refl -- this could just be derived from ext postulate iext : ∀{i j}{A : Set i}{B B' : A → Set j}{f : ∀ {a} → B a}{g : ∀{a} → B' a} → (∀ a → f {a} ≅ g {a}) → _≅_ {_}{ {a : A} → B a} f { {a : A} → B' a} g sym : ∀{l : Level}{A : Set l }{a b : A} → a ≅ b → b ≅ a sym refl = refl trans : ∀{l : Level}{A : Set l}{a b c : A} → a ≅ b → b ≅ c → a ≅ c trans refl refl = refl isEqRel : ∀{l : Level}{A : Set l} → EqRel {A = A} (λ x y → x ≅ y) isEqRel {l} {A} = record { parEqPf = record { symPf = sym; transPf = trans }; refPf = refl } ir : ∀{l : Level}{A A' : Set l}{a : A}{a' : A'}{p q : a ≅ a'} → p ≅ q ir {p = refl}{q = refl} = refl eqApp : ∀{l l' : Level}{A : Set l}{B : Set l'}{f : A → B}{b c : A} → b ≅ c → (f b) ≅ (f c) eqApp refl = refl subst≅ : {l l' : Level}{A : Set l}{a b : A}{P : A → Set l'} → a ≅ b → P a → P b subst≅ refl x = x -- Cite from relative monads paper. deqApp : ∀{l : Level}{A : Set l}{B : A → Set l}(f : ∀ a → B a){a a' : A} → a ≅ a' → f a ≅ f a' deqApp f refl = refl feqApp : ∀{l l' : Level}{A : Set l}{B : Set l'}{f f' : A → B}{b c : A} → f ≅ f' → b ≅ c → (f b) ≅ (f' c) feqApp refl refl = refl ifeqApp : ∀{i j}{A : Set i}{B : A → Set j}{f f' : {x : A} → B x}(a : A) → _≅_ {_}{ {a : A} → B a} f { {a : A} → B a} f' → f {a} ≅ f' {a} ifeqApp a refl = refl ieqApp : ∀{x y}{A : Set x}{B : A → Set y}(f : ∀ {a} → B a){a a' : A} → a ≅ a' → f {a} ≅ f {a'} ieqApp f refl = refl -- Cite from relative monads paper. eqApp2 : ∀{i j k}{A : Set i}{B : A → Set j}{C : Set k}{a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → (f : (a : A) → B a → C) → f a b ≅ f a' b' eqApp2 refl refl f = refl eqApp3 : ∀{x y z w}{A : Set x}{B : A → Set y}{C : (a : A) → B a → Set z}{E : Set w} (f : (a : A)(b : B a)(c : C a b) → E) → {a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → {c : C a b}{c' : C a' b'} → c ≅ c' → f a b c ≅ f a' b' c' eqApp3 f refl refl refl = refl depfeqApp3a : ∀{l}{A : Set l}{B : Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B)(z : C x) → D) → (f' : (x : A)(y : B)(z : C x) → D) → f ≅ f' → {a : A}{b : B} {c : C a} → f a b c ≅ f' a b c depfeqApp3a {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3b : ∀{l}{A : Set l}{B : A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x)(z : C x) → D) → (f' : (x : A)(y : B x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a} {c : C a} → f a b c ≅ f' a b c depfeqApp3b {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3c : ∀{l}{A : Set l}{B : A → A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x x)(z : C x) → D) → (f' : (x : A)(y : B x x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a a} {c : C a} → f a b c ≅ f' a b c depfeqApp3c {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3d : ∀{l}{A : Set l}{B : A → A → Set (suc l)}{C : A → A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x x)(z : C x x) → D) → (f' : (x : A)(y : B x x)(z : C x x) → D) → f ≅ f' → {a : A}{b : B a a} {c : C a a} → f a b c ≅ f' a b c depfeqApp3d {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3e : ∀{l}{A : Set l}{B : Set (suc l)}{C : A → A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B)(z : C x x) → D) → (f' : (x : A)(y : B)(z : C x x) → D) → f ≅ f' → {a : A}{b : B} {c : C a a} → f a b c ≅ f' a b c depfeqApp3e {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqAppa : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''}{a : A} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D x y) → f ≅ f' → f a ≅ f' a depfeqAppa {l}{l'}{l''}{l'''}{A}{B}{C}{D}{a} f f' p = eqApp {f = λ h → h a} p depfeqApp2a : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''}{a : A} (f : (y : B)(z : C a y) → D a y) → (f' : (y : B)(z : C a y) → D a y) → f ≅ f' → {b : B} {c : C a b} → f b c ≅ f' b c depfeqApp2a f f' p {b} {c} = feqApp {f = f b} {f' = f' b} (eqApp {f = λ h → h b} p) refl depfeqApp3f : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D x y) → f ≅ f' → {a : A}{b : B} {c : C a b} → f a b c ≅ f' a b c depfeqApp3f {_}{_}{_}{_}{A}{B}{C}{D} f f' p {a}{b}{c} = depfeqApp2a {A = A} {B = B}{C = λ o1 o2 → C o1 o2} {D = λ o1₁ o2₁ → D o1₁ o2₁} (f a) (f' a) (eqApp {f = λ h → h a} p) {b} {c} depfeqApp3g : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D D' : A → B → Set l'''} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D' x y) → D ≅ D' → f ≅ f' → {a : A}{b : B} {c : C a b} → f a b c ≅ f' a b c depfeqApp3g {_}{_}{_}{_}{A}{B}{C}{D} f f' refl p {a}{b}{c} = depfeqApp2a {A = A} {B = B} {C = λ o1₁ o2₁ → C o1₁ o2₁} {D = λ o1 o2 → D o1 o2} (f a) (f' a) (eqApp {f = λ h → h a} p) {b} {c} idepfeqApp2a : ∀{l l' l'' l''' l''''}{A : Set l}{B : Set l'}{C : Set l''}{D : A → B → C → Set l'''}{E : A → B → C → Set l''''}{a : A} (f : {x : B}{y : C}(z : D a x y) → E a x y) → (f' : {x : B}{y : C}(z : D a x y) → E a x y) → (∀{x y} → f {x}{y} ≅ f' {x}{y}) → {b : B}{c : C}{m : D a b c} → f {b}{c} m ≅ f' {b} {c} m idepfeqApp2a {l}{l'}{l''}{l'''}{l''''}{A}{B}{C}{D}{E}{a} f f' p {b}{c}{m} = feqApp {f = f {b} {c}} {f' = f' {b} {c}} {m} {m} (ext (λ h → feqApp {f = f {b} {c}} {f' = f' {b} {c}} {h} {h} (p {b}{c}) refl)) refl depfeqApp2b : ∀{l l' l''}{A : Set l}{D : A → A → Set l'}{E E' : A → A → Set l''} (f : (x : A)(y : A)(z : A) → (m1 : D y z) → (m2 : D x y) → E x z) → {f' : (x : A)(y : A)(z : A) → (m1 : D y z) → (m2 : D x y) → E' x z} → E ≅ E' → f ≅ f' → {a a' b b' c c' : A}{m1 : D b c}{m2 : D a b}{m1' : D b' c'}{m2' : D a' b'} → a ≅ a' → b ≅ b' → c ≅ c' → m1 ≅ m1' → m2 ≅ m2' → f a b c m1 m2 ≅ f' a' b' c' m1' m2' depfeqApp2b {_}{_}{_}{A}{D}{E} f refl refl {a = a}{b = b}{c = c}{m1 = m1}{m2 = m2} refl refl refl refl refl = eqApp {f = f a b c m1} {m2}{m2} refl feqApp3 : ∀{l}{A : Set l}{B : A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x)(z : C x) → D) → (f' : (x : A)(y : B x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a} {c : C a} → f a b c ≅ f' a b c feqApp3 {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl coerce : ∀{l}{A B : Set l} → A ≅ B → A → B coerce refl a = a p : ∀{m}{A B : Set m}{a : A}{b : B} → (q : B ≅ A) → _≅_ {m} {A} a {A} (coerce q b) → _≅_ {m} {A} a {B} b p refl refl = refl eqApp4 : ∀{x y z v w}{A : Set x}{B : A → Set y}{C : (a : A) → B a → Set z}{D : (a : A)(b : B a) → C a b → Set v}{E : Set w} (f : (a : A)(b : B a)(c : C a b) → D a b c → E) → {a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → {c : C a b}{c' : C a' b'} → c ≅ c' → {d : D a b c}{d' : D a' b' c'} → d ≅ d' → f a b c d ≅ f a' b' c' d' eqApp4 f refl refl refl refl = refl funCong : ∀{l m : Level}{A : Set l}{B : Set m}{f g : A → B}{a : A}{b : B} → (p : f ≅ g) → (q : f a ≅ b) → (w : g a ≅ b) → q ≅ w funCong refl q w = ir funCong2 : ∀{l : Level}{A B B' X Y : Set l}{f : ∀{X Y} → A → B}{g : ∀{X Y} → A → B'}{a : A}{b : B} → (r : B ≅ B') → (p : (λ {X}{Y} → f {X}{Y}) ≅ (λ {X}{Y} → g {X}{Y})) → (q : f {X}{Y} a ≅ b) → (w : g {X}{Y} a ≅ b) → q ≅ w funCong2 refl refl q w = ir fixtypes : ∀{x}{A A' : Set x}{a a' : A}{a'' a''' : A'}{p : a ≅ a'}{q : a'' ≅ a'''} → a ≅ a'' → a' ≅ a''' → p ≅ q fixtypes refl refl = ir
State Before: R : Type u inst✝ : Ring R G H : ModuleCat R f✝ : G ⟶ H M N : ModuleCat R f : M ⟶ N x y : ↑N m : ↑M w : x = y + ↑f m ⊢ ↑(cokernel.π f) x = ↑(cokernel.π f) y State After: R : Type u inst✝ : Ring R G H : ModuleCat R f✝ : G ⟶ H M N : ModuleCat R f : M ⟶ N y : ↑N m : ↑M ⊢ ↑(cokernel.π f) (y + ↑f m) = ↑(cokernel.π f) y Tactic: subst w State Before: R : Type u inst✝ : Ring R G H : ModuleCat R f✝ : G ⟶ H M N : ModuleCat R f : M ⟶ N y : ↑N m : ↑M ⊢ ↑(cokernel.π f) (y + ↑f m) = ↑(cokernel.π f) y State After: no goals Tactic: simpa only [map_add, add_right_eq_self] using cokernel.condition_apply f m
#redirect Rick Schubert
If $s$ is a convex set and $a, b \in s$, then for any $u \in [0, 1]$, $(1 - u)a + ub \in s$.
{- This second-order signature was created from the following second-order syntax description: syntax Monoid | M type * : 0-ary term unit : * | ε add : * * -> * | _⊕_ l20 theory (εU⊕ᴸ) a |> add (unit, a) = a (εU⊕ᴿ) a |> add (a, unit) = a (⊕A) a b c |> add (add(a, b), c) = add (a, add(b, c)) -} module Monoid.Signature where open import SOAS.Context open import SOAS.Common open import SOAS.Syntax.Signature *T public open import SOAS.Syntax.Build *T public -- Operator symbols data Mₒ : Set where unitₒ addₒ : Mₒ -- Term signature M:Sig : Signature Mₒ M:Sig = sig λ { unitₒ → ⟼₀ * ; addₒ → (⊢₀ *) , (⊢₀ *) ⟼₂ * } open Signature M:Sig public
Formal statement is: lemma uniformly_continuous_on_diff[continuous_intros]: fixes f :: "'a::metric_space \<Rightarrow> 'b::real_normed_vector" assumes "uniformly_continuous_on s f" and "uniformly_continuous_on s g" shows "uniformly_continuous_on s (\<lambda>x. f x - g x)" Informal statement is: If $f$ and $g$ are uniformly continuous on a set $S$, then $f - g$ is uniformly continuous on $S$.
The closure of the set of all real numbers less than $b$ is the set of all real numbers less than or equal to $b$.
module type_oscillator_model use mod_kinds, only: rk, ik use mod_constants, only: ZERO, ONE, TWO, PI use mod_rigid_body_motion, only: rigid_body_motion_disp_old, rigid_body_motion_disp_new, & rigid_body_motion_vel, rigid_body_t0, rigid_body_t1 use mod_chidg_mpi, only: IRANK, GLOBAL_MASTER implicit none type :: oscillator_model_t ! Linearly damped oscillator ODE model ! mass*x'' + damping_coeff*x' + stiffness_coeff*x = external_force real(rk) :: mass = ONE real(rk) :: damping_coeff(3) = ONE real(rk) :: stiffness_coeff(3) = ONE real(rk) :: external_forces(3) = ZERO real(rk) :: undamped_angular_frequency(3) real(rk) :: undamped_natural_frequency(3) real(rk) :: damping_factor(3) real(rk) :: minimum_stable_timestep character(:), allocatable :: damping_type real(rk) :: eq_pos(3) ! Equilibrium position real(rk) :: pos(3) ! Displaced position real(rk) :: disp(2,3) ! Displacement real(rk) :: vel(2,3) ! Velocity real(rk), allocatable, dimension(:,:) :: history_pos(:,:), history_vel(:,:), history_force(:,:) contains procedure :: init procedure :: set_external_forces procedure :: update_disp procedure :: update_vel procedure :: update_oscillator_step procedure :: update_oscillator_subcycle_step end type oscillator_model_t contains subroutine init(self, mass_in, damping_coeff_in, stiffness_coeff_in, initial_displacement_in, initial_velocity_in) class(oscillator_model_t), intent(inout) :: self real(rk),intent(in),optional :: mass_in real(rk),intent(in),optional :: damping_coeff_in(3) real(rk),intent(in),optional :: stiffness_coeff_in(3) real(rk),intent(in),optional :: initial_displacement_in(3) real(rk),intent(in),optional :: initial_velocity_in(3) real(rk) :: tol real(rk) :: mass, damping_coeff(3), stiffness_coeff(3), initial_displacement(3), initial_velocity(3), external_forces(3),t0 integer(ik) :: unit, msg, myunit logical :: file_exists, exists namelist /viv_cylinder/ mass,& damping_coeff, & stiffness_coeff, & initial_displacement, & initial_velocity tol = 1.0e-14 self%disp = ZERO self%pos = ZERO self%vel = ZERO self%external_forces = ZERO if (present(mass_in)) then self%mass = mass_in end if if (present(damping_coeff_in)) then self%damping_coeff = damping_coeff_in end if if (present(stiffness_coeff_in)) then self%stiffness_coeff = stiffness_coeff_in end if if (present(initial_displacement_in)) then self%disp(1,:) = initial_displacement_in end if if (present(initial_velocity_in)) then self%vel(1,:) = initial_velocity_in end if ! ! Check if input from 'models.nml' is available. ! 1: if available, read and set self%mu ! 2: if not available, do nothing and mu retains default value ! inquire(file='structural_models.nml', exist=file_exists) if (file_exists) then open(newunit=unit,form='formatted',file='structural_models.nml') read(unit,nml=viv_cylinder,iostat=msg) if (msg == 0) self%mass = mass if (msg == 0) self%damping_coeff = damping_coeff if (msg == 0) self%stiffness_coeff = stiffness_coeff if (msg == 0) self%disp(1,:) = initial_displacement if (msg == 0) self%vel(1,:) = initial_velocity close(unit) end if self%undamped_angular_frequency = sqrt(self%stiffness_coeff/self%mass) self%undamped_natural_frequency = self%undamped_angular_frequency/(TWO*PI) self%damping_factor = self%damping_coeff/(TWO*sqrt(self%mass*self%stiffness_coeff)) ! ! Compute the minimum stable timestep size for the lepfrog algorithm. ! dt < 2/ang_freq ! self%minimum_stable_timestep = TWO/(maxval(self%undamped_angular_frequency)) if (maxval(self%damping_factor) > ONE + tol) then self%damping_type = 'overdamped' else if (maxval(self%damping_factor) < ONE-tol) then self%damping_type = 'underdamped' else self%damping_type = 'critically damped' end if ! print *, 'Oscillator mass' ! print *, self%mass ! print *, 'Oscillator damping coefficients' ! print *, self%damping_coeff ! print *, 'Oscillator stiffness coefficients' ! print *, self%stiffness_coeff ! print *, 'Oscillaing cylinder damping type:' ! print *, self%damping_type ! ! print *, 'Oscillating cylinder minimum stable time step size:' ! print *, self%minimum_stable_timestep rigid_body_motion_disp_new = self%disp(1,:) rigid_body_motion_vel = self%vel(1,:) external_forces = ZERO t0 = ZERO ! ! Write initial state to file to files ! ! ! if (IRANK == GLOBAL_MASTER) then ! inquire(file="viv_output.txt", exist=exists) ! if (exists) then ! open(newunit=myunit, file="viv_output.txt", status="old", position="append",action="write") ! else ! open(newunit=myunit, file="viv_output.txt", status="new",action="write") ! end if ! write(myunit,*) t0, rigid_body_motion_disp_new(1), rigid_body_motion_disp_new(2), & ! rigid_body_motion_vel(1), rigid_body_motion_vel(2), & ! external_forces(1),external_forces(2) ! close(myunit) ! end if end subroutine init subroutine set_external_forces(self, external_forces) class(oscillator_model_t) :: self real(rk) :: external_forces(3) self%external_forces = external_forces end subroutine set_external_forces subroutine update_disp(self,dt_struct) class(oscillator_model_t) :: self real(rk) :: dt_struct self%disp(2,:) = self%disp(1,:) + dt_struct*self%vel(1,:) self%disp(1,:) = self%disp(2,:) end subroutine update_disp subroutine update_vel(self,dt_struct) class(oscillator_model_t) :: self real(rk) :: dt_struct real(rk) :: gam(3), mass ! ! Special version of the Leapfrog algorithm for linear damping ! gam = self%damping_coeff mass = self%mass self%vel(2,:) = ((ONE - gam*dt_struct/(TWO*mass))*self%vel(1,:) + & dt_struct*(self%external_forces-self%stiffness_coeff*self%disp(1,:))/mass)/ & (ONE + gam*dt_struct/(TWO*mass)) self%vel(1,:) = self%vel(2,:) end subroutine update_vel subroutine update_oscillator_subcycle_step(self, dt_struct, external_forces) class(oscillator_model_t) :: self real(rk) :: dt_struct real(rk) :: external_forces(3) call self%set_external_forces(external_forces) call self%update_vel(dt_struct) call self%update_disp(dt_struct) end subroutine update_oscillator_subcycle_step subroutine update_oscillator_step(self, dt_fluid, t0_in, external_forces) class(oscillator_model_t) :: self real(rk) :: dt_fluid real(rk) :: t0_in real(rk) :: external_forces(3) real(rk) :: dt_struct integer(ik) :: nsteps, istep, max_steps integer(ik) :: myunit logical :: exists integer(ik) :: unit, msg logical :: file_exists real(rk) :: mass real(rk), dimension(3) :: damping_coeff, stiffness_coeff, initial_displacement, initial_velocity namelist /viv_cylinder/ mass,& damping_coeff, & stiffness_coeff, & initial_displacement, & initial_velocity ! ! Perform update ! rigid_body_t0 = t0_in rigid_body_t1 = t0_in+dt_fluid rigid_body_motion_disp_old = rigid_body_motion_disp_new ! Check stability of the initial time step and decrease it until it becomes stable dt_struct = dt_fluid nsteps = 1 max_steps = 1000 do while ((dt_struct> 0.1_rk*self%minimum_stable_timestep) .and. (nsteps < max_steps)) dt_struct = dt_struct/TWO nsteps = nsteps*2 end do do istep = 1, nsteps call self%update_oscillator_subcycle_step(dt_struct, external_forces) end do !Force one DOF motion self%disp(1,1) = ZERO self%disp(1,3) = ZERO self%vel(1,1) = ZERO self%vel(1,3) = ZERO rigid_body_motion_disp_new = self%disp(1,:) rigid_body_motion_vel = self%vel(1,:) ! ! Write to files ! if (IRANK == GLOBAL_MASTER) then inquire(file="viv_output.txt", exist=exists) if (exists) then open(newunit=myunit, file="viv_output.txt", status="old", position="append",action="write") else open(newunit=myunit, file="viv_output.txt", status="new",action="write") end if write(myunit,*) t0_in, rigid_body_motion_disp_new(1), rigid_body_motion_disp_new(2), & rigid_body_motion_vel(1), rigid_body_motion_vel(2), & external_forces(1),external_forces(2) close(myunit) end if ! ! Write the new position and velocity to models.nml for restart purposes ! mass = self%mass damping_coeff = self%damping_coeff(1:3) stiffness_coeff = self%stiffness_coeff(1:3) initial_displacement = self%disp(1,:) initial_velocity = self%vel(1,:) if (IRANK == GLOBAL_MASTER) then inquire(file='structural_models.nml', exist=file_exists) if (file_exists) then open(newunit=unit,form='formatted',file='structural_models.nml') write(unit,nml=viv_cylinder,iostat=msg) close(unit) end if end if end subroutine update_oscillator_step end module type_oscillator_model
------------------------------------------------------------------------ -- Function setoids and related constructions ------------------------------------------------------------------------ module Relation.Binary.FunctionSetoid where open import Data.Function open import Relation.Binary infixr 0 _↝_ _⟶_ _⇨_ _≡⇨_ -- A logical relation (i.e. a relation which relates functions which -- map related things to related things). _↝_ : ∀ {A B} → (∼₁ : Rel A) (∼₂ : Rel B) → Rel (A → B) _∼₁_ ↝ _∼₂_ = λ f g → ∀ {x y} → x ∼₁ y → f x ∼₂ g y -- Functions which preserve equality. record _⟶_ (From To : Setoid) : Set where open Setoid infixl 5 _⟨$⟩_ field _⟨$⟩_ : carrier From → carrier To pres : _⟨$⟩_ Preserves _≈_ From ⟶ _≈_ To open _⟶_ public ↝-isEquivalence : ∀ {A B C} {∼₁ : Rel A} {∼₂ : Rel B} (fun : C → (A → B)) → (∀ f → fun f Preserves ∼₁ ⟶ ∼₂) → IsEquivalence ∼₁ → IsEquivalence ∼₂ → IsEquivalence ((∼₁ ↝ ∼₂) on₁ fun) ↝-isEquivalence _ pres eq₁ eq₂ = record { refl = λ {f} x∼₁y → pres f x∼₁y ; sym = λ f∼g x∼y → sym eq₂ (f∼g (sym eq₁ x∼y)) ; trans = λ f∼g g∼h x∼y → trans eq₂ (f∼g (refl eq₁)) (g∼h x∼y) } where open IsEquivalence -- Function setoids. _⇨_ : Setoid → Setoid → Setoid S₁ ⇨ S₂ = record { carrier = S₁ ⟶ S₂ ; _≈_ = (_≈_ S₁ ↝ _≈_ S₂) on₁ _⟨$⟩_ ; isEquivalence = ↝-isEquivalence _⟨$⟩_ pres (isEquivalence S₁) (isEquivalence S₂) } where open Setoid; open _⟶_ -- A generalised variant of (_↝_ _≡_). ≡↝ : ∀ {A} {B : A → Set} → (∀ x → Rel (B x)) → Rel ((x : A) → B x) ≡↝ R = λ f g → ∀ x → R x (f x) (g x) ≡↝-isEquivalence : {A : Set} {B : A → Set} {R : ∀ x → Rel (B x)} → (∀ x → IsEquivalence (R x)) → IsEquivalence (≡↝ R) ≡↝-isEquivalence eq = record { refl = λ _ → refl ; sym = λ f∼g x → sym (f∼g x) ; trans = λ f∼g g∼h x → trans (f∼g x) (g∼h x) } where open module Eq {x} = IsEquivalence (eq x) _≡⇨_ : (A : Set) → (A → Setoid) → Setoid A ≡⇨ S = record { carrier = (x : A) → carrier (S x) ; _≈_ = ≡↝ (λ x → _≈_ (S x)) ; isEquivalence = ≡↝-isEquivalence (λ x → isEquivalence (S x)) } where open Setoid
subroutine gdpm_corr (iflg) !*********************************************************************** ! Copyright, 1993, 2004, The Regents of the University of California. ! This program was prepared by the Regents of the University of ! California at Los Alamos National Laboratory (the University) under ! contract No. W-7405-ENG-36 with the U.S. Department of Energy (DOE). ! All rights in the program are reserved by the DOE and the University. ! Permission is granted to the public to copy and use this software ! without charge, provided that this Notice and any statement of ! authorship are reproduced on all copies. Neither the U.S. Government ! nor the University makes any warranty, express or implied, or ! assumes any liability or responsibility for the use of this software. C*********************************************************************** CD1 CD1 PURPOSE CD1 CD1 Manage gdpm connections when simulating rate-limited conditions. CD1 IE make the connection value large for those nodes that serve only CD1 to link gdpm nodes (diffusion only) to flow field CD1 C*********************************************************************** CD2 CD2 REVISION HISTORY CD2 CD2 Revision ECD CD2 Date Programmer Number Comments CD2 CD2 01-JAN-2007 G. Zyvoloski Initial implementation. CD2 CD2 C*********************************************************************** CD3 CD3 INTERFACES CD3 CD3 Formal Calling Parameters CD3 CD3 Identifier Type Use Description CD3 CD3 iz INT I Flag to indicate type of boundary CD3 condition modification to be performed CD3 CD3 Interface Tables CD3 CD3 None CD3 CD3 Files CD3 CD3 None CD3 C*********************************************************************** CD4 CD4 GLOBAL OBJECTS CD4 CD4 Global Constants CD4 CD4 None CD4 CD4 Global Types CD4 CD4 None CD4 CD4 Global Variables CD4 CD4 COMMON CD4 Identifier Type Block Description CD4 CD4 CD4 Global Subprograms CD4 CD4 None CD4 C*********************************************************************** CD5 CD5 LOCAL IDENTIFIERS CD5 CD5 Local Constants CD5 CD5 Identifier Type Description CD5 CD5 sx1bc REAL*8 /1.e12/ CD5 CD5 Local Types CD5 CD5 None CD5 CD5 Local variables CD5 CD5 Identifier Type Description CD5 CD5 cqtout REAL*8 Total produced tracer mass for each species at CD5 the boundary CD5 cqtin REAL*8 Total lost tracer mass for each species at CD5 the boundary CD5 cqtrxn REAL*8 Total produced tracer mass for each species at CD5 the boundary (reaction) CD5 i INT Loop index CD5 j INT Loop index CD5 qtb REAL*8 Total outflow for time step at the boundary CD5 qtcb REAL*8 Total mass injected at the boundary CD5 qteb REAL*8 Total energy outflow for time step at the CD5 boundary CD5 CD5 Local Subprograms CD5 CD5 None CD5 C*********************************************************************** CD6 CD6 FUNCTIONAL DESCRIPTION CD6 CD6 CD6 C*********************************************************************** CD7 CD7 ASSUMPTIONS AND LIMITATIONS CD7 CD7 None CD7 C*********************************************************************** CD8 CD8 SPECIAL COMMENTS CD8 CD8 Requirements from SDN: 10086-RD-2.20-00 CD8 SOFTWARE REQUIREMENTS DOCUMENT (RD) for the CD8 FEHM Application Version 2.20 CD8 C*********************************************************************** CD9 CD9 REQUIREMENTS TRACEABILITY CD9 CD9 ????? matrix pre-processing CD9 C*********************************************************************** CDA CDA REFERENCES CDA CDA None CDA C*********************************************************************** CPS CPS PSEUDOCODE CPS CPS BEGIN bcon CPS CPS CPS END bcon CPS C*********************************************************************** c c adjust connections between some nodes and its neighbors c intended to be used with gdpm macro but might have general utility c use combi use comdti use comai use comei use davidi use comki implicit none integer ii, i, iflg, jj, i1, i2, i3, i4, kb, nmat_id, neqp1 integer kk, ipiv, ipiv1, kc integer, allocatable :: igdpm_rate_nodes_dum(:) character*20 dummy logical null1, sheat_flag, stran_flag real*8 aijsave, aiidiff, corr_tol parameter (corr_tol = 1.e-18) if(igdpm_rate.le.0) return if (iflg.eq.0) then c c read nodes and processes to be modified c allocate(igdpm_rate_nodes(n0)) igdpm_rate = 1 macro = 'cgdp' read (inpt, '(a80)') wdd1 select case (wdd1(1:4)) case ('heat') read (wdd1, *) dummy,val_conh val_conh = max(val_conh*1.d-6,corr_tol) sheat_flag = .true. igdpm_rate = 1 case('tran') read (wdd1, *) dummy, val_conh val_conh = max(val_conh*1.d-6,corr_tol) stran_flag = .true. igdpm_rate = 2 end select igroup = 1 narrays = 1 itype(1) = 4 default(1) = 0 c c read in initial node identifier here c call initdata2( inpt, ischk, n0, narrays, & itype, default, macroread(8), macro, igroup, ireturn, & i4_1 = igdpm_rate_nodes(1:n0)) else if (iflg .eq. -1) then c c expand the array size needed to store next nearest nodes c just counting nodes now c do i= 1,n0 if(igdpm_rate_nodes(i).gt.0) then i1 = nelm(i)+1 i2 = nelm(i+1) do jj = i1,i2 kb = nelm(jj) if(igdpm_rate_nodes(kb).eq.0) then c igdpm_rate_nodes(kb) = -1 endif enddo endif enddo ngdpm_rate = 0 kc = 0 do i= 1,n0 if(igdpm_rate_nodes(i).gt.0) then ngdpm_rate = ngdpm_rate + 1 else if(igdpm_rate_nodes(i).lt.0) then kc = kc+1 endif enddo if (iout .ne. 0) write (iout,*)'gdpm primary nodes ', & ngdpm_rate, 'next neighbor nodes ', kc else if (iflg .eq. 1) then c c remove resistance from identified nodes c c should be called just before array normalization and order switching c neqp1 = neq+1 if(igdpm_rate.eq.1) then c heat conduction terms do i = 1,n0 if(igdpm_rate_nodes(i).gt.0) then call gdpm_geneqh(i) endif enddo else if(igdpm_rate.eq.2) then endif end if end
[STATEMENT] lemma mirror_\<alpha>_\<beta>: assumes lp: "iszlfm p (a#bs)" shows "(Inum (real_of_int (i::int)#bs)) ` set (\<alpha> p) = (Inum (real_of_int i#bs)) ` set (\<beta> (mirror p))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Inum (real_of_int i # bs) ` set (\<alpha> p) = Inum (real_of_int i # bs) ` set (\<beta> (mirror p)) [PROOF STEP] using lp [PROOF STATE] proof (prove) using this: iszlfm p (a # bs) goal (1 subgoal): 1. Inum (real_of_int i # bs) ` set (\<alpha> p) = Inum (real_of_int i # bs) ` set (\<beta> (mirror p)) [PROOF STEP] by (induct p rule: mirror.induct) auto
lemma translate_inj_on: fixes A :: "'a::ab_group_add set" shows "inj_on (\<lambda>x. a + x) A"
In response to the growing demand for skilled professionals in health professions, YouthBuild Just-A-Start has committee to broadening its horizons by providing new career training for healthcare related fields. Recently on Wednesday June 6, 2012 YouthBuild Just-A-Start was featured in a YouthBuild USA film screening, "Building Career Opportunities in Healthcare". The film captures current participants and alumni from YouthBuild Just-A-Start as they explore and pursue career pathways withing the health care industry. Developing pathways to health care related careers has been recognized by YouthBuild USA as a best practice for creating promising futures for our young people. While construction training remains a key component of YouthBuild programs, YouthBuild Just-A-Start remains open to an ever changing workforce environment. We are so proud of the YouthBuild Just-A-Start students and look forward to hearing about their future success. Please take a moment to view the short film below. As the Massachusetts YouthBuild Coalition continues its mission to empower underserved young people through advocacy, resource development, peer evaluation, and support, the students and staff took some time to say thank you in appreciation of public officials who have provided both financial and moral support to YouthBuild programs over the past sixteen years. This was accomplished by landscaping the State House front lawn. On Wednesday May 23rd, students and staff from six Massachusetts YouthBuild programs gathered to volunteer their service. This group committed to the landscaping project for the fourth consecutive year by planting red and white geranium flowers and impatiens. They also assisted with pruning of tree shrubs and bushes. During the lunch hour Congressman William Keating, came out to visit with the students. They had a chance to introduce themselves and inform Congressman Keating of what projects they have been working on. To wrap up the day, YouthBuild students made their way into the State House to meet with, among others, Senator Eileen Donoghue of Lowell who has been a strong supporter of YouthBuild. This was a wonderful experience and there was a great turn out. Members of the State House staff were proud see young people and adult supervisors working together to take care of the property. The students proved that they were ready to be the difference by taking a step forward and making things happen. The work at the State house showed initiative and that our youth care. Keep up the great work!
Require Export GeoCoq.Tarski_dev.Ch04_cong_bet. Section T4_1. Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}. Lemma col_permutation_1 : forall A B C,Col A B C -> Col B C A. Proof. unfold Col. intros. intuition. Qed. Lemma col_permutation_2 : forall A B C, Col A B C -> Col C A B. Proof. unfold Col. intros. intuition. Qed. Lemma col_permutation_3 : forall A B C, Col A B C -> Col C B A. Proof. unfold Col. intros. intuition. Qed. Lemma col_permutation_4 : forall A B C, Col A B C -> Col B A C. Proof. unfold Col. intros. intuition. Qed. Lemma col_permutation_5 : forall A B C, Col A B C -> Col A C B. Proof. unfold Col. intros. intuition. Qed. End T4_1. #[global] Hint Resolve bet_col col_permutation_1 col_permutation_2 col_permutation_3 col_permutation_4 col_permutation_5 : col. Ltac Col := auto 3 with col. Ltac Col5 := auto with col. Section T4_2. Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}. Lemma not_col_permutation_1 : forall (A B C : Tpoint), ~ Col A B C -> ~ Col B C A. Proof. intros. intro. apply H. Col. Qed. Lemma not_col_permutation_2 : forall (A B C : Tpoint), ~ Col A B C -> ~ Col C A B. Proof. intros. intro. apply H. Col. Qed. Lemma not_col_permutation_3 : forall (A B C : Tpoint), ~ Col A B C -> ~ Col C B A. Proof. intros. intro. apply H. Col. Qed. Lemma not_col_permutation_4 : forall (A B C : Tpoint), ~ Col A B C -> ~ Col B A C. Proof. intros. intro. apply H. Col. Qed. Lemma not_col_permutation_5 : forall (A B C : Tpoint), ~ Col A B C -> ~ Col A C B. Proof. intros. intro. apply H. Col. Qed. End T4_2. #[global] Hint Resolve not_col_permutation_1 not_col_permutation_2 not_col_permutation_3 not_col_permutation_4 not_col_permutation_5 : col. Section T4_3. Context `{Tn:Tarski_neutral_dimensionless}. (** This lemma is used by tactics for trying several permutations. *) Lemma Col_cases : forall A B C, Col A B C \/ Col A C B \/ Col B A C \/ Col B C A \/ Col C A B \/ Col C B A -> Col A B C. Proof. intros. decompose [or] H; Col. Qed. Lemma Col_perm : forall A B C, Col A B C -> Col A B C /\ Col A C B /\ Col B A C /\ Col B C A /\ Col C A B /\ Col C B A. Proof. intros. repeat split; Col. Qed. Lemma col_trivial_1 : forall A B, Col A A B. Proof. unfold Col. intros. Between. Qed. Lemma col_trivial_2 : forall A B, Col A B B. Proof. unfold Col. intros. Between. Qed. Lemma col_trivial_3 : forall A B, Col A B A. Proof. unfold Col. intros. right;Between. Qed. End T4_3. #[global] Hint Immediate col_trivial_1 col_trivial_2 col_trivial_3: col. Section T4_4. Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}. Lemma l4_13 : forall A B C A' B' C', Col A B C -> Cong_3 A B C A' B' C' -> Col A' B' C'. Proof. unfold Col. intros. decompose [or] H; eauto 6 using l4_6 with cong3. Qed. Lemma l4_14 : forall A B C A' B', Col A B C -> Cong A B A' B' -> exists C', Cong_3 A B C A' B' C'. Proof. unfold Col. intros. intuition. prolong A' B' C' B C. exists C'. assert (Cong A C A' C') by (eapply l2_11;eCong). unfold Cong_3;intuition. assert (exists C', Bet A' C' B' /\ Cong_3 A C B A' C' B') by (eapply l4_5;Between). ex_and H1 C'. exists C'. auto with cong3. prolong B' A' C' A C. exists C'. assert (Cong B C B' C') by (eapply l2_11;eBetween;Cong). unfold Cong_3;intuition. Qed. Lemma l4_16 : forall A B C D A' B' C' D', FSC A B C D A' B' C' D' -> A<>B -> Cong C D C' D'. Proof. unfold FSC. unfold Col. intros. decompose [or and] H; clear H. assert (Bet A' B' C') by (eapply l4_6;eauto). unfold Cong_3 in *; spliter. assert(OFSC A B C D A' B' C' D') by (unfold OFSC;repeat split; assumption). eapply five_segment_with_def; eauto. assert(Bet B' C' A') by (apply (l4_6 B C A B' C' A'); Cong;auto with cong3). apply (l4_2 B C A D B' C' A' D'). unfold IFSC; unfold Cong_3 in *; spliter; repeat split;Between;Cong. assert (Bet C' A' B') by (eapply (l4_6 C A B C' A' B'); auto with cong3). eapply (five_segment_with_def B A C D B' A'); unfold OFSC; unfold Cong_3 in *; spliter; repeat split; Between; Cong. Qed. Lemma l4_17 : forall A B C P Q, A<>B -> Col A B C -> Cong A P A Q -> Cong B P B Q -> Cong C P C Q. Proof. intros. assert (FSC A B C P A B C Q) by (unfold FSC; unfold Cong_3;repeat split; Cong). eapply l4_16; eauto. Qed. Lemma l4_18 : forall A B C C', A<>B -> Col A B C -> Cong A C A C' -> Cong B C B C' -> C=C'. Proof. intros. apply cong_identity with C. apply (l4_17 A B); Cong. Qed. Lemma l4_19 : forall A B C C', Bet A C B -> Cong A C A C' -> Cong B C B C' -> C=C'. Proof. intros. induction (eq_dec_points A B). treat_equalities; reflexivity. apply (l4_18 A B); Cong. auto using bet_col with col. Qed. Lemma not_col_distincts : forall A B C , ~ Col A B C -> ~ Col A B C /\ A <> B /\ B <> C /\ A <> C. Proof. intros. repeat split;(auto;intro); subst; apply H; Col. Qed. Lemma NCol_cases : forall A B C, ~ Col A B C \/ ~ Col A C B \/ ~ Col B A C \/ ~ Col B C A \/ ~ Col C A B \/ ~ Col C B A -> ~ Col A B C. Proof. intros. decompose [or] H; Col. Qed. Lemma NCol_perm : forall A B C, ~ Col A B C -> ~ Col A B C /\ ~ Col A C B /\ ~ Col B A C /\ ~ Col B C A /\ ~ Col C A B /\ ~ Col C B A. Proof. intros. repeat split; Col. Qed. Lemma col_cong_3_cong_3_eq : forall A B C A' B' C1 C2, A <>B -> Col A B C -> Cong_3 A B C A' B' C1 -> Cong_3 A B C A' B' C2 -> C1 = C2. Proof. intros A B C A' B' C1 C2 HAB HCol HCong1 HCong2. apply l4_18 with A' B'; try apply l4_13 with A B C; Col; unfold Cong_3 in *; spliter. intro; treat_equalities; intuition. apply cong_transitivity with A C; Cong. apply cong_transitivity with B C; Cong. Qed. End T4_4.
module Command %default total public export data Command : Type where TurnLeft : Command TurnRight : Command Forward : Command
% This document is part of the emcee3 project. % Copyright 2015 Dan Foreman-Mackey % % RULES OF THE GAME % % * 80 characters % * line breaks at the ends of sentences % * eqnarrys ONLY % \documentclass[12pt,preprint]{aastex} \pdfoutput=1 \usepackage{color,hyperref} \definecolor{linkcolor}{rgb}{0,0,0.5} \hypersetup{colorlinks=true,linkcolor=linkcolor,citecolor=linkcolor, filecolor=linkcolor,urlcolor=linkcolor} \usepackage{url} \usepackage{amssymb,amsmath} \usepackage{subfigure} \usepackage{booktabs} \usepackage{natbib} \bibliographystyle{apj} % Typography \newcommand{\project}[1]{\textsl{#1}} \newcommand{\license}{MIT License} \newcommand{\paper}{\textsl{Article}} \newcommand{\foreign}[1]{\emph{#1}} \newcommand{\etal}{\foreign{et\,al.}} \newcommand{\etc}{\foreign{etc.}} \newcommand{\figref}[1]{\ref{fig:#1}} \newcommand{\Fig}[1]{\figurename~\figref{#1}} \newcommand{\fig}[1]{\Fig{#1}} \newcommand{\figlabel}[1]{\label{fig:#1}} \newcommand{\Tab}[1]{Table~\ref{tab:#1}} \newcommand{\tab}[1]{\Tab{#1}} \newcommand{\tablabel}[1]{\label{tab:#1}} \newcommand{\Eq}[1]{Equation~(\ref{eq:#1})} \newcommand{\eq}[1]{\Eq{#1}} \newcommand{\eqalt}[1]{Equation~\ref{eq:#1}} \newcommand{\eqlabel}[1]{\label{eq:#1}} \newcommand{\sectionname}{Section} \newcommand{\Sect}[1]{\sectionname~\ref{sect:#1}} \newcommand{\sect}[1]{\Sect{#1}} \newcommand{\sectalt}[1]{\ref{sect:#1}} \newcommand{\App}[1]{Appendix~\ref{sect:#1}} \newcommand{\app}[1]{\App{#1}} \newcommand{\sectlabel}[1]{\label{sect:#1}} % Algorithms \usepackage{algorithm} \usepackage{algorithmicx} \usepackage[]{algpseudocode} \newcommand*\Let[2]{\State #1 $\gets$ #2} \newcommand{\Alg}[1]{Algorithm~\ref{alg:#1}} \newcommand{\alg}[1]{\Alg{#1}} \newcommand{\alglabel}[1]{\label{alg:#1}} % To-do \newcommand{\todo}[3]{{\color{#2}\emph{#1}: #3}} \newcommand{\dfmtodo}[1]{\todo{DFM}{red}{#1}} % Response to referee \definecolor{mygreen}{rgb}{0, 0.50196, 0} \newcommand{\response}[1]{#1} % \newcommand{\response}[1]{{\color{mygreen} {\bf #1}}} % Notation for this paper. \newcommand{\T}{{\ensuremath{\mathrm{T}}}} \newcommand{\bvec}[1]{{\ensuremath{\boldsymbol{#1}}}} \newcommand{\lnprob}{{\ensuremath{\mathcal{L}}}} \newcommand{\pos}{{\bvec{q}}} \newcommand{\mom}{{\bvec{p}}} \newcommand{\mass}{{\bvec{M}}} \newcommand{\normal}[2]{{\ensuremath{\mathcal{N}(#1,\,#2)}}} \begin{document} \title{% Affine-invariant Hamiltonian Monte Carlo } \newcommand{\uw}{2} \newcommand{\sagan}{3} \author{% Daniel~Foreman-Mackey\altaffilmark{1,\uw,\sagan} } \altaffiltext{1} {To whom correspondence should be addressed: \url{[email protected]}} \altaffiltext{\uw} {Astronomy Department, University of Washington, Seattle, WA 98195} \altaffiltext{\sagan} {Sagan Fellow} \begin{abstract} Hamiltonian Monte Carlo (HMC) sampling is an efficient method for drawing samples from a probability density when the gradient of the probability with respect to the parameters can be computed. We present a simple but effective affine-invariant HMC method that uses an ensemble of samplers to adaptively update the mass matrix. We demonstrate the performance of this method on some simple test cases and compare its computational cost on a real data analysis problem in exoplanet astronomy. A well-tested and efficient Python implementation is released alongside this note. \end{abstract} \keywords{% methods: data analysis --- methods: statistical } \section{Introduction} % Text. \citep{Foreman-Mackey:2013} % Adaptive: \citet{Girolami:2011, Wang:2013, Hoffman:2014} % \section{Hamiltonian Monte Carlo} Pseudocode for the standard implementation of the Hamiltonian Monte Carlo (HMC) algorithm \citep{Neal:2011} is shown in \alg{basic-hmc}. In this implementation, there are $(D^2 + D) / 2 + 2$ tuning parameters, where $D$ is the dimension of the problem. Of these parameters, $(D^2 + D) / 2$ are the elements of the positive definite mass matrix \bvec{M} and the other 2 are the step size $\epsilon$ and the number of steps $L$. Most practical applications of HMC fix the mass matrix to a constant (often set to 1) times the identity and reduce the tuning to only the two parameters $\epsilon$ and $L$. Methods have been developed to automatically tune these parameters \citep[for example][]{Hoffman:2014}. The major problem with fixing the mass matrix to be diagonal is that the \emph{units} of the input space can change the performance of the algorithm. For example, sampling from a Gaussian with different variances in the different dimensions or covariance between the parameters will be less efficient than sampling from an isotropic Gaussian. It has been demonstrated that samplers that satisfy affine invariance can be very useful for real problems in science where the dynamic range of parameters can vary by orders of magnitude \citep{Goodman:2010, Foreman-Mackey:2013}. It turns out that HMC can be simply adapted to an affine-invariant algorithm. The affine-invariant samplers proposed by \citet{Goodman:2010} sample the target density by evolving an \emph{ensemble} of parallel MCMC chains (called ``walkers'') where the instantaneous proposal for one walker is conditioned on the current locations of the other walkers, the \emph{complementary ensemble}. If the move preserves the conditional distribution of the target walker given the complementary ensemble, it will also preserve the joint distribution of the ensemble. The intuition from these proposals can be incorporated into HMC to derive an affine-invariant algorithm. \begin{algorithm} \caption{Standard implementation of a single HMC step \alglabel{basic-hmc}} \begin{algorithmic} \Function{HMCStep}{$\lnprob(\pos),\,\pos_t,\,\mass,\,\epsilon,\,L$} \State $\mom_t \sim \normal{\bvec{0}}{\mass}$ \Comment{sample the initial momentum exactly} \Let{\pos}{$\pos_t$} \State \Let{\mom}{$\mom_t + \frac{\epsilon}{2}\,\nabla\lnprob(\pos)$} \Comment{run $L$ steps of leapfrog integration} \For{$l \gets 1 \textrm{ to } L$} \Let{\pos}{$\pos + \epsilon\,\mass^{-1}\,\mom$} \If{$l < L$} \Let{\mom}{$\mom + \epsilon\,\nabla\lnprob(\pos)$} \EndIf \EndFor \Let{\mom}{$\mom + \frac{\epsilon}{2}\,\nabla\lnprob(\pos)$} \Comment{synchronize the momentum and position} \State \State{$r \sim \mathcal{U}(0, 1)$} \If{$r < \exp\left[\lnprob(\pos) - \frac{1}{2}\mom^T\mass^{-1}\mom - \lnprob(\pos_t)+\frac{1}{2}{\mom_t}^T\mass^{-1}\mom_t \right]$} \State\Return{$\pos$} \Comment{accept} \Else \State\Return{$\pos_t$} \Comment{reject} \EndIf \EndFunction \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{Affine-invariant HMC \alglabel{ai-hmc}} \begin{algorithmic} \Function{AIHMCStep}{$\lnprob(\pos),\,\{\pos_k\}_{k=1}^K,\,\epsilon,\,L$} \For{$k \gets 1 \textrm{ to } K$} \Let{${\mass_k}^{-1}$}{$\mathrm{Cov}(\pos_{[k]})$} \Comment{estimate the empirical mass matrix} \State $\mom_k \sim \normal{\bvec{0}}{\mass_k}$ \Comment{sample the initial momentum exactly} \State \Let{$\mom^\prime$}{$\mom_k$} \Comment{save the initial coordinates} \Let{$\pos^\prime$}{$\pos_k$} \State \Let{$\mom^\prime$}{$\mom^\prime + \frac{\epsilon}{2}\,\nabla\lnprob(\pos^\prime)$} \Comment{run $L$ steps of leapfrog integration} \For{$l \gets 1 \textrm{ to } L$} \Let{$\pos^\prime$}{$\pos^\prime + \epsilon\,{\mass_k}^{-1}\,\mom^\prime$} \If{$l < L$} \Let{$\mom^\prime$}{$\mom^\prime + \epsilon\,\nabla\lnprob(\pos^\prime)$} \EndIf \EndFor \Let{$\mom^\prime$}{$\mom^\prime + \frac{\epsilon}{2}\,\nabla\lnprob(\pos^\prime)$} \Comment{synchronize the momentum and position} \State \State{$r \sim \mathcal{U}(0, 1)$} \If{$r < \exp\left[ \lnprob(\pos^\prime) - \frac{1}{2}{\mom^\prime}^T{\mass_k}^{-1}\mom^\prime - \lnprob(\pos_k) + \frac{1}{2}{\mom_k}^T{\mass_k}^{-1}\mom_k \right]$} \Let{$\pos_k$}{$\pos^\prime$} \Comment{accept} \Else \Let{$\pos_k$}{$\pos_k$} \Comment{reject} \EndIf \EndFor \State\Return{$\{ \pos_k \}_{k=1}^K$} \EndFunction \end{algorithmic} \end{algorithm} \clearpage \bibliography{emcee-hmc} \clearpage \end{document}
[GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 1 ⊢ log b r = -↑(Nat.clog b ⌈r⁻¹⌉₊) [PROOFSTEP] obtain rfl | hr := hr.eq_or_lt [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hr : 1 ≤ 1 ⊢ log b 1 = -↑(Nat.clog b ⌈1⁻¹⌉₊) [PROOFSTEP] rw [log, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr✝ : r ≤ 1 hr : r < 1 ⊢ log b r = -↑(Nat.clog b ⌈r⁻¹⌉₊) [PROOFSTEP] exact if_neg hr.not_le [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n : ℕ ⊢ log b ↑n = ↑(Nat.log b n) [PROOFSTEP] cases n [GOAL] case zero R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ ⊢ log b ↑Nat.zero = ↑(Nat.log b Nat.zero) [PROOFSTEP] simp [log_of_right_le_one] [GOAL] case succ R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n✝ : ℕ ⊢ log b ↑(Nat.succ n✝) = ↑(Nat.log b (Nat.succ n✝)) [PROOFSTEP] rw [log_of_one_le_right, Nat.floor_coe] [GOAL] case succ.hr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n✝ : ℕ ⊢ 1 ≤ ↑(Nat.succ n✝) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : b ≤ 1 r : R ⊢ log b r = 0 [PROOFSTEP] cases' le_total 1 r with h h [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : b ≤ 1 r : R h : 1 ≤ r ⊢ log b r = 0 [PROOFSTEP] rw [log_of_one_le_right _ h, Nat.log_of_left_le_one hb, Int.ofNat_zero] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : b ≤ 1 r : R h : r ≤ 1 ⊢ log b r = 0 [PROOFSTEP] rw [log_of_right_le_one _ h, Nat.clog_of_left_le_one hb, Int.ofNat_zero, neg_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 ⊢ log b r = 0 [PROOFSTEP] rw [log_of_right_le_one _ (hr.trans zero_le_one), Nat.clog_of_right_le_one ((Nat.ceil_eq_zero.mpr <| inv_nonpos.2 hr).trans_le zero_le_one), Int.ofNat_zero, neg_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r ⊢ ↑b ^ log b r ≤ r [PROOFSTEP] cases' le_total 1 r with hr1 hr1 [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r hr1 : 1 ≤ r ⊢ ↑b ^ log b r ≤ r [PROOFSTEP] rw [log_of_one_le_right _ hr1] [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r hr1 : 1 ≤ r ⊢ ↑b ^ ↑(Nat.log b ⌊r⌋₊) ≤ r [PROOFSTEP] rw [zpow_ofNat, ← Nat.cast_pow, ← Nat.le_floor_iff hr.le] [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r hr1 : 1 ≤ r ⊢ b ^ Nat.log b ⌊r⌋₊ ≤ ⌊r⌋₊ [PROOFSTEP] exact Nat.pow_log_le_self b (Nat.floor_pos.mpr hr1).ne' [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r hr1 : r ≤ 1 ⊢ ↑b ^ log b r ≤ r [PROOFSTEP] rw [log_of_right_le_one _ hr1, zpow_neg, zpow_ofNat, ← Nat.cast_pow] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r hr1 : r ≤ 1 ⊢ (↑(b ^ Nat.clog b ⌈r⁻¹⌉₊))⁻¹ ≤ r [PROOFSTEP] exact inv_le_of_inv_le hr (Nat.ceil_le.1 <| Nat.le_pow_clog hb _) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R ⊢ r < ↑b ^ (log b r + 1) [PROOFSTEP] cases' le_or_lt r 0 with hr hr [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : r ≤ 0 ⊢ r < ↑b ^ (log b r + 1) [PROOFSTEP] rw [log_of_right_le_zero _ hr, zero_add, zpow_one] [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : r ≤ 0 ⊢ r < ↑b [PROOFSTEP] exact hr.trans_lt (zero_lt_one.trans_le <| by exact_mod_cast hb.le) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : r ≤ 0 ⊢ 1 ≤ ↑b [PROOFSTEP] exact_mod_cast hb.le [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r ⊢ r < ↑b ^ (log b r + 1) [PROOFSTEP] cases' le_or_lt 1 r with hr1 hr1 [GOAL] case inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : 1 ≤ r ⊢ r < ↑b ^ (log b r + 1) [PROOFSTEP] rw [log_of_one_le_right _ hr1] [GOAL] case inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : 1 ≤ r ⊢ r < ↑b ^ (↑(Nat.log b ⌊r⌋₊) + 1) [PROOFSTEP] rw [Int.ofNat_add_one_out, zpow_ofNat, ← Nat.cast_pow] [GOAL] case inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : 1 ≤ r ⊢ r < ↑(b ^ Nat.succ (Nat.log b ⌊r⌋₊)) [PROOFSTEP] apply Nat.lt_of_floor_lt [GOAL] case inr.inl.h R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : 1 ≤ r ⊢ ⌊r⌋₊ < b ^ Nat.succ (Nat.log b ⌊r⌋₊) [PROOFSTEP] exact Nat.lt_pow_succ_log_self hb _ [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 ⊢ r < ↑b ^ (log b r + 1) [PROOFSTEP] rw [log_of_right_le_one _ hr1.le] [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 ⊢ r < ↑b ^ (-↑(Nat.clog b ⌈r⁻¹⌉₊) + 1) [PROOFSTEP] have hcri : 1 < r⁻¹ := one_lt_inv hr hr1 [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 hcri : 1 < r⁻¹ ⊢ r < ↑b ^ (-↑(Nat.clog b ⌈r⁻¹⌉₊) + 1) [PROOFSTEP] have : 1 ≤ Nat.clog b ⌈r⁻¹⌉₊ := Nat.succ_le_of_lt (Nat.clog_pos hb <| Nat.one_lt_cast.1 <| hcri.trans_le (Nat.le_ceil _)) [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 hcri : 1 < r⁻¹ this : 1 ≤ Nat.clog b ⌈r⁻¹⌉₊ ⊢ r < ↑b ^ (-↑(Nat.clog b ⌈r⁻¹⌉₊) + 1) [PROOFSTEP] rw [neg_add_eq_sub, ← neg_sub, ← Int.ofNat_one, ← Int.ofNat_sub this, zpow_neg, zpow_ofNat, lt_inv hr (pow_pos (Nat.cast_pos.mpr <| zero_lt_one.trans hb) _), ← Nat.cast_pow] [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 hcri : 1 < r⁻¹ this : 1 ≤ Nat.clog b ⌈r⁻¹⌉₊ ⊢ ↑(b ^ (Nat.clog b ⌈r⁻¹⌉₊ - 1)) < r⁻¹ [PROOFSTEP] refine' Nat.lt_ceil.1 _ [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r hr1 : r < 1 hcri : 1 < r⁻¹ this : 1 ≤ Nat.clog b ⌈r⁻¹⌉₊ ⊢ b ^ (Nat.clog b ⌈r⁻¹⌉₊ - 1) < ⌈r⁻¹⌉₊ [PROOFSTEP] exact Nat.pow_pred_clog_lt_self hb <| Nat.one_lt_cast.1 <| hcri.trans_le <| Nat.le_ceil _ [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ ⊢ log b 1 = 0 [PROOFSTEP] rw [log_of_one_le_right _ le_rfl, Nat.floor_one, Nat.log_one_right, Int.ofNat_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z : ℤ ⊢ log b (↑b ^ z) = z [PROOFSTEP] obtain ⟨n, rfl | rfl⟩ := Int.eq_nat_or_neg z [GOAL] case intro.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b n : ℕ ⊢ log b (↑b ^ ↑n) = ↑n [PROOFSTEP] rw [log_of_one_le_right _ (one_le_zpow_of_nonneg _ <| Int.coe_nat_nonneg _), zpow_ofNat, ← Nat.cast_pow, Nat.floor_coe, Nat.log_pow hb] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b n : ℕ ⊢ 1 ≤ ↑b [PROOFSTEP] exact_mod_cast hb.le [GOAL] case intro.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b n : ℕ ⊢ log b (↑b ^ (-↑n)) = -↑n [PROOFSTEP] rw [log_of_right_le_one _ (zpow_le_one_of_nonpos _ <| neg_nonpos.mpr (Int.coe_nat_nonneg _)), zpow_neg, inv_inv, zpow_ofNat, ← Nat.cast_pow, Nat.ceil_natCast, Nat.clog_pow _ _ hb] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b n : ℕ ⊢ 1 ≤ ↑b [PROOFSTEP] exact_mod_cast hb.le [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] cases' le_or_lt b 1 with hb hb [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : b ≤ 1 ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] rw [log_of_left_le_one hb, log_of_left_le_one hb] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] cases' le_total r₁ 1 with h₁ h₁ [GOAL] case inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : r₁ ≤ 1 ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] cases' le_total r₂ 1 with h₂ h₂ [GOAL] case inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : 1 ≤ r₁ ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] cases' le_total r₂ 1 with h₂ h₂ [GOAL] case inr.inl.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : r₁ ≤ 1 h₂ : r₂ ≤ 1 ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] rw [log_of_right_le_one _ h₁, log_of_right_le_one _ h₂, neg_le_neg_iff, Int.ofNat_le] [GOAL] case inr.inl.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : r₁ ≤ 1 h₂ : r₂ ≤ 1 ⊢ Nat.clog b ⌈r₂⁻¹⌉₊ ≤ Nat.clog b ⌈r₁⁻¹⌉₊ [PROOFSTEP] exact Nat.clog_mono_right _ (Nat.ceil_mono <| inv_le_inv_of_le h₀ h) [GOAL] case inr.inl.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : r₁ ≤ 1 h₂ : 1 ≤ r₂ ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] rw [log_of_right_le_one _ h₁, log_of_one_le_right _ h₂] [GOAL] case inr.inl.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : r₁ ≤ 1 h₂ : 1 ≤ r₂ ⊢ -↑(Nat.clog b ⌈r₁⁻¹⌉₊) ≤ ↑(Nat.log b ⌊r₂⌋₊) [PROOFSTEP] exact (neg_nonpos.mpr (Int.coe_nat_nonneg _)).trans (Int.coe_nat_nonneg _) [GOAL] case inr.inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : 1 ≤ r₁ h₂ : r₂ ≤ 1 ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] obtain rfl := le_antisymm h (h₂.trans h₁) [GOAL] case inr.inr.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ : R h₀ : 0 < r₁ hb : 1 < b h₁ : 1 ≤ r₁ h : r₁ ≤ r₁ h₂ : r₁ ≤ 1 ⊢ log b r₁ ≤ log b r₁ [PROOFSTEP] rfl [GOAL] case inr.inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : 1 ≤ r₁ h₂ : 1 ≤ r₂ ⊢ log b r₁ ≤ log b r₂ [PROOFSTEP] rw [log_of_one_le_right _ h₁, log_of_one_le_right _ h₂, Int.ofNat_le] [GOAL] case inr.inr.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ hb : 1 < b h₁ : 1 ≤ r₁ h₂ : 1 ≤ r₂ ⊢ Nat.log b ⌊r₁⌋₊ ≤ Nat.log b ⌊r₂⌋₊ [PROOFSTEP] exact Nat.log_mono_right (Nat.floor_mono h) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z : ℤ ⊢ 0 < ↑b [PROOFSTEP] exact_mod_cast zero_lt_one.trans hb [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z₁ z₂ : ℤ hz : z₁ ≤ z₂ ⊢ 1 < ↑b [PROOFSTEP] exact_mod_cast hb [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 1 ⊢ clog b r = -↑(Nat.log b ⌊r⁻¹⌋₊) [PROOFSTEP] obtain rfl | hr := hr.eq_or_lt [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hr : 1 ≤ 1 ⊢ clog b 1 = -↑(Nat.log b ⌊1⁻¹⌋₊) [PROOFSTEP] rw [clog, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr✝ : r ≤ 1 hr : r < 1 ⊢ clog b r = -↑(Nat.log b ⌊r⁻¹⌋₊) [PROOFSTEP] exact if_neg hr.not_le [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 ⊢ clog b r = 0 [PROOFSTEP] rw [clog, if_neg (hr.trans_lt zero_lt_one).not_le, neg_eq_zero, Int.coe_nat_eq_zero, Nat.log_eq_zero_iff] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 ⊢ ⌊r⁻¹⌋₊ < b ∨ b ≤ 1 [PROOFSTEP] cases' le_or_lt b 1 with hb hb [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 hb : b ≤ 1 ⊢ ⌊r⁻¹⌋₊ < b ∨ b ≤ 1 [PROOFSTEP] exact Or.inr hb [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 hb : 1 < b ⊢ ⌊r⁻¹⌋₊ < b ∨ b ≤ 1 [PROOFSTEP] refine' Or.inl (lt_of_le_of_lt _ hb) [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hr : r ≤ 0 hb : 1 < b ⊢ ⌊r⁻¹⌋₊ ≤ 1 [PROOFSTEP] exact Nat.floor_le_one_of_le_one ((inv_nonpos.2 hr).trans zero_le_one) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R ⊢ clog b r⁻¹ = -log b r [PROOFSTEP] cases' lt_or_le 0 r with hrp hrp [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hrp : 0 < r ⊢ clog b r⁻¹ = -log b r [PROOFSTEP] obtain hr | hr := le_total 1 r [GOAL] case inl.inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hrp : 0 < r hr : 1 ≤ r ⊢ clog b r⁻¹ = -log b r [PROOFSTEP] rw [clog_of_right_le_one _ (inv_le_one hr), log_of_one_le_right _ hr, inv_inv] [GOAL] case inl.inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hrp : 0 < r hr : r ≤ 1 ⊢ clog b r⁻¹ = -log b r [PROOFSTEP] rw [clog_of_one_le_right _ (one_le_inv hrp hr), log_of_right_le_one _ hr, neg_neg] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hrp : r ≤ 0 ⊢ clog b r⁻¹ = -log b r [PROOFSTEP] rw [clog_of_right_le_zero _ (inv_nonpos.mpr hrp), log_of_right_le_zero _ hrp, neg_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R ⊢ log b r⁻¹ = -clog b r [PROOFSTEP] rw [← inv_inv r, clog_inv, neg_neg, inv_inv] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R ⊢ -log b r⁻¹ = clog b r [PROOFSTEP] rw [log_inv, neg_neg] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R ⊢ -clog b r⁻¹ = log b r [PROOFSTEP] rw [clog_inv, neg_neg] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n : ℕ ⊢ clog b ↑n = ↑(Nat.clog b n) [PROOFSTEP] cases' n with n [GOAL] case zero R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ ⊢ clog b ↑Nat.zero = ↑(Nat.clog b Nat.zero) [PROOFSTEP] simp [clog_of_right_le_one] [GOAL] case succ R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n : ℕ ⊢ clog b ↑(Nat.succ n) = ↑(Nat.clog b (Nat.succ n)) [PROOFSTEP] rw [clog_of_one_le_right, (Nat.ceil_eq_iff (Nat.succ_ne_zero n)).mpr] [GOAL] case succ R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n : ℕ ⊢ ↑(Nat.succ n - 1) < ↑(Nat.succ n) ∧ ↑(Nat.succ n) ≤ ↑(Nat.succ n) [PROOFSTEP] simp [GOAL] case succ.hr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b n : ℕ ⊢ 1 ≤ ↑(Nat.succ n) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : b ≤ 1 r : R ⊢ clog b r = 0 [PROOFSTEP] rw [← neg_log_inv_eq_clog, log_of_left_le_one hb, neg_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R ⊢ r ≤ ↑b ^ clog b r [PROOFSTEP] cases' le_or_lt r 0 with hr hr [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : r ≤ 0 ⊢ r ≤ ↑b ^ clog b r [PROOFSTEP] rw [clog_of_right_le_zero _ hr, zpow_zero] [GOAL] case inl R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : r ≤ 0 ⊢ r ≤ 1 [PROOFSTEP] exact hr.trans zero_le_one [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r ⊢ r ≤ ↑b ^ clog b r [PROOFSTEP] rw [← neg_log_inv_eq_clog, zpow_neg, le_inv hr (zpow_pos_of_pos _ _)] [GOAL] case inr R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r ⊢ ↑b ^ log b r⁻¹ ≤ r⁻¹ [PROOFSTEP] exact zpow_log_le_self hb (inv_pos.mpr hr) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b r : R hr : 0 < r ⊢ 0 < ↑b [PROOFSTEP] exact Nat.cast_pos.mpr (zero_le_one.trans_lt hb) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r ⊢ ↑b ^ (clog b r - 1) < r [PROOFSTEP] rw [← neg_log_inv_eq_clog, ← neg_add', zpow_neg, inv_lt _ hr] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r ⊢ r⁻¹ < ↑b ^ (log b r⁻¹ + 1) [PROOFSTEP] exact lt_zpow_succ_log_self hb _ [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r : R hb : 1 < b hr : 0 < r ⊢ 0 < ↑b ^ (log b r⁻¹ + 1) [PROOFSTEP] exact zpow_pos_of_pos (Nat.cast_pos.mpr <| zero_le_one.trans_lt hb) _ [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ ⊢ clog b 1 = 0 [PROOFSTEP] rw [clog_of_one_le_right _ le_rfl, Nat.ceil_one, Nat.clog_one_right, Int.ofNat_zero] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z : ℤ ⊢ clog b (↑b ^ z) = z [PROOFSTEP] rw [← neg_log_inv_eq_clog, ← zpow_neg, log_zpow hb, neg_neg] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ ⊢ clog b r₁ ≤ clog b r₂ [PROOFSTEP] rw [← neg_log_inv_eq_clog, ← neg_log_inv_eq_clog, neg_le_neg_iff] [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ r₁ r₂ : R h₀ : 0 < r₁ h : r₁ ≤ r₂ ⊢ log b r₂⁻¹ ≤ log b r₁⁻¹ [PROOFSTEP] exact log_mono_right (inv_pos.mpr <| h₀.trans_le h) (inv_le_inv_of_le h₀ h) [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z : ℤ ⊢ 0 < ↑b [PROOFSTEP] exact_mod_cast zero_lt_one.trans hb [GOAL] R : Type u_1 inst✝¹ : LinearOrderedSemifield R inst✝ : FloorSemiring R b : ℕ hb : 1 < b z₁ z₂ : ℤ hz : z₁ ≤ z₂ ⊢ 1 < ↑b [PROOFSTEP] exact_mod_cast hb
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Typing rules and a type inference algorithm for RTL. *) Require Import CoqlibC. Require Import Errors. Require Import Unityping. Require Import Maps. Require Import AST. Require Import Op. Require Import Registers. Require Import Globalenvs. Require Import ValuesC. Require Import IntegersC. Require Import MemoryC. Require Import Events. Require Import RTLC. Require Import ConventionsC. Require Import sflib. (** newly added **) Require Export RTLtyping. Require Import Skeleton ModSem Preservation. Require Import SoundTop. Require Import RTLC. Section LPRSV. Variable prog: program. Hypothesis wt_prog: forall i fd, In (i, Gfun fd) prog.(prog_defs) -> wt_fundef fd. Theorem wt_state_local_preservation: forall skenv_link, local_preservation (modsem2 skenv_link prog) (fun _ _ st => wt_state st). Proof. econs; ii; ss; eauto. - (* init *) inv INIT. econs; et. + econs; et. + inv TYP. eapply typify_has_type_list; et. - (* step *) eapply subject_reduction; et. ii. unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs. unfold Skeleton.SkEnv.revive in *. eapply Genv_map_defs_def in Heq. des. u in MAP. des_ifs_safe. esplits. eapply in_prog_defmap; eauto. - esplits; eauto. { rr. esplits; ss; eauto. des_ifs. esplits; ss. rr. rewrite Forall_forall. ii; ss. } ii. inv AFTER. inv SUST. econs; et. apply typify_has_type. - esplits; eauto. rr. des_ifs. Unshelve. all: ss. Qed. End LPRSV.
<a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/linear_fujioka.ipynb" target="_parent"></a> # メモ 手を動かしてまなぶ 線形代数 藤岡敦 を読む。 http://www.shokabo.co.jp/ に詳細な解答があるって。 # 行列 1. 行列とは数を長方形状に並べたものである。 1. すべての成分が 0 の行列を零行列という。 1. 行と列の個数が等しい行列を正方行列という。 1. 特別な正方行列として、単位行列、対角行列、スカラー行列、上三角行列、下三角行列があげられる。 1. 単位行列はクロネッカーのデルタを用いて、簡単に表すことができる。 1. 転置をとっても変わらない正方行列を対称行列という。 1. 行ベクトル、列ベクトルをあわせて数ベクトルという。 1. すべての成分が 0 の数ベクトルを零ベクトルという。 自然数 $i=1,2,\cdots,m$ および $j=1,2,\cdots,n$ に対して、数 $a_{ij}$ が対応しているとする。 このとき、$mn$ 個の数 $a_{11},a_{12},\cdots,a_{mn}$ を丸括弧 ( ) や角括弧 [ ] を用いて長方形状に並べたものを $m \times n$ 行列または$m$行$n$列の行列という。 $a_{ij}$ の $i$ や $j$ を添字(そえじ)という。 ```latex %%latex \begin{pmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{pmatrix}, \quad \begin{bmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{bmatrix} ``` \begin{pmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{pmatrix}, \quad \begin{bmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{bmatrix} 例 次の行列は $2 \times 3$ 行列である。 ```latex %%latex \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} ``` \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} ``` from sympy import * A=Matrix([[1,2,3],[4,5,6]]) display(A) ``` $\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\end{matrix}\right]$ 行列 $A$ について $A = (a_{ij})$ と書く。 $\quad a_{ij},\quad (a_{i1} a_{i2} \cdots a_{in}), \quad \begin{pmatrix} a_{1j} \\ a_{2j} \\ a_{2j} \\ a_{mj} \end{pmatrix}$ を$A$の$(i,j)$成分、第$i$行、第$j$列という。 ```latex %%latex \begin{pmatrix} a_{1j} \\ a_{2j} \\ a_{2j} \\ a_{mj} \end{pmatrix} ``` \displaystyle \begin{pmatrix} a_{1j} \\ a_{2j} \\ a_{2j} \\ a_{mj} \end{pmatrix} $ A=(a_{ij})_{m \times n} $ を $ m \times n $ 行列、 $ B=(b_{kl})_{p \times q} $ を $ p \times q $ 行列とする。 $ A $ と $ B $ が同じ型で、対応する成分が等しいとき、すなわち、 $ m=p $ かつ $ n=q $ で、 任意の $ i=1,2,\cdots,m $ および $ j=1,2,\cdots,n $ に対して $ a_{ij}=b_{ij} $ が成り立つとき $$ A = B$$ と記し、A $ と $ B $ は等しい、という。A = B $ でないときは $$ A \neq B $$ $$ \begin{array}{rcl} \begin{pmatrix} a & b & c \\ d & e & f \end{pmatrix} &=& \begin{pmatrix} p & q & r \\ s & t & u \end{pmatrix} \\[0.8em] &\Updownarrow& \\[0.8em] a = p,\quad b = q,\quad c = r&,& d = s,\quad e = t,\quad f = u \end{array} $$ ```latex %%latex \begin{array}{rcl} \begin{pmatrix} a & b & c \\ d & e & f \end{pmatrix} &=& \begin{pmatrix} p & q & r \\ s & t & u \end{pmatrix} \\[0.8em] &\Updownarrow& \\[0.8em] a = p,\quad b = q,\quad c = r&,& d = s,\quad e = t,\quad f = u \end{array} \\ ``` \begin{array}{rcl} \begin{pmatrix} a & b & c \\ d & e & f \end{pmatrix} &=& \begin{pmatrix} p & q & r \\ s & t & u \end{pmatrix} \\[0.8em] &\Updownarrow& \\[0.8em] a = p,\quad b = q,\quad c = r&,& d = s,\quad e = t,\quad f = u \end{array} \\ ```latex %%latex すべての成分が~0~の~m \times n~行列を~O_{m,n}~または~O~と書き、零行列という。 \\[0.8em] \quad \quad \quad \quad O_{3,2} = \begin{pmatrix} 0 & 0 \\ 0 & 0 \\ 0 & 0 \end{pmatrix} \\[0.8em] 2~列、~3~行 ``` すべての成分が~0~の~m \times n~行列を~O_{m,n}~または~O~と書き、零行列という。 \\[0.8em] \quad \quad \quad \quad O_{3,2} = \begin{pmatrix} 0 & 0 \\ 0 & 0 \\ 0 & 0 \end{pmatrix} \\[0.8em] 2~列、~3~行 ```latex %%latex 一般に、2~つの命題~P,~Q~に対して、P~ならば~Q~であることを~P \Longrightarrow Q~と表し、P~と~Q~が同値であることを ~P \Longleftrightarrow Q~と表す。 ``` 一般に、2~つの命題~P,~Q~に対して、P~ならば~Q~であることを~P \Longrightarrow Q~と表し、P~と~Q~が同値であることを ~P \Longleftrightarrow Q~と表す。 ```latex %%latex A = (a_{ij})_{n \times n}~を~n \times n~ 行列とするとき、A~を~n~次の正方行列という。\\ 成分~a_{11}, a_{22}, \cdots a_{nn}~を~A~の対角成分という。\\[0.8em] 正方行列 ~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i \neq j) \\[0.8em] を満たすとき、A~を対角行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i \neq j), \quad a_{11} = a_{22} = \cdots = a_{nn} \\[0.8em] を満たすとき、A~をスカラー行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i > j) \\[0.8em] を満たすとき、A~を上三角行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i < j) \\[0.8em] を満たすとき、A~を下三角行列という。 ``` A = (a_{ij})_{n \times n}~を~n \times n~ 行列とするとき、A~を~n~次の正方行列という。\\ 成分~a_{11}, a_{22}, \cdots a_{nn}~を~A~の対角成分という。\\[0.8em] 正方行列 ~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i \neq j) \\[0.8em] を満たすとき、A~を対角行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i \neq j), \quad a_{11} = a_{22} = \cdots = a_{nn} \\[0.8em] を満たすとき、A~をスカラー行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i > j) \\[0.8em] を満たすとき、A~を上三角行列という。 正方行列~A~が\\[0.8em] \quad \quad \quad \quad a_{ij} = 0 \quad (i < j) \\[0.8em] を満たすとき、A~を下三角行列という。 ```latex %%latex 2~次の正方行列 ~A~ = \begin{pmatrix} a & b \\ c & d \end{pmatrix} ~とする。\\[0.8em] A~の対角成分は~ \begin{pmatrix} a & 0 \\ 0 & d \end{pmatrix}\\[0.8em] A~が対角行列、上三角行列、下三角行列となるときそれぞれ\\[0.8em] \begin{pmatrix} a & 0 \\ 0 & a \end{pmatrix}, \quad \begin{pmatrix} a & b \\ 0 & d \end{pmatrix}, \quad \begin{pmatrix} a & 0 \\ c & d \end{pmatrix} ``` 2~次の正方行列 ~A~ = \begin{pmatrix} a & b \\ c & d \end{pmatrix} ~とする。\\[0.8em] A~の対角成分は~ \begin{pmatrix} a & 0 \\ 0 & d \end{pmatrix}\\[0.8em] A~が対角行列、上三角行列、下三角行列となるときそれぞれ\\[0.8em] \begin{pmatrix} a & 0 \\ 0 & a \end{pmatrix}, \quad \begin{pmatrix} a & b \\ 0 & d \end{pmatrix}, \quad \begin{pmatrix} a & 0 \\ c & d \end{pmatrix} ```latex %%latex 対角成分がすべて~1~の~n~次スカラー行列を~E_n~または~E~と書き、~n~次単位行列という。 ~I_n~や~I~と書くこともある。\\[0.8em] E_1 = (1) = 1, \quad E_2 = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \quad E_3 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} ``` 対角成分がすべて~1~の~n~次スカラー行列を~E_n~または~E~と書き、~n~次単位行列という。 ~I_n~や~I~と書くこともある。\\[0.8em] E_1 = (1) = 1, \quad E_2 = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \quad E_3 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} ``` # クロネッカーのデルタ %%latex クロネッカーのデルタ\\[0.8em] i,j = 1,2, \cdots, n~ に対して\\[0.8em] \quad \quad \quad \quad \delta = \left \{ \begin{array}{cl} 1 & (i = j) \\ 0 & (i \neq j) \end{array} \right . \\[0.8em] により、~0~または~1~をとる記号~\delta_{ij}~を定める。 \\ ~\delta_{ij}~をクロネッカーのデルタという。 ``` クロネッカーのデルタ\\[0.8em] i,j = 1,2, \cdots, n~ に対して\\[0.8em] \quad \quad \quad \quad \delta = \left \{ \begin{array}{cl} 1 & (i = j) \\ 0 & (i \neq j) \end{array} \right . \\[0.8em] により、~0~または~1~をとる記号~\delta_{ij}~を定める。 \\ ~\delta_{ij}~をクロネッカーのデルタという。 ```latex %%latex i,j = 1,2 のとき、クロネッカーのデルタ~\delta_{ij}~の値を求める。\\[0.8em] \quad \quad \quad \quad \delta_{11} = \delta_{22} = 1, \quad \delta_{12} = \delta_{21} = 0 ``` i,j = 1,2 のとき、クロネッカーのデルタ~\delta_{ij}~の値を求める。\\[0.8em] \quad \quad \quad \quad \delta_{11} = \delta_{22} = 1, \quad \delta_{12} = \delta_{21} = 0 ```latex %%latex クロネッカーのデルタを用いると、~n~次単位行列~E_n~は~E_n = (\delta_{ij})_{n \times n}~ と表すことができる。\\ 例えば、~2~次単位行列は\\[0.8em] \quad \quad \quad \quad E_2 = \begin{pmatrix} \delta_{11} & \delta_{12} \\ \delta_{21} & \delta_{22} \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \\[0.8em] となる。 ``` クロネッカーのデルタを用いると、~n~次単位行列~E_n~は~E_n = (\delta_{ij})_{n \times n}~ と表すことができる。\\ 例えば、~2~次単位行列は\\[0.8em] \quad \quad \quad \quad E_2 = \begin{pmatrix} \delta_{11} & \delta_{12} \\ \delta_{21} & \delta_{22} \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \\[0.8em] となる。 ```latex %%latex 転置行列\\[0.8em] m \times n~ 行列~A~の行と列を入れ替えて得られる~n \times m~ 行列を~{}^t A, A^t~ または~{}^T A~ などと書き、\\ ~A~の転置行列という。 すなわち、\\[0.8em] \quad \quad \quad \quad A = \begin{pmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{pmatrix} \\[0.8em] のとき、\\[0.8em] \quad \quad \quad \quad {}^t A = \begin{pmatrix} a_{11} & a_{21} & \ldots & a_{m1} \\ a_{12} & a_{22} & \ldots & a_{m2} \\ \vdots & \vdots & \ddots & \vdots \\ a_{1n} & a_{2m} & \ldots & a_{mn} \end{pmatrix} \\[0.8em] である。定義より、\\[0.8em] \quad \quad \quad \quad {}^t({}^t A) = A \\[0.8em] が成り立つ。 なお転置行列を作ることを、転置を取る、ともいう。 ``` 転置行列\\[0.8em] m \times n~ 行列~A~の行と列を入れ替えて得られる~n \times m~ 行列を~{}^t A, A^t~ または~{}^T A~ などと書き、\\ ~A~の転置行列という。 すなわち、\\[0.8em] \quad \quad \quad \quad A = \begin{pmatrix} a_{11} & a_{12} & \ldots & a_{1n} \\ a_{21} & a_{22} & \ldots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \ldots & a_{mn} \end{pmatrix} \\[0.8em] のとき、\\[0.8em] \quad \quad \quad \quad {}^t A = \begin{pmatrix} a_{11} & a_{21} & \ldots & a_{m1} \\ a_{12} & a_{22} & \ldots & a_{m2} \\ \vdots & \vdots & \ddots & \vdots \\ a_{1n} & a_{2m} & \ldots & a_{mn} \end{pmatrix} \\[0.8em] である。定義より、\\[0.8em] \quad \quad \quad \quad {}^t({}^t A) = A \\[0.8em] が成り立つ。 なお転置行列を作ることを、転置を取る、ともいう。 ```latex %%latex 例題 \\[0.8em] 2 \times 3~ 行列~ \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix}~ の転置行列を求める。 \\[0.8em] ``` 例題 \\[0.8em] 2 \times 3~ 行列~ \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix}~ の転置行列を求める。 ``` from sympy import * init_printing() A = Matrix([[1,2,3],[4,5,6]]) display(A) print() display (A.T) ``` $\displaystyle \left[\begin{matrix}1 & 2 & 3\\4 & 5 & 6\end{matrix}\right]$ $\displaystyle \left[\begin{matrix}1 & 4\\2 & 5\\3 & 6\end{matrix}\right]$ ```latex %%latex 対称行列\\[0.8em] ~n~次の正方行列の転置行列は再び~n~次の正方行列となる。よって、次のような正方行列を考えることができる。\\[0.8em] 定義 \quad {}^t A = A が成り立つ正方行列~A~を対称行列という。\\[0.8em] 例 \\[0.8em] \quad \quad \quad \quad (1), \quad \begin{pmatrix} 1 & 2 \\ 2 & 3 \end{pmatrix} , \quad \begin{pmatrix} 1 & 2 & 3\\ 2 & 4 & 5\\ 3 & 5 & 6 \end{pmatrix} ``` 対称行列\\[0.8em] ~n~次の正方行列の転置行列は再び~n~次の正方行列となる。よって、次のような正方行列を考えることができる。\\[0.8em] 定義 \quad {}^t A = A が成り立つ正方行列~A~を対称行列という。\\[0.8em] 例 \\[0.8em] \quad \quad \quad \quad (1), \quad \begin{pmatrix} 1 & 2 \\ 2 & 3 \end{pmatrix} , \quad \begin{pmatrix} 1 & 2 & 3\\ 2 & 4 & 5\\ 3 & 5 & 6 \end{pmatrix} ```latex %%latex 定義より、対称行列について、次の定理が成り立つ。\\[0.8em] A=(a_{ij})~を~n~次の正方行列とする。 ~A~が対称行列であるための必要十分条件は\\[0.8em] \quad \quad \quad \quad a_{ij} = a_{ji} \quad (i,j = 1,2,\cdots, n)\\[0.8em] である。 ``` 定義より、対称行列について、次の定理が成り立つ。\\[0.8em] A=(a_{ij})~を~n~次の正方行列とする。 ~A~が対称行列であるための必要十分条件は\\[0.8em] \quad \quad \quad \quad a_{ij} = a_{ji} \quad (i,j = 1,2,\cdots, n)\\[0.8em] である。 ```latex %%latex ベクトルと名のつくものを簡単に書くときは太文字、ボールド体を用いる。\\[0.8em] \quad \quad \quad \quad \mathbf{0,a,b,c,d,e,n,v,x,y,z,R,C}\\[0.8em] 手書きするときは、文字の左側を~2~重にする。\\[0.8em] \quad \quad \quad \quad \mathbb{0,a,b,c,d,e,n,v,x,y,z,R,C}\\[0.8em] 大文字しか~2~重にならない。 ``` ベクトルと名のつくものを簡単に書くときは太文字、ボールド体を用いる。\\[0.8em] \quad \quad \quad \quad \mathbf{0,a,b,c,d,e,n,v,x,y,z,R,C}\\[0.8em] 手書きするときは、文字の左側を~2~重にする。\\[0.8em] \quad \quad \quad \quad \mathbb{0,a,b,c,d,e,n,v,x,y,z,R,C}\\[0.8em] 大文字しか~2~重にならない。 => いまの考えテキストが~2~重文字のとき、テキスト重視の考え方から\\ ~\mathbb~ ```latex %%latex 問題\\[0.8em] ~3~次の正方行列~A~を~A = \begin{pmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{pmatrix}~と表す。 1.~A~の対角成分を答える。 2.~A~が対角行列、スカラー行列、上三角行列、下三角行列になるとき、~A~をそれぞれ具体的に示す。 ``` 問題\\[0.8em] ~3~次の正方行列~A~を~A = \begin{pmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{pmatrix} ```latex %%latex 1.~a_{11},a_{12},a_{13} \\[0.8em] 2.~ \begin{pmatrix} a_{11} & 0 & 0 \\ 0 & a_{22} & 0 \\ 0 & 0 & a_{33} \end{pmatrix}, \quad \begin{pmatrix} a_{11} & 0 & 0 \\ 0 & a_{11} & 0 \\ 0 & 0 & a_{11} \end{pmatrix}, \quad \begin{pmatrix} a_{11} & a_{12} & a_{13} \\ 0 & a_{22} & a_{23} \\ 0 & 0 & a_{33} \end{pmatrix}~, \quad \begin{pmatrix} a_{11} & 0 & 0 \\ a_{21} & a_{22} & 0 \\ a_{31} & a_{32} & a_{33} \end{pmatrix} ``` 1.~a_{11},a_{12},a_{13} \\[0.8em] 2.~ \begin{pmatrix} a_{11} & 0 & 0 \\ 0 & a_{22} & 0 \\ 0 & 0 & a_{33} \end{pmatrix}, \quad \begin{pmatrix} a_{11} & 0 & 0 \\ 0 & a_{11} & 0 \\ 0 & 0 & a_{11} \end{pmatrix}, \quad \begin{pmatrix} a_{11} & a_{12} & a_{13} \\ 0 & a_{22} & a_{23} \\ 0 & 0 & a_{33} \end{pmatrix}~, \quad \begin{pmatrix} a_{11} & 0 & 0 \\ a_{21} & a_{22} & 0 \\ a_{31} & a_{32} & a_{33} \end{pmatrix} ```latex %%latex 問題 \\[0.8em] クロネッカーのデルタ~\delta_{ij} \quad (i,j = 1,2, \cdots, n)~ について、~i,j=1,2,3~のとき、~\delta_{ij}~の値を求める。 \\[0.8em] 解答 \\[0.8em] \delta_{11}=\delta_{22}=\delta_{33}=1, \quad \delta_{12}=\delta_{13}=\delta_{21}=\delta_{23}=\delta_{31}=\delta_{32}=0 ``` 問題 \\[0.8em] クロネッカーのデルタ~\delta_{ij} \quad (i,j = 1,2, \cdots, n)~ について、~i,j=1,2,3~のとき、~\delta_{ij}~の値を求める。 \\[0.8em] 解答 \\[0.8em] \delta_{11}=\delta_{22}=\delta_{33}=1, \quad \delta_{12}=\delta_{13}=\delta_{21}=\delta_{23}=\delta_{31}=\delta_{32}=0 ```latex %%latex 問題 \\[0.8em] ~3 \times 2~行列~ \begin{pmatrix} 5 & 4 \\ 3 & 2 \\ 1 & 0 \end{pmatrix}~の転置行列を求める。 ``` 問題 \\[0.8em] ~3 \times 2~行列~ \begin{pmatrix} 5 & 4 \\ 3 & 2 \\ 1 & 0 \end{pmatrix} ``` from sympy import * from IPython.display import Markdown init_printing() display(Markdown("解答")) print() display(Matrix([[5,4],[3,2],[1,0]])) print() display(Matrix([[5,4],[3,2],[1,0]]).T) ``` 解答 $\displaystyle \left[\begin{matrix}5 & 4\\3 & 2\\1 & 0\end{matrix}\right]$ $\displaystyle \left[\begin{matrix}5 & 3 & 1\\4 & 2 & 0\end{matrix}\right]$ ```latex %%latex 問題 \\[0.8em] \begin{pmatrix} a^2+b^2 & ab + bc \\ ab + bc & b^2 + c^2 \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 4 \end{pmatrix} ``` 問題 \\[0.8em] \begin{pmatrix} a^2+b^2 & ab + bc \\ ab + bc & b^2 + c^2 \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 4 \end{pmatrix} ``` from sympy import * from IPython.display import Markdown init_printing() display(Markdown("問題")) a,b,c = symbols('a,b,c') A = Matrix([[a**2+b**2, a*b+b*c],[a*b+b*c, b**2+c**2]]) display(A) B = Matrix([[1,0],[0,4]]) display(B) display(Eq(A,B)) display(Markdown("解答")) display(solve((A-B),a,b,c)) display(solve((A-B))) ``` ``` from sympy import * from IPython.display import Markdown init_printing() display(Markdown("問題")) a,b,c = symbols('a,b,c') A = Matrix([[a**2+b**2, a*b+b*c],[a*b+b*c, b**2+c**2],[]]) display(A) ``` 問題 $\displaystyle \left[\begin{matrix}a^{2} + b^{2} & a b + b c\\a b + b c & b^{2} + c^{2}\end{matrix}\right]$ # いまここ p.10
-- Andreas, 2014-01-10 -- Code by Jesper Cockx and Conor McBride and folks from the Coq-club {-# OPTIONS --cubical-compatible #-} -- An empty type. data Zero : Set where -- A unit type as W-type. mutual data WOne : Set where wrap : FOne -> WOne FOne = Zero -> WOne -- Type equality. data _<->_ (X : Set) : Set -> Set₁ where Refl : X <-> X -- This postulate is compatible with univalence: postulate iso : WOne <-> FOne -- But accepting that is incompatible with univalence: auoo : WOne -> Zero auoo (wrap f) = noo FOne iso f where noo : (X : Set) -> (WOne <-> X) -> X -> Zero noo .WOne Refl w = auoo w -- Matching against Refl silently applies the conversion -- FOne -> WOne to f. But this conversion corresponds -- to an application of wrap. Thus, f, which is really -- (wrap f), should not be considered a subterm of (wrap f) -- by the termination checker. -- At least, if we want to be compatible with univalence. absurd : Zero absurd = auoo (wrap \ ()) -- noo should fail termination check.
Set Implicit Arguments. Add Rec LoadPath "." as Top. Require Import Regex Automata2. Require Import List ListSet Bool Arith. Import ListNotations. Definition bool_list_dec : forall x y: list bool, {x = y} + {x <> y} := list_eq_dec bool_dec. Section Nae. Variable A St: Type. Variable Seq_dec: forall x y:St, {x = y} + {x <> y}. Definition word := list A. Definition nae := nfa (option A) St. (*Non recurisif sur un argument, on ajoute donc un entier qui sera 2 fois la taille de la liste, on considère qu'il y a une altérnence entre transition None et transition Some*) Fixpoint accepts_eps_from (nae : nae) (l: nat) s w := match l with | 0 => set_mem Seq_dec s (fin nae) | S n => let aux l := fun b s => b || accepts_eps_from nae n s l in if set_fold_left (aux w) (next nae (None) s) false then true else match w with | [] => set_mem Seq_dec s (fin nae) | h::q => set_fold_left (aux q) (next nae (Some h) s) false end end. Definition accepts_eps (nae: nae) w := accepts_eps_from nae (length w * 2)(start nae) w. (* (*On utilise steps car mieux pour raisonner après, blocage avec l'autre version de accepts_eps_from*) Inductive steps_nae nae : list A -> Ensemble (S * S) := | In_steps_nil : forall p q, rtrancl (eps nae) (p, q) -> steps_nae nae [] (p, q) | In_steps_cons : forall h q sa sb sc sd, rtrancl (eps nae) (sa, sb) -> step nae (Some h) (sb, sc) -> steps_nae nae q (sc, sd) -> steps_nae nae (h::q) (sa, sd). Inductive accepts_eps_from (nae: nae) (s: S) : list A -> Prop := | acc_nil : In _ (fin nae) s -> accepts_eps_from nae s [] | acc_cons : forall e h q, In _ (next nae (Some h) s) e -> accepts_eps_from nae e q -> accepts_eps_from nae s (h::q) | acc_none : forall e w, In _ (next nae None s) e -> accepts_eps_from nae e w -> accepts_eps_from nae s w. Definition accepts_eps nae w : Prop := exists k, In _ (fin nae) k /\ In _ (steps_nae nae w) (start nae, k). *) End Nae. Section BitsNAe. Variable A : Type. Variable Aeq_dec : forall x y:A, {x = y} + {x <> y}. Definition bitsNAe := nae A (list bool). Fixpoint atom_next (a: A) oa lb: set (list bool) := match lb with | [true] => match oa with | Some x => if Aeq_dec x a then [[false]] else [] | _ => [] end | _ => [] end. Definition atom (a: A): bitsNAe := mkNfa ([true]) (atom_next a) ([[false]]). Definition prepend_list_set (b: bool) (ens: set (list bool)) := set_map bool_list_dec (fun l => b::l) ens. (*Inductive alt_next (nae1 nae2: bitsNAe): option A -> list bool -> Ensemble (list bool) := | nextL : forall a q s, In _ (next nae1 a s) q -> alt_next nae1 nae2 a (true::q) s | nextR : forall a q s, In _ (next nae2 a s) q -> alt_next nae1 nae2 a (false::q) s. Inductive alt_next (nae1 nae2: bitsNAe): option A -> list bool -> Ensemble (list bool) := | nextNL : alt_next nae1 nae2 None [] (true::start nae1) | nextNR : alt_next nae1 nae2 None [] (false::start nae2) | nextL : forall a q s, In _ (next nae1 a q) s -> alt_next nae1 nae2 a (true::q) (true::s) | nextR : forall a q s, In _ (next nae2 a q) s -> alt_next nae1 nae2 a (false::q) (true::s). Inductive alt_fin (nae1 nae2: bitsNAe): Ensemble (list bool) := | finL : forall s, In _ (fin nae1) s -> alt_fin nae1 nae2 (true::s) | finR : forall s, In _ (fin nae1) s -> alt_fin nae1 nae2 (false::s).*) Fixpoint alt_next (nae1 nae2: bitsNAe) oa lb: set (list bool) := match oa with | None => match lb with | [] => [true::start nae1; false::start nae2] | _ => [] end | Some x => match lb with | true::q => prepend_list_set true (next nae1 oa q) | false::q => prepend_list_set false (next nae2 oa q) | _ => [] end end. Definition alt (nae1: bitsNAe) (nae2: bitsNAe): bitsNAe := let start1 := start nae1 in let start2 := start nae2 in let next1 := next nae1 in let next2 := next nae2 in let fin1 := fin nae1 in let fin2 := fin nae2 in mkNfa ([]) (alt_next nae1 nae2) (set_union bool_list_dec (prepend_list_set true fin1) (prepend_list_set false fin2)). (*Definition conc (nae1: bitsNAe) (nae2: bitsNAe): bitsNAe := let start1 := start nae1 in let start2 := start nae2 in let next1 := next nae1 in let next2 := next nae2 in let fin1 := fin nae1 in let fin2 := fin nae2 in mkNfa (true::start1) (fun t s => match s with | [] => empty_set | true::q => prepend_list_set true (next1 t q) | false::q => prepend_list_set false (next2 t q) end) (prepend_list_set false fin2). Fixpoint to_nfae (rexp: rexp A): bitsNAe := match rexp with | Empty _ => mkNfa ([]) (fun s t => empty_set) (fun s => s = []) | Atom a => atom a | Alt r1 r2 => alt (to_nfae r1) (to_nfae r2) | Conc r1 r2 => conc (to_nfae r1) (to_nfae r2) | Star r => mkNfa ([]) (fun s t => empty_set) (fun s => s = []) end.*) End BitsNAe. Section Test. Definition rexp1 := Atom 1. Definition nfae1 := atom eq_nat_dec 1. Lemma acc_nfae1 : accepts_eps bool_list_dec nfae1 [1] = true. auto. Qed. Definition nfae2 := alt (atom eq_nat_dec 1) (atom eq_nat_dec 2). Goal accepts_eps bool_list_dec nfae2 [1] = true. Proof. auto. Qed. Goal forall (A : Type) (nae1 nae2 : bitsNAe A) w, accepts_eps bool_list_dec nae1 w = true -> accepts_eps bool_list_dec (alt nae1 nae2) w = true. Proof. intros A nae1 nae2 w. intros H. induction w. compute. Qed. Variable A: Type. Goal forall nae: bitsNAe A, accepts_eps nae [] -> exists s: list bool, In _ (fin nae) s -> rtrancl (eps nae) (start nae, s). intros nae H. unfold accepts_eps in H. destruct H. destruct H as (H, H'). exists x. intros _. inversion H'. assumption. Qed. Lemma step_imp_next: forall (na : bitsNAe A) (a : option A) (p q : list bool), In _ (step na a) (p, q) -> In _ (next na a p) q. Proof. intros na a p q H. inversion_clear H. assumption. Qed. (*Bon ça prouve le goal suivant mais ça à l'air faux quand meme hein*) Lemma rtrancl_imp_step : forall (na : bitsNAe A) (a : option A) (p q : list bool), rtrancl (step na a) (p, q) -> step na a (p, q). Admitted. Goal forall nae1 nae2: bitsNAe A, accepts_eps nae1 [] -> accepts_eps (alt nae1 nae2) []. intros nae1 nae2 H. induction H. destruct H as (H, H'). unfold accepts_eps. exists (true::x). split. apply finL. assumption. simpl. Print In_steps_nil. apply In_steps_nil. unfold eps. inversion_clear H'. Print rtrancl. apply rtrancl_trans with (b := true::start nae1). apply rtrancl_base. apply In_step. simpl. apply nextNL. apply rtrancl_base. apply In_step. Print nextL. simpl. apply nextL. induction H0. Admitted. Goal forall (nae1 nae2 : bitsNAe A), next (alt nae1 nae2) None [] (true::start nae1). Proof. intros nae1 nae2. apply nextNL. Qed. Goal forall h q (nae1 nae2: bitsNAe A), ((accepts_eps nae1 q) -> accepts_eps (alt nae1 nae2) q) -> accepts_eps nae1 (h::q) -> accepts_eps (alt nae1 nae2) (h::q). Proof. intros h q nae1 nae2 IH H. induction H. destruct H as (H, H'). exists (true::x). split. * apply finL. assumption. * simpl. inversion_clear H'. apply In_steps_cons with (sb := true::sb) (sc := true::sc). apply rtrancl_trans with (true::start nae1). apply rtrancl_base. apply In_step. apply nextNL. apply rtrancl_base. apply In_step. apply nextL. Qed. Goal forall nae1 nae2: bitsNAe A, accepts_eps nae1 [] -> accepts_eps (alt nae1 nae2) []. intros nae1 nae2 H. inversion H as (x, H'). destruct H' as (H', H''). inversion_clear H''. unfold accepts_eps. exists (true::x). split; simpl; try apply finL; try assumption. apply In_steps_nil. apply rtrancl_intro_rtrancl with (b := true::start nae1); try apply rtrancl_refl. apply rtrancl_intro_rtrancl with (b := []); try apply rtrancl_refl. apply In_step. apply nextNL. unfold eps. apply In_step. apply nextL. apply step_imp_next. induction H0. assumption. Qed. Goal forall (w : list A) (nae1 nae2 : bitsNAe A), accepts_eps nae1 w -> accepts_eps (alt nae1 nae2) w. intros w nae1 nae2. induction 1. destruct H as (H, H'). unfold accepts_eps. exists (true::x). split. * simpl. apply finL. assumption. * induction w. ** apply In_steps_nil. simpl. Print rtrancl. apply rtrancl_intro_rtrancl with (b := true::start nae1). *** apply rtrancl_intro_rtrancl with (b := []); try apply rtrancl_refl. unfold eps. apply In_step. simpl. unfold In. Print alt_next. apply nextNL. *** unfold eps. apply In_step. simpl. Print alt_next. Qed. (*Blocage....*) Goal forall (w : list A) (nae1 nae2 : bitsNAe A), accepts_eps nae1 w -> accepts_eps nae2 w -> accepts_eps (alt nae1 nae2) w. unfold accepts_eps. intros w nae1 nae2 H H'. simpl. apply acc_none with (e := (false::(start nae2))). * unfold In. simpl. apply nextNR. * Print accepts_eps_from. induction w. Goal accepts_eps nfae2 [1]. Print acc_cons. apply acc_none with (e := [true; true]). unfold In. simpl. Print nextNL. apply nextNL. Print accepts_eps_from. apply acc_cons with (e := . Goal forall x : nat, accepts (to_nfae (Atom x)) [Some x]. intro x. compute. exists [false]. tauto. Goal accepts nfae1 [Some 1]. Proof. compute. exists [false]. tauto. Qed. Goal accepts nfae1 = L rexp1. Definition rexp2 := Conc (Atom 1) (Atom 2). Definition nfae2 := to_nfae rexp2. Goal accepts nfae2 [Some 1; Some 3]. Proof. unfold accepts. simpl. unfold prepend_list_set. exists [true; false]. split. tauto. exists [false; false]. split; tauto. Qed. Definition rexp3 := Alt (Atom 1) (Atom 2). Definition nfae3 := to_nfae rexp3. Goal accepts nfae3 [Some ] /\ accepts nfae3 [Some 2]. Proof. split; compute. * exists [true; false]. split. intro. discriminate H. reflexivity. Qed. End Test.
%-------------------------------------------------------------------------- % C = lrsc(A,tau) % Low Rank Subspace Clustering algorithm for clean data lying in a % union of subspaces % % C = argmin |C|_* + tau/2 * |A - AC|_F^2 s.t. C = C' % % A: clean data matrix whose columns are points in a union of subspaces % tau: scalar parameter %-------------------------------------------------------------------------- % Adapted from LRSC by @ Rene Vidal, November 2012 %-------------------------------------------------------------------------- function C = clean_relaxed(A,tau) % Make an estimate of tau if necessary if nargin < 2 tau = 100/norm(A)^2; end threshold = 1/sqrt(tau) options = struct; options.lambda = threshold; options.tolerance = 16*eps; M = size(A, 1); options.p0 = ones(M, 1); [~, S, V, details] = spx.fast.lansvd(A, options); r = numel(S); C = V * (eye(r) - diag(1./(S.^2)/tau)) * V'; end
###################################################################### # A full tree on A is a tree that contains A, and also contains {a} # for all a in A. # (Definition defn-full-trees) `is_element/full_trees` := (A::set) -> proc(TT) local a; global reason; if not(`is_element/trees`(A)(TT)) then reason := [convert(procname,string),"TT is not a tree",TT,reason]; return false; fi; if not(member(A,TT)) then reason := [convert(procname,string),"The full set A is not in TT",A,TT]; return false; fi; for a in A do if not(member({a},TT)) then reason := [convert(procname,string),"The singleton {a} is not in TT",a,TT]; return false; fi; od; return true; end; `is_equal/full_trees` := eval(`is_equal/trees`); `is_leq/full_trees` := eval(`is_leq/trees`); # A full tree TT on A is binary if every non-minimal set in TT has # precisely two children. This holds iff |TT| = 2|A|-1. `is_binary/full_trees` := (A) -> proc(TT) return evalb(nops(TT) = 2*nops(A)-1); end: `list_elements/full_trees`:= proc(A::set) local n,a,A1,TTT1,TTT,TT1,T1; # Degenerate cases for small A if A={} then return []; fi; if nops(A)=1 then return [{A}]; fi; # If A is not too small, we write it as {a} union A1. Then we recursively # choose a random tree on A1, and attach a to it. n := nops(A); a := A[n]; A1 := A minus {a}; TTT1 := `list_elements/full_trees`(A1); TTT := []; for TT1 in TTT1 do for T1 in TT1 do TTT := [op(TTT),`attach_to_tree`(A1)(TT1,T1,a,true)]; if n > 2 and nops(T1) > 1 then TTT := [op(TTT),`attach_to_tree`(A1)(TT1,T1,a,false)]; fi; od; od; return TTT; end: # A000311 from OEIS `count_elements/full_trees` := proc(A::set) local n,i,j,k; n := nops(A); if n = 0 then return 0; elif n = 1 then return 1; else return add( (n+k-1)!* add( 1/(k-j)! * add( (2^i*(-1)^(i)*Stirling2(n+j-i-1,j-i))/((n+j-i-1)!*i!), i=0..j), j=1..k), k=1..n-1); fi; end; `random_element/full_trees`:= (A::set) -> proc() local n,a,A1,T0,T1,T,above; # Degenerate cases for small A if A={} then return FAIL; fi; if nops(A)=1 then return {A}; fi; # If A is not too small, we write it as {a} union A1. Then we recursively # choose a random tree on A1, and attach a to it. n := nops(A); a := A[rand(1..n)()]; A1 := A minus {a}; if n = 2 then above := true; else above := evalb(rand(0..1)() = 1); fi; T0 := `random_element/full_trees`(A1)(); T1 := select(U -> nops(U) > 1,T0); if above then T := T0[rand(1..nops(T0))()]; else T := T1[rand(1..nops(T1))()]; fi; T := `attach_to_tree`(A1)(T0,T,a,above); return T; end;
```python %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import pearsonr from scipy.stats import t as tdist ``` # DIY t-test As a first exercise lets try to mimic a t-test using simulated data. As the t-test is just a theoretic representation of what we are doing here, our empirical result from the simulation should be the very close to the theoretical one. To generate a so called null-distribution for the correlation coefficient we repeatedly draw __uncorrelated__ samples from a normal distribution and correlate them with each other saving the result. ```python # Total number of samples nsample = 10000 # Number of observations in each sample nobs = 100 # Initialization of a variable for all our samples r_sample= np.zeros(nsample) # Draw samples and correlate for i in range(nsample): x = np.random.randn(nobs) y = np.random.randn(nobs) r, p = pearsonr(x, y) r_sample[i] = r ``` We can take a look at the samples and how they are distributed using a histogram. Note that they have a mean value of 0. The width of the distribution changes with the number of observations we correlate in each of the samples. Go ahead and give that a try, by changing the value of `nobs` above. ```python plt.hist(r_sample, histtype='step') plt.xlabel('$r$') ``` For the t-test we use the value of $r$ and the number of observations to calculate the test statistic, the t-value using the following formula: \begin{align} t = r \frac{\sqrt{n - 2}}{\sqrt{1 - r^2}} \end{align} below this formula is implemented in a function and than applied to the sample of $r$'s that we have produced above. ```python def calc_t(r, n): """Calculate t statistic for Pearsons r""" t = r * np.sqrt(n - 2) / np.sqrt(1 - r**2) return t ``` ```python t_sample = calc_t(r_sample, nobs) ``` To be able to compare the sample with the theoretical distribution of this variable, the t-distribution we need to have a range of t-values that spans the range of our samples: ```python t_plot = np.linspace(np.min(t_sample), np.max(t_sample), 100) ``` Now we have everything to compare our empirical distribution with the theoretical one: ```python plt.hist(t_sample, histtype='step', density=True, label='empirical') plt.plot(t_plot, tdist.pdf(t_plot, nobs - 2), label='theoretical') plt.legend() ``` They should be a pretty close match as the theory is exactly describing what we have done before, just for infinitly many samples. Lets now compare the $r$ value of the time series in the slides to both the theoretical and empirical ones. Recall. that $r=0.27$ and we had 99 observations in the correlation. ```python r_data = 0.27 nobs = 99 ``` First lets test the value using the classical t-test: ```python t_data = calc_t(r_data, nobs) print('t = %.2f' % t_data) p_theoretical = 2 * (1 - tdist.cdf(t_data, nobs - 2)) print('Theoretical p-value: %.3f' % p_theoretical) ``` Now lets use the code from above to generate a sample for r and for t that we can test these values against. ```python # Total number of samples nsample = 10000 # Number of observations in each sample # Initialization of a variable for all our samples r_sample= np.zeros(nsample) # Draw samples and correlate for i in range(nsample): x = np.random.randn(nobs) y = np.random.randn(nobs) r, p = pearsonr(x, y) r_sample[i] = r t_sample = calc_t(r_sample, nobs) ``` We can test both the fraction of simulated t-values that are larger than the t-value for the data as well as the r-value directly to obtain an empirical p-value for our data. ```python np.mean(np.abs(t_sample) >= t_data) ``` ```python np.mean(np.abs(r_sample) >= r_data) ``` Again, these values should be very close to the theoretical one as they are essenitally generated the same way, just with a finite number of samples. So why was this important, when the result is the same as in the t-test anyway? The t-test as per the theory is not always applicable, depending on the data or the type of statistic that we are looking at. The same is true for any other statistical test. However, as long as you can generate an empirical null-distribution, you will have something to test against. You will not be limited to the special cases that the usual tests are usefull for! So this a very important tool to have.
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module LSI.FrequencyResponse where import Data.Complex import Data.Vector as V hiding (map, zip, foldr) import Linear.V as V import LSI.RationalFunction computeFR :: RealFloat f => RationalFunction d f -> V d f -> Complex f computeFR rf = (computeFR' rf) . V.toList .V.toVector where computeFR' f = case f of Monomial c es -> let fs = map toInteger . V.toList . V.toVector $ es in \vs -> {-# SCC monom #-} let factors = map iexp $ zip zs fs iexp (z, e) | e < 0 = 1/(z^(-e)) iexp (z, e) = z^e zs = map (\w -> mkPolar 1.0 w) vs in (c :+ 0.0) * (foldr (*) 1 factors) Add rf1 rf2 -> let fr1 = computeFR' rf1 fr2 = computeFR' rf2 in \vs -> (fr1 vs) + (fr2 vs) Mul rf1 rf2 -> let fr1 = computeFR' rf1 fr2 = computeFR' rf2 in \vs -> (fr1 vs) * (fr2 vs) Div rf1 rf2 -> let fr1 = computeFR' rf1 fr2 = computeFR' rf2 in \vs -> (fr1 vs) / (fr2 vs)
-- --------------------------------------------------------------- [ GLang.idr ] -- Module : GLang.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] ||| The original unadulterated version of the GRL. module GRL.Lang.GLang import public GRL.Common import public GRL.IR import public GRL.Model import public GRL.Builder import public GRL.Pretty import public GRL.Lang.GLang.Pretty %access export %default total ||| The original unadulterated version of the GRL. data GLang : GTy -> Type where ||| Make a Goal node. MkGoal : String -> Maybe SValue -> GLang ELEM ||| Make a Soft Goal node. MkSoft : String -> Maybe SValue -> GLang ELEM ||| Make a Task node. MkTask : String -> Maybe SValue -> GLang ELEM ||| Make a resource node. MkRes : String -> Maybe SValue -> GLang ELEM ||| Declare an impact relation. MkImpacts : CValue -> GLang ELEM -> GLang ELEM -> GLang INTENT ||| Declare a side-effect relation. MkEffects : CValue -> GLang ELEM -> GLang ELEM -> GLang INTENT ||| And decomposition relation. MkAnd : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT ||| XOR decomposition relation. MkXor : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT ||| IOR decomposition relation. MkIor : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT -- --------------------------------------------------------------- [ Accessors ] ||| Obtain the node's title. getElemTitle : GLang ELEM -> String getElemTitle (MkGoal t _) = t getElemTitle (MkSoft t _) = t getElemTitle (MkTask t _) = t getElemTitle (MkRes t _) = t -- ------------------------------------------------------------ [ Constructors ] mkGoal : String -> GLang ELEM mkGoal t = MkGoal t Nothing mkSoft : String -> GLang ELEM mkSoft t = MkSoft t Nothing mkTask : String -> GLang ELEM mkTask t = MkTask t Nothing mkRes : String -> GLang ELEM mkRes t = MkRes t Nothing mkSatGoal : String -> SValue -> GLang ELEM mkSatGoal t s = MkGoal t (Just s) mkSatSoft : String -> SValue -> GLang ELEM mkSatSoft t s = MkSoft t (Just s) mkSatTask : String -> SValue -> GLang ELEM mkSatTask t s = MkTask t (Just s) mkSatRes : String -> SValue -> GLang ELEM mkSatRes t s = MkRes t (Just s) mkImpacts : CValue -> GLang ELEM -> GLang ELEM -> GLang INTENT mkImpacts = MkImpacts mkEffects : CValue -> GLang ELEM -> GLang ELEM -> GLang INTENT mkEffects = MkEffects mkAnd : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT mkAnd = MkAnd mkIor : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT mkIor = MkIor mkXor : GLang ELEM -> List (GLang ELEM) -> GLang STRUCT mkXor = MkXor -- --------------------------------------------------------------------- [ GRL ] GRL GLang where mkElem (MkGoal s v) = Elem GOALty s v mkElem (MkSoft s v) = Elem SOFTty s v mkElem (MkTask s v) = Elem TASKty s v mkElem (MkRes s v) = Elem RESty s v mkIntent (MkImpacts c a b) = ILink IMPACTSty c (mkElem a) (mkElem b) mkIntent (MkEffects c a b) = ILink AFFECTSty c (mkElem a) (mkElem b) mkStruct (MkAnd a bs) = SLink ANDty (mkElem a) (map mkElem bs) mkStruct (MkXor a bs) = SLink XORty (mkElem a) (map mkElem bs) mkStruct (MkIor a bs) = SLink IORty (mkElem a) (map mkElem bs) -- -------------------------------------------------------------------- [ Sort ] private record DeclGroups where constructor DGroup elems : List (GLang ELEM) intes : List (GLang INTENT) strus : List (GLang STRUCT) private getGroups : DList GTy GLang gs -> DeclGroups getGroups xs = DList.foldr doGrouping (DGroup Nil Nil Nil) xs where doGrouping : GLang ty -> DeclGroups -> DeclGroups doGrouping {ty=ELEM} x g = record {elems = x :: (elems g)} g doGrouping {ty=INTENT} x g = record {intes = x :: (intes g)} g doGrouping {ty=STRUCT} x g = record {strus = x :: (strus g)} g private recoverList : DeclGroups -> (xs ** DList GTy GLang xs) recoverList (DGroup es is ss) = (_ ** (snd es') ++ (snd is') ++ (snd ss')) where es' : (xs ** DList GTy GLang xs) es' = fromList es is' : (ys ** DList GTy GLang ys) is' = fromList is ss' : (zs ** DList GTy GLang zs) ss' = fromList ss groupDecls : DList GTy GLang gs -> (gs' ** DList GTy GLang gs') groupDecls xs = recoverList $ getGroups xs insertDecls : DList GTy GLang gs -> GModel -> GModel insertDecls ds m = doInsert (getGroups ds) m where doInsert' : List (GLang ELEM) -> List (GLang STRUCT) -> List (GLang INTENT) -> GModel -> GModel doInsert' es ss is m = insertGroup es ss is m doInsert : DeclGroups -> GModel -> GModel doInsert (DGroup es is ss) m = doInsert' es ss is m -- -------------------------------------------------------------------- [ Show ] private showElem : GLang ELEM -> String showElem (MkGoal t s) = with List unwords ["[Goal", t, show s, "]"] showElem (MkSoft t s) = with List unwords ["[Soft", t, show s, "]"] showElem (MkTask t s) = with List unwords ["[Task", t, show s, "]"] showElem (MkRes t s) = with List unwords ["[Res" , t, show s, "]"] private showIntent : GLang INTENT -> String showIntent (MkImpacts c a b) = "[Impacts " ++ show c ++ " " ++ showElem a ++ " " ++ showElem b ++ "]" showIntent (MkEffects c a b) = "[Effects " ++ show c ++ " " ++ showElem a ++ " " ++ showElem b ++ "]" private showElems : List (GLang ELEM) -> String showElems ys = "[" ++ (unwords $ intersperse "," (map showElem ys)) ++ "]" private showStruct : GLang STRUCT -> String showStruct (MkAnd a bs) = "[And " ++ showElem a ++ " " ++ showElems bs ++ "]" showStruct (MkXor a bs) = "[And " ++ showElem a ++ " " ++ showElems bs ++ "]" showStruct (MkIor a bs) = "[And " ++ showElem a ++ " " ++ showElems bs ++ "]" private showLang : {ty : GTy} -> GLang ty -> String showLang {ty=ELEM} x = showElem x showLang {ty=INTENT} x = showIntent x showLang {ty=STRUCT} x = showStruct x Show (GLang ty) where show x = showLang x -- ---------------------------------------------------------------------- [ Eq ] private eqGLangE : GLang ELEM -> GLang ELEM -> Bool eqGLangE (MkGoal x t) (MkGoal y u) = x == y && t == u eqGLangE (MkSoft x t) (MkSoft y u) = x == y && t == u eqGLangE (MkTask x t) (MkTask y u) = x == y && t == u eqGLangE (MkRes x t) (MkRes y u) = x == y && t == u eqGLangE _ _ = False private eqGLangI : GLang INTENT -> GLang INTENT -> Bool eqGLangI (MkImpacts c a b) (MkImpacts d x y) = c == d && eqGLangE a x && eqGLangE b y eqGLangI (MkEffects c a b) (MkEffects d x y) = c == d && eqGLangE a x && eqGLangE b y eqGLangI _ _ = False mutual private eqGLangS : GLang STRUCT -> GLang STRUCT -> Bool eqGLangS (MkAnd a as) (MkAnd b bs) = eqGLangE a b && eqGLangList as bs eqGLangS (MkXor a as) (MkXor b bs) = eqGLangE a b && eqGLangList as bs eqGLangS (MkIor a as) (MkIor b bs) = eqGLangE a b && eqGLangList as bs eqGLangS _ _ = False private eqGLangList : List (GLang ELEM) -> List (GLang ELEM) -> Bool eqGLangList Nil Nil = True eqGLangList (x::xs) (y::ys) = if eqGLangE x y then eqGLangList xs ys else False eqGLangList _ _ = False private eqGLang : GLang a -> GLang b -> Bool eqGLang {a=ELEM} {b=ELEM} x y = eqGLangE x y eqGLang {a=INTENT} {b=INTENT} x y = eqGLangI x y eqGLang {a=STRUCT} {b=STRUCT} x y = eqGLangS x y eqGLang _ _ = False Eq (GLang ty) where (==) = eqGLang -- -------------------------------------------------------------- [ Comparable ] cmpGLang : GLang x -> GLang y -> Ordering cmpGLang {x} {y} _ _ = compare x y Ord (GLang ty) where compare x y = cmpGLang x y -- ---------------------------------------------------------------- [ Synonyms ] public export GOAL : Type GOAL = GLang ELEM public export SOFT : Type SOFT = GLang ELEM public export TASK : Type TASK = GLang ELEM public export RES : Type RES = GLang ELEM -- ----------------------------------------------------------- [ Pretty Syntax ] syntax [a] "==>" [b] "|" [c] = mkImpacts c a b syntax [a] "~~>" [b] "|" [c] = mkEffects c a b syntax [a] "&=" [b] = mkAnd a b syntax [a] "X=" [b] = mkXor a b syntax [a] "|=" [b] = mkIor a b -- ---------------------------------------------------------------- [ toString ] -- --------------------------------------------------------------------- [ EOF ]
||| Helper functions to work with `Data.Bits`. module Patricia.BitsUtils import Data.Bits import Data.Fin %default total %access public export ||| Checks if bit at index `i` is set to `0`. isZeroBit : Fin n -> Bits n -> Bool isZeroBit i b = not $ getBit i b ||| Sets the indicated bit to zero and all the lesser bits to one. ||| ||| @i Index of bit to set. ||| @b Target bits. maskInsignificant : (i : Fin n) -> (b : Bits n) -> Bits n maskInsignificant i b = and (b `or` minus m (cast 1)) (complement m) where m : Bits n m = intToBits $ pow 2 (finToNat i) -- TODO: implement more efficiently? ||| Checks if bits key before _branching bit_ matches _prefix_ bits. ||| ||| @i Index of branching bit. ||| @p Prefix bits. ||| @k Key bits. matchPrefix : (i : Fin n) -> (p : Bits n) -> (k : Bits n) -> Bool matchPrefix i p k = maskInsignificant i k == p {- // Fast Imperative implementation for 32bits >>> public static int highestOneBit(int i) { >>> i |= (i >> 1); >>> i |= (i >> 2); >>> i |= (i >> 4); >>> i |= (i >> 8); >>> i |= (i >> 16); >>> return i - (i >>> 1); >>> } -} -- TODO: make it truely total -- 1. Ensure bits value under `b` is not zero -- 2. Ensure `natToFin` returns `Just` (use `fromInteger`?) -- 3. Ensure `shiftGo` returns not zero bits -- TODO: make it fast -- 1. ¯\_(ツ)_/¯ ||| Returns index of highest one bit set in `b`. highestOneBit : Bits (S n) -> Fin (S n) -- TODO: support Bits n -> Fin n ? highestOneBit {n} b = bitsToFin $ shiftGo iterations b oneBit where iterations : Nat iterations = log2NZ (S n) SIsNotZ oneBit : Bits (S n) oneBit = cast 1 shiftGo : Nat -> Bits (S n) -> Bits (S n) -> Bits (S n) shiftGo Z i p = i `minus` (i `shiftRightLogical` oneBit) shiftGo (S k) i p = shiftGo k (i `or` (i `shiftRightArithmetic` p)) (p `shiftLeft` oneBit) bitsToFin : Bits (S n) -> Fin (S n) bitsToFin bits = fromMaybe FZ $ natToFin (log2NZ (toNat $ bitsToInt bits) believe_me) (S n) branchingBit : Bits (S n) -> Bits (S n) -> Fin (S n) branchingBit p0 p1 = highestOneBit $ xor p0 p1
In this notebook, we'll explore chemical reaction balance using python. We'll use atomic balance equations along with Python's built-in sympy package. Notes: 1. v<molecule name> represents the co-efficient of that molecule. ```python import numpy as np import sympy as sm import scipy as sp ``` Methane Combustion Reaction: To balance this equation, we will use atomic balance. For each atom, a balance equation can be written. ```python # creating variables from molecule name sm.var(['vCH4','vO2','vCO2','vH2O']) # writing atomic balance equation in sympy format atom_balances = [ sm.Eq(vCH4 + vCO2, 0), # Carbon (C) balance sm.Eq(4*vCH4 + 2*vH2O, 0), # Hydrogen (H) balance sm.Eq(2*vO2 + 2*vCO2 + vH2O, 0) # Oxygen (O) balance ] # checking the atomic balance equations for eqn in atom_balances: print(eqn) ``` Eq(vCH4 + vCO2, 0) Eq(4*vCH4 + 2*vH2O, 0) Eq(2*vCO2 + vH2O + 2*vO2, 0) Now, we need a basis equation to balance the equations. As, this is a combustion, we can take methane and basis as -1. ```python # basis equation vCH4 and -1 basis_eqn = [sm.Eq(vCH4, -1)] # checking the basis equations for eqn in basis_eqn: print(eqn) ``` Eq(vCH4, -1) Now, let's solve the atom balance equations and basis equations using sympy module. ```python # solving the atomic balance equations balance_one = sm.solve(atom_balances + basis_eqn) print(balance_one) ``` {vCH4: -1, vCO2: 1, vH2O: 2, vO2: -2} So, the balanced co-efficients are saved in a dictionary. For left hand side of the equation, co-efficient is negative and for right-hand side, co-efficient is positive. Let's solve a Complex chemical reaction. Here is the equation: as before, we'll use atomic balance to solve this. ```python atoms = ['K','Fe','S','C','N','Cr','O','H'] # creating variables from molecule name sm.var(['vK4FeSCN6','vK2Cr2O7','vH2SO4','vFe2SO43','vCr2SO43','vCO2','vH2O','vK2SO4','vKNO3']) # writing atomic balance equation in sympy format atom_balances = [ sm.Eq(4*vK4FeSCN6+2*vK2Cr2O7+0*vH2SO4+0*vFe2SO43+0*vCr2SO43+0*vCO2+0*vH2O+2*vK2SO4+vKNO3,0), # Potassium (K) balance sm.Eq(vK4FeSCN6+0*vK2Cr2O7+0*vH2SO4+2*vFe2SO43+0*vCr2SO43+0*vCO2+0*vH2O+0*vK2SO4+0*vKNO3,0), # Iron (Fe) balance sm.Eq(6*vK4FeSCN6+0*vK2Cr2O7+vH2SO4+3*vFe2SO43+3*vCr2SO43+0*vCO2+0*vH2O+vK2SO4+0*vKNO3,0), # Sulfur (S) balance sm.Eq(6*vK4FeSCN6+0*vK2Cr2O7+0*vH2SO4+0*vFe2SO43+0*vCr2SO43+vCO2+0*vH2O+0*vK2SO4+0*vKNO3,0), # Carbon (C) balance sm.Eq(6*vK4FeSCN6+0*vK2Cr2O7+0*vH2SO4+0*vFe2SO43+0*vCr2SO43+0*vCO2+0*vH2O+0*vK2SO4+vKNO3,0), # Nitrogen (N) balance sm.Eq(0*vK4FeSCN6+2*vK2Cr2O7+0*vH2SO4+0*vFe2SO43+2*vCr2SO43+0*vCO2+0*vH2O+0*vK2SO4+0*vKNO3,0), # Chromium (Cr) balance sm.Eq(0*vK4FeSCN6+7*vK2Cr2O7+4*vH2SO4+4*3*vFe2SO43+4*3*vCr2SO43+2*vCO2+vH2O+4*vK2SO4+3*vKNO3,0), # Oxygen (O) balance sm.Eq(0*vK4FeSCN6+0*vK2Cr2O7+2*vH2SO4+0*vFe2SO43+0*vCr2SO43+0*vCO2+vH2O+0*vK2SO4+0*vKNO3,0), # Hydrogen (H) balance ] # checking the atomic balance equations print(atoms) for eqn in atom_balances: print(eqn) ``` ['K', 'Fe', 'S', 'C', 'N', 'Cr', 'O', 'H'] Eq(2*vK2Cr2O7 + 2*vK2SO4 + 4*vK4FeSCN6 + vKNO3, 0) Eq(2*vFe2SO43 + vK4FeSCN6, 0) Eq(3*vCr2SO43 + 3*vFe2SO43 + vH2SO4 + vK2SO4 + 6*vK4FeSCN6, 0) Eq(vCO2 + 6*vK4FeSCN6, 0) Eq(6*vK4FeSCN6 + vKNO3, 0) Eq(2*vCr2SO43 + 2*vK2Cr2O7, 0) Eq(2*vCO2 + 12*vCr2SO43 + 12*vFe2SO43 + vH2O + 4*vH2SO4 + 7*vK2Cr2O7 + 4*vK2SO4 + 3*vKNO3, 0) Eq(vH2O + 2*vH2SO4, 0) ```python # basis equation vK2Cr2O7 and -1 basis_eqn = [sm.Eq(vK2Cr2O7, -1)] # checking the basis equations for eqn in basis_eqn: print(eqn) ``` Eq(vK2Cr2O7, -1) ```python # solving the atomic balance equations balance_two = sm.solve(atom_balances + basis_eqn) # co-efficients of balance equation molecules print(balance_two) ``` {vCO2: -6/43, vCr2SO43: 1, vFe2SO43: -1/86, vH2O: 355/43, vH2SO4: -355/86, vK2Cr2O7: -1, vK2SO4: 44/43, vK4FeSCN6: 1/43, vKNO3: -6/43} ```python ```
||| N-ary congruence for reasoning module Data.Telescope.Congruence import Data.Telescope.Telescope import Data.Telescope.Segment import Data.Telescope.SimpleFun import Data.Telescope.Fun public export congType : (delta : Segment n gamma) -> (env1 : Left.Environment gamma) -> (sy1 : SimpleFun env1 delta Type) -> (lhs : Fun env1 delta sy1) -> (env2 : Left.Environment gamma) -> (sy2 : SimpleFun env2 delta Type) -> (rhs : Fun env2 delta sy2) -> Type congType [] env1 sy1 lhs env2 sy2 rhs = lhs ~=~ rhs congType (ty :: delta) env1 sy1 lhs env2 sy2 rhs = {x1 : ty env1} -> {x2 : ty env2} -> x1 ~=~ x2 -> congType delta (env1 ** x1) (sy1 x1) (lhs x1) (env2 ** x2) (sy2 x2) (rhs x2) public export congSegment : {n : Nat} -> (0 delta : Segment n gamma) ->(0 env1 : Left.Environment gamma)-> (0 sy1 : SimpleFun env1 delta Type) -> (0 lhs : Fun env1 delta sy1) ->(0 env2 : Left.Environment gamma)-> (0 sy2 : SimpleFun env2 delta Type) -> (0 rhs : Fun env2 delta sy2) ->(0 _ : env1 ~=~ env2) -> (0 _ : sy1 ~=~ sy2) -> (0 _ : lhs ~=~ rhs) -> congType delta env1 sy1 lhs env2 sy2 rhs congSegment {n = 0 } [] env sy context env sy context Refl Refl Refl = Refl congSegment {n = S n} (ty :: delta) env sy context env sy context Refl Refl Refl = recursiveCall where recursiveCall : {x1 : ty env} -> {x2 : ty env} -> x1 ~=~ x2 -> congType delta (env ** x1) (sy x1) (context x1) (env ** x2) (sy x2) (context x2) recursiveCall {x1=x} {x2=x} Refl = congSegment delta (env ** x) (sy x) (context x) (env ** x) (sy x) (context x) Refl Refl Refl public export cong : {n : Nat} -> {0 delta : Segment n []} -> {0 sy : SimpleFun () delta Type} -> (context : Fun () delta sy) -> congType delta () sy context () sy context cong {n} {delta} {sy} context = congSegment delta () sy context () sy context Refl Refl Refl
State Before: R : Type u S : Type v T : Type w a b : R n : ℕ inst✝¹ : CommRing R inst✝ : IsDomain R p✝ q p : R[X] ha : a ≠ 0 ⊢ roots (↑C a * p) = roots p State After: no goals Tactic: by_cases hp : p = 0 <;> simp only [roots_mul, *, Ne.def, mul_eq_zero, C_eq_zero, or_self_iff, not_false_iff, roots_C, zero_add, MulZeroClass.mul_zero]
(* Copyright (C) 2020 Susi Lehtola This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) (* prefix: gga_k_lkt_params *params; assert(p->params != NULL); params = (gga_k_lkt_params * )(p->params); *) (* The m_min avoids divisions by zero *) lkt_f0 := s -> 1/cosh(params_a_a * m_min(200, s)) + 5*s^2/3 : lkt_f := x -> lkt_f0(X2S*x): f := (rs, z, xt, xs0, xs1) -> gga_kinetic(lkt_f, rs, z, xs0, xs1):
[STATEMENT] lemma map_of_sorted_Cons: "sorted (a # map fst ps) \<Longrightarrow> x < a \<Longrightarrow> map_of ps x = None" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>sorted (a # map fst ps); x < a\<rbrakk> \<Longrightarrow> map_of ps x = None [PROOF STEP] by (simp add: map_of_None sorted_Cons_le)
[STATEMENT] lemma eOp_simp6[simp]: assumes "\<not> liftAll (\<lambda> eA. eA \<noteq> ERR) ebinp" shows "eOp MOD delta einp ebinp = ERR" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eOp MOD delta einp ebinp = ERR [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<not> liftAll (\<lambda>eA. eA \<noteq> ERR) ebinp goal (1 subgoal): 1. eOp MOD delta einp ebinp = ERR [PROOF STEP] unfolding errMOD_def [PROOF STATE] proof (prove) using this: \<not> liftAll (\<lambda>eA. eA \<noteq> ERR) ebinp goal (1 subgoal): 1. igOp \<lparr>igWls = \<lambda>s eX. case eX of ERR \<Rightarrow> False | OK X \<Rightarrow> igWls MOD s X, igWlsAbs = \<lambda>(us, s) eA. case eA of ERR \<Rightarrow> False | OK A \<Rightarrow> igWlsAbs MOD (us, s) A, igVar = \<lambda>xs x. OK (igVar MOD xs x), igAbs = \<lambda>xs x eX. if eX \<noteq> ERR \<and> (\<exists>s. isInBar (xs, s) \<and> igWls MOD s (check eX)) then OK (igAbs MOD xs x (check eX)) else ERR, igOp = \<lambda>delta einp ebinp. if liftAll (\<lambda>X. X \<noteq> ERR) einp \<and> liftAll (\<lambda>A. A \<noteq> ERR) ebinp \<and> igWlsInp MOD delta (checkI einp) \<and> igWlsBinp MOD delta (checkI ebinp) then OK (igOp MOD delta (checkI einp) (checkI ebinp)) else ERR, igFresh = \<lambda>ys y eX. if eX \<noteq> ERR \<and> (\<exists>s. igWls MOD s (check eX)) then igFresh MOD ys y (check eX) else True, igFreshAbs = \<lambda>ys y eA. if eA \<noteq> ERR \<and> (\<exists>us s. igWlsAbs MOD (us, s) (check eA)) then igFreshAbs MOD ys y (check eA) else True, igSwap = \<lambda>zs z1 z2 eX. if eX \<noteq> ERR \<and> (\<exists>s. igWls MOD s (check eX)) then OK (igSwap MOD zs z1 z2 (check eX)) else ERR, igSwapAbs = \<lambda>zs z1 z2 eA. if eA \<noteq> ERR \<and> (\<exists>us s. igWlsAbs MOD (us, s) (check eA)) then OK (igSwapAbs MOD zs z1 z2 (check eA)) else ERR, igSubst = \<lambda>ys eY y eX. if eY \<noteq> ERR \<and> igWls MOD (asSort ys) (check eY) \<and> eX \<noteq> ERR \<and> (\<exists>s. igWls MOD s (check eX)) then OK (igSubst MOD ys (check eY) y (check eX)) else ERR, igSubstAbs = \<lambda>ys eY y eA. if eY \<noteq> ERR \<and> igWls MOD (asSort ys) (check eY) \<and> eA \<noteq> ERR \<and> (\<exists>us s. igWlsAbs MOD (us, s) (check eA)) then OK (igSubstAbs MOD ys (check eY) y (check eA)) else ERR\<rparr> delta einp ebinp = ERR [PROOF STEP] by auto
[STATEMENT] lemma upper_comp': "y \<in> carrier \<Y> \<Longrightarrow> (\<pi>\<^sub>* \<circ> \<pi>\<^sup>* \<circ> \<pi>\<^sub>*) y = \<pi>\<^sub>* y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. y \<in> carrier \<Y> \<Longrightarrow> (\<pi>\<^sub>* \<circ> \<pi>\<^sup>* \<circ> \<pi>\<^sub>*) y = \<pi>\<^sub>* y [PROOF STEP] by (simp add: upper_comp)
proposition compact_eq_Bolzano_Weierstrass: fixes S :: "'a::metric_space set" shows "compact S \<longleftrightarrow> (\<forall>T. infinite T \<and> T \<subseteq> S \<longrightarrow> (\<exists>x \<in> S. x islimpt T))"
""" ATEMview Location Window """ from PyQt5 import QtCore, QtWidgets import pyqtgraph as pg import numpy as np from .ATEMWidget import ATEMWidget from .colormaps import jetCM, jetBrush class LocWidget(ATEMWidget): """docstring for LocWidget""" def __init__(self, parent): super(LocWidget, self).__init__(parent) self.parent = parent self.init_ui() self.showData = False self.data = None self.tInd = -1 self.x = None self.y = None self.minVal = 1. self.maxVal = 1. self.cbFormatStr = '{:.2f}' self.show() def init_ui(self): """ Docstring """ # Make the background white palette = self.palette() palette.setColor(self.backgroundRole(), QtCore.Qt.white) self.setPalette(palette) self.plotWidget = pg.PlotWidget(enableMenu=False) self.plotWidget.setLabel('left', 'Easting', units='m') self.plotWidget.setLabel('bottom', 'Northing', units='m') self.plotWidget.showGrid(x=True, y=True) self.plotWidget.getViewBox().setAspectLocked() self.scatter = pg.ScatterPlotItem(pen=None, pxMode=True) self.plotWidget.addItem(self.scatter) self.selectedLocVline = pg.InfiniteLine(angle=90, movable=False, pen={'color':'k', 'width':2, 'style':QtCore.Qt.DotLine}) self.plotWidget.addItem(self.selectedLocVline, ignoreBounds=True) self.selectedLocHline = pg.InfiniteLine(angle=0, movable=False, pen={'color':'k', 'width':2, 'style':QtCore.Qt.DotLine}) self.plotWidget.addItem(self.selectedLocHline, ignoreBounds=True) self.plotWidget.scene().sigMouseClicked.connect(self.clickEvent) self.colorbarWidget = pg.PlotWidget(enableMenu=False) self.colorbarWidget.setMaximumWidth(100) self.colorbarWidget.getViewBox().setMouseEnabled(False, False) self.colorbarWidget.setXRange(0, 20, padding=0) self.colorbarWidget.setYRange(0, 256, padding=0) self.colorbarWidget.getAxis('bottom').setPen(None) self.colorbarWidget.getAxis('left').setPen(None) self.colorbarWidget.setVisible(False) self.cbMinLabel = QtWidgets.QLabel() self.cbMinLabel.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) self.cbMinLabel.setText('0.00') self.cbMaxLabel = QtWidgets.QLabel() self.cbMaxLabel.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) self.cbMaxLabel.setText('1.00') self.colorbar = pg.ImageItem() cbData = np.arange(0, 256)[:, np.newaxis].repeat(20, axis=1).T self.colorbar.setImage(jetCM[cbData]) self.colorbarWidget.addItem(self.colorbar) self.misfitCheckBox = QtWidgets.QCheckBox('Show Misfit') self.misfitCheckBox.toggled.connect(self.toggleMisfit) self.selectCombo = QtWidgets.QComboBox() self.selectCombo.addItem("Misfit (time)") self.selectCombo.addItem("Misfit (total)") self.selectCombo.addItem("Observed") self.selectCombo.addItem("Predicted") self.selectCombo.activated[str].connect(self.changeCombo) self.selectCombo.setVisible(False) self.titleLabel = QtWidgets.QLabel(self.selectCombo.currentText()) self.titleLabel.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.titleLabel.setVisible(False) self.maxCvalSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.maxCvalSlider.setMaximum(100) self.maxCvalSlider.setValue(100) self.maxCvalSlider.valueChanged.connect(self.setClim) self.maxCvalSlider.setVisible(False) self.minCvalSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.minCvalSlider.setMaximum(100) self.minCvalSlider.setValue(0) self.minCvalSlider.valueChanged.connect(self.updatePlot) self.minCvalSlider.setVisible(False) cbvLayout = QtWidgets.QVBoxLayout() cbvLayout.addWidget(self.cbMaxLabel) cbvLayout.addWidget(self.colorbarWidget) cbvLayout.addWidget(self.cbMinLabel) hLayout = QtWidgets.QHBoxLayout() hLayout.addWidget(self.plotWidget) hLayout.addLayout(cbvLayout) vLayout = QtWidgets.QVBoxLayout(self) hMisLayout = QtWidgets.QHBoxLayout() hMisLayout.addWidget(self.misfitCheckBox) hMisLayout.addWidget(self.selectCombo) vLayout.addLayout(hMisLayout) vLayout.addWidget(self.titleLabel) vLayout.addLayout(hLayout) vLayout.addWidget(self.maxCvalSlider) vLayout.addWidget(self.minCvalSlider) def clickEvent(self, event): if self.plotWidget.sceneBoundingRect().contains(event.scenePos()): mousePoint = self.plotWidget.getViewBox().mapSceneToView(event.scenePos()) signal = {'name':'closestLoc', 'x':mousePoint.x(), 'y':mousePoint.y()} self.ChangeSelectionSignal.emit(signal) else: pass @QtCore.pyqtSlot(bool) def toggleMisfit(self, show): """ Callback that gets fired 'Show Misfit' box is toggled """ if self.data is not None: if show: self.colorbarWidget.setVisible(True) self.maxCvalSlider.setVisible(True) self.minCvalSlider.setVisible(True) self.selectCombo.setVisible(True) self.titleLabel.setVisible(True) self.showData = True else: self.colorbarWidget.setVisible(False) self.maxCvalSlider.setVisible(False) self.minCvalSlider.setVisible(False) self.selectCombo.setVisible(False) self.titleLabel.setVisible(False) self.updatePlot() @QtCore.pyqtSlot(str) def changeCombo(self, text): if self.selectCombo.currentText() == "Misfit (time)": self.cbFormatStr = "{:.2f}" elif self.selectCombo.currentText() == "Misfit (total)": self.cbFormatStr = "{:.2f}" elif self.selectCombo.currentText() == "Observed": self.cbFormatStr = "{:.2e}" elif self.selectCombo.currentText() == "Predicted": self.cbFormatStr = "{:.2e}" self.titleLabel.setText(text) self.setData() self.updatePlot() def updatePlot(self): if self.showData & (self.data is not None): clMin, clMax = self.getClim() self.cbMaxLabel.setText(self.cbFormatStr.format(clMax)) self.cbMinLabel.setText(self.cbFormatStr.format(clMin)) bins = np.linspace(clMin, clMax, 255) di = np.digitize(self.data, bins) self.scatter.setData(self.x, self.y, pen=None, brush=jetBrush[di], symbolSize=10.) else: self.scatter.setData(self.x, self.y, pen=None, brush='k', symbolSize=10.) def setAll(self, x, y): """ Docstring """ self.scatter.setData(x, y, pen=None, brush='k', symbolSize=10.) self.plotWidget.setXRange(x.min()-100., x.max()+100.) self.plotWidget.setYRange(y.min()-100., y.max()+100.) def setLocation(self, loc): """ Docstring """ xl = loc.iloc[0].x yl = loc.iloc[0].y self.selectedLocVline.setPos(xl) self.selectedLocHline.setPos(yl) def setTime(self, data_times): """ Set the displayed misfit data """ self.tInd = data_times.tInd.iloc[0] if self.selectCombo.currentText() != "Misfit (total)": self.setData() self.updatePlot() def setData(self): data_time = self.parent.data.getTime(self.tInd) self.x = data_time.x.values self.y = data_time.y.values if self.selectCombo.currentText() == "Misfit (time)": if data_time.dBdt_Z_pred.any(): self.data = (data_time.dBdt_Z-data_time.dBdt_Z_pred).abs()/data_time.dBdt_Z_uncert else: self.data = None elif self.selectCombo.currentText() == "Misfit (total)": if data_time.dBdt_Z_pred.any(): grp = self.parent.data.df.groupby('locInd') l22 = lambda g: np.linalg.norm((g.dBdt_Z - g.dBdt_Z_pred)/g.dBdt_Z_uncert)**2/g.shape[0] grp = grp.agg(l22)[['x', 'y', 'dBdt_Z']] self.data = grp.dBdt_Z.values self.x = self.parent.data.locs.sort_index().x.values self.y = self.parent.data.locs.sort_index().y.values print(self.data) else: self.data = None elif self.selectCombo.currentText() == "Observed": self.data = data_time.dBdt_Z elif self.selectCombo.currentText() == "Predicted": self.data = data_time.dBdt_Z_pred else: self.data = None if self.data is not None: self.minVal = self.data.min() self.maxVal = self.data.max() def setClim(self): """ Set the color limits on the misfit scatter plot """ lsVal = self.minCvalSlider.value() hsVal = self.maxCvalSlider.value() if lsVal >= hsVal: self.minCvalSlider.setValue(hsVal-1) lsVal = self.minCvalSlider.value() self.updatePlot() def getClim(self): lsVal = self.minCvalSlider.value() hsVal = self.maxCvalSlider.value() dv = self.data.max()-self.data.min() clMin = self.data.min()+dv*lsVal/100. clMax = self.data.min()+dv*hsVal/100. return clMin, clMax
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.limits.creates import category_theory.sites.sheafification /-! # Limits and colimits of sheaves ## Limits We prove that the forgetful functor from `Sheaf J D` to presheaves creates limits. If the target category `D` has limits (of a certain shape), this then implies that `Sheaf J D` has limits of the same shape and that the forgetful functor preserves these limits. ## Colimits Given a diagram `F : K ⥤ Sheaf J D` of sheaves, and a colimit cocone on the level of presheaves, we show that the cocone obtained by sheafifying the cocone point is a colimit cocone of sheaves. This allows us to show that `Sheaf J D` has colimits (of a certain shape) as soon as `D` does. -/ namespace category_theory namespace Sheaf open category_theory.limits open opposite section limits universes w v u variables {C : Type (max v u)} [category.{v} C] {J : grothendieck_topology C} variables {D : Type w} [category.{max v u} D] variables {K : Type (max v u)} [small_category K] noncomputable theory section /-- An auxiliary definition to be used below. Whenever `E` is a cone of shape `K` of sheaves, and `S` is the multifork associated to a covering `W` of an object `X`, with respect to the cone point `E.X`, this provides a cone of shape `K` of objects in `D`, with cone point `S.X`. See `is_limit_multifork_of_is_limit` for more on how this definition is used. -/ def multifork_evaluation_cone (F : K ⥤ Sheaf J D) (E : cone (F ⋙ Sheaf_to_presheaf J D)) (X : C) (W : J.cover X) (S : multifork (W.index E.X)) : cone (F ⋙ Sheaf_to_presheaf J D ⋙ (evaluation Cᵒᵖ D).obj (op X)) := { X := S.X, π := { app := λ k, (presheaf.is_limit_of_is_sheaf J (F.obj k).1 W (F.obj k).2).lift $ multifork.of_ι _ S.X (λ i, S.ι i ≫ (E.π.app k).app (op i.Y)) begin intros i, simp only [category.assoc], erw [← (E.π.app k).naturality, ← (E.π.app k).naturality], dsimp, simp only [← category.assoc], congr' 1, apply S.condition, end, naturality' := begin intros i j f, dsimp [presheaf.is_limit_of_is_sheaf], rw [category.id_comp], apply presheaf.is_sheaf.hom_ext (F.obj j).2 W, intros ii, erw [presheaf.is_sheaf.amalgamate_map], rw [category.assoc, ← (F.map f).naturality, ← category.assoc], erw [presheaf.is_sheaf.amalgamate_map], dsimp [multifork.of_ι], rw [category.assoc, ← E.w f], simp, end } } variables [has_limits_of_shape K D] /-- If `E` is a cone of shape `K` of sheaves, which is a limit on the level of presheves, this definition shows that the limit presheaf satisfies the multifork variant of the sheaf condition, at a given covering `W`. This is used below in `is_sheaf_of_is_limit` to show that the limit presheaf is indeed a sheaf. -/ def is_limit_multifork_of_is_limit (F : K ⥤ Sheaf J D) (E : cone (F ⋙ Sheaf_to_presheaf J D)) (hE : is_limit E) (X : C) (W : J.cover X) : is_limit (W.multifork E.X) := multifork.is_limit.mk _ (λ S, (is_limit_of_preserves ((evaluation Cᵒᵖ D).obj (op X)) hE).lift $ multifork_evaluation_cone F E X W S) begin intros S i, apply (is_limit_of_preserves ((evaluation Cᵒᵖ D).obj (op i.Y)) hE).hom_ext, intros k, dsimp [multifork.of_ι], erw [category.assoc, (E.π.app k).naturality], dsimp, rw ← category.assoc, erw (is_limit_of_preserves ((evaluation Cᵒᵖ D).obj (op X)) hE).fac (multifork_evaluation_cone F E X W S), dsimp [multifork_evaluation_cone, presheaf.is_limit_of_is_sheaf], erw presheaf.is_sheaf.amalgamate_map, refl, end begin intros S m hm, apply (is_limit_of_preserves ((evaluation Cᵒᵖ D).obj (op X)) hE).hom_ext, intros k, dsimp, erw (is_limit_of_preserves ((evaluation Cᵒᵖ D).obj (op X)) hE).fac, apply presheaf.is_sheaf.hom_ext (F.obj k).2 W, intros i, erw presheaf.is_sheaf.amalgamate_map, dsimp [multifork.of_ι], change _ = S.ι i ≫ _, erw [← hm, category.assoc, ← (E.π.app k).naturality, category.assoc], refl, end /-- If `E` is a cone which is a limit on the level of presheaves, then the limit presheaf is again a sheaf. This is used to show that the forgetful functor from sheaves to presheaves creates limits. -/ lemma is_sheaf_of_is_limit (F : K ⥤ Sheaf J D) (E : cone (F ⋙ Sheaf_to_presheaf J D)) (hE : is_limit E) : presheaf.is_sheaf J E.X := begin rw presheaf.is_sheaf_iff_multifork, intros X S, exact ⟨is_limit_multifork_of_is_limit _ _ hE _ _⟩, end instance (F : K ⥤ Sheaf J D) : creates_limit F (Sheaf_to_presheaf J D) := creates_limit_of_reflects_iso $ λ E hE, { lifted_cone := ⟨⟨E.X, is_sheaf_of_is_limit _ _ hE⟩, ⟨E.π.app, E.π.naturality⟩⟩, valid_lift := cones.ext (eq_to_iso rfl) $ λ j, by { dsimp, simp }, makes_limit := { lift := λ S, hE.lift ((Sheaf_to_presheaf J D).map_cone S), fac' := λ S j, hE.fac ((Sheaf_to_presheaf J D).map_cone S) j, uniq' := λ S m hm, hE.uniq ((Sheaf_to_presheaf J D).map_cone S) m hm } } instance : creates_limits_of_shape K (Sheaf_to_presheaf J D) := {} instance : has_limits_of_shape K (Sheaf J D) := has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape (Sheaf_to_presheaf J D) end instance [has_limits D] : creates_limits (Sheaf_to_presheaf J D) := {} instance [has_limits D] : has_limits (Sheaf J D) := has_limits_of_has_limits_creates_limits (Sheaf_to_presheaf J D) end limits section colimits universes w v u variables {C : Type (max v u)} [category.{v} C] {J : grothendieck_topology C} variables {D : Type w} [category.{max v u} D] variables {K : Type (max v u)} [small_category K] -- Now we need a handful of instances to obtain sheafification... variables [concrete_category.{max v u} D] variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] variables [preserves_limits (forget D)] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)] variables [reflects_isomorphisms (forget D)] /-- Construct a cocone by sheafifying a cocone point of a cocone `E` of presheaves over a functor which factors through sheaves. In `is_colimit_sheafify_cocone`, we show that this is a colimit cocone when `E` is a colimit. -/ @[simps] def sheafify_cocone {F : K ⥤ Sheaf J D} (E : cocone (F ⋙ Sheaf_to_presheaf J D)) : cocone F := { X := ⟨J.sheafify E.X, grothendieck_topology.plus.is_sheaf_plus_plus _ _⟩, ι := { app := λ k, by apply E.ι.app k ≫ J.to_sheafify E.X, -- annoying... naturality' := λ i j f, by erw [category.comp_id, ← category.assoc, E.w f] } } /-- If `E` is a colimit cocone of presheaves, over a diagram factoring through sheaves, then `sheafify_cocone E` is a colimit cocone. -/ @[simps] def is_colimit_sheafify_cocone {F : K ⥤ Sheaf J D} (E : cocone (F ⋙ Sheaf_to_presheaf J D)) (hE : is_colimit E) : is_colimit (sheafify_cocone E) := { desc := λ S, J.sheafify_lift (hE.desc ((Sheaf_to_presheaf J D).map_cocone S)) S.X.2, fac' := begin intros S j, dsimp [sheafify_cocone], erw [category.assoc, J.to_sheafify_sheafify_lift, hE.fac], refl, end, uniq' := begin intros S m hm, apply J.sheafify_lift_unique, apply hE.uniq ((Sheaf_to_presheaf J D).map_cocone S), intros j, erw [← category.assoc, hm j], refl, end } instance [has_colimits_of_shape K D] : has_colimits_of_shape K (Sheaf J D) := ⟨λ F, has_colimit.mk ⟨sheafify_cocone (colimit.cocone _), is_colimit_sheafify_cocone _ (colimit.is_colimit _)⟩⟩ instance [has_colimits D] : has_colimits (Sheaf J D) := ⟨infer_instance⟩ end colimits end Sheaf end category_theory
(**************************************************************) (* Copyright Dominique Larchey-Wendling [*] *) (* *) (* [*] Affiliation LORIA -- CNRS *) (**************************************************************) (* This file is distributed under the terms of the *) (* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *) (**************************************************************) Require Import List Arith Lia. From Undecidability.Shared.Libs.DLW.Utils Require Import utils_tac utils_list finite. From Undecidability.Shared.Libs.DLW.Vec Require Import pos vec. From Undecidability.FOL.TRAKHTENBROT Require Import notations utils fol_ops fo_sig fo_terms fo_logic. Import fol_notations. Set Implicit Arguments. (* * First order definability and closure properties *) Notation ø := vec_nil. Opaque fo_term_subst fo_term_map fo_term_sem. Section fo_definability. Variable (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ)) (X : Type) (M : fo_model Σ X). Definition fot_definable (f : (nat -> X) -> X) := { t | incl (fo_term_syms t) ls /\ forall φ, fo_term_sem M φ t = f φ }. Definition fol_definable (R : (nat -> X) -> Prop) := { A | incl (fol_syms A) ls /\ incl (fol_rels A) lr /\ forall φ, fol_sem M φ A <-> R φ }. (* A FOL definable predicate is always extensional *) Fact fot_def_ext t : fot_definable t -> forall φ ψ, (forall n, φ n = ψ n) -> t φ = t ψ. Proof. intros (k & _ & Hk) phi psi H. rewrite <- Hk, <- Hk; apply fo_term_sem_ext; auto. Qed. Fact fol_def_ext R : fol_definable R -> forall φ ψ, (forall n, φ n = ψ n) -> R φ <-> R ψ. Proof. intros (A & _ & _ & HA) phi psi H. rewrite <- HA, <- HA; apply fol_sem_ext. intros; auto. Qed. (* We derive closure properties *) Fact fot_def_proj n : fot_definable (fun φ => φ n). Proof. exists (£ n); intros; split; rew fot; auto; intros _ []. Qed. Fact fot_def_map (f : nat -> nat) t : fot_definable t -> fot_definable (fun φ => t (fun n => φ (f n))). Proof. intros H; generalize (fot_def_ext H); revert H. intros (k & H1 & H2) H3. exists (fo_term_map f k); split. + rewrite fo_term_syms_map; auto. + intro phi; rewrite <- fo_term_subst_map; rew fot. rewrite H2; apply H3; intro; rew fot; auto. Qed. Fact fot_def_comp s v : In s ls -> (forall p, fot_definable (fun φ => vec_pos (v φ) p)) -> fot_definable (fun φ => fom_syms M s (v φ)). Proof. intros H0 H; apply vec_reif_t in H. destruct H as (w & Hw). exists (in_fot _ w); split; rew fot. + intros x [ -> | H ]; auto; revert H. rewrite in_flat_map. intros (t & H1 & H2). apply in_vec_list, in_vec_inv in H1. destruct H1 as (p & <- ). revert H2; apply Hw. + intros phi; rew fot; f_equal. apply vec_pos_ext; intros p. rewrite vec_pos_map. apply Hw; auto. Qed. Fact fot_def_equiv f g : (forall φ, f φ = g φ) -> fot_definable f -> fot_definable g. Proof. intros E (t & H1 & H2); exists t; split; auto; intro; rewrite H2; auto. Qed. Fact fol_def_atom r v : In r lr -> (forall p, fot_definable (fun φ => vec_pos (v φ) p)) -> fol_definable (fun φ => fom_rels M r (v φ)). Proof. intros H0 H; apply vec_reif_t in H. destruct H as (w & Hw). exists (@fol_atom _ _ w); msplit 2. + simpl; intro s; rewrite in_flat_map. intros (t & H1 & H2). apply in_vec_list, in_vec_inv in H1. destruct H1 as (p & <- ). revert H2; apply Hw. + simpl; intros ? [ -> | [] ]; auto. + intros phi; simpl. apply fol_equiv_ext; f_equal. apply vec_pos_ext; intros p. rewrite vec_pos_map; apply Hw; auto. Qed. Fact fol_def_True : fol_definable (fun _ => True). Proof. exists (⊥⤑⊥); intros; simpl; msplit 2; try red; simpl; tauto. Qed. Fact fol_def_False : fol_definable (fun _ => False). Proof. exists ⊥; intros; simpl; msplit 2; try red; simpl; tauto. Qed. Fact fol_def_equiv R T : (forall φ, R φ <-> T φ) -> fol_definable R -> fol_definable T. Proof. intros H (A & H1 & H2 & H3); exists A; msplit 2; auto; intro; rewrite <- H; auto. Qed. Fact fol_def_conj R T : fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ /\ T φ). Proof. intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_conj A B); msplit 2. 1,2: simpl; intro; rewrite in_app_iff; intros []; auto. intro; simpl; rewrite H3, H6; tauto. Qed. Fact fol_def_disj R T : fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ \/ T φ). Proof. intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_disj A B); msplit 2. 1,2: simpl; intro; rewrite in_app_iff; intros []; auto. intro; simpl; rewrite H3, H6; tauto. Qed. Fact fol_def_imp R T : fol_definable R -> fol_definable T -> fol_definable (fun φ => R φ -> T φ). Proof. intros (A & H1 & H2 & H3) (B & HH4 & H5 & H6); exists (fol_bin fol_imp A B); msplit 2. 1,2: simpl; intro; rewrite in_app_iff; intros []; auto. intro; simpl; rewrite H3, H6; tauto. Qed. Fact fol_def_fa (R : X -> (nat -> X) -> Prop) : fol_definable (fun φ => R (φ 0) (fun n => φ (S n))) -> fol_definable (fun φ => forall x, R x φ). Proof. intros (A & H1 & H2 & H3); exists (fol_quant fol_fa A); msplit 2; auto. intro; simpl; apply forall_equiv. intro; rewrite H3; simpl; tauto. Qed. Fact fol_def_ex (R : X -> (nat -> X) -> Prop) : fol_definable (fun φ => R (φ 0) (fun n => φ (S n))) -> fol_definable (fun φ => exists x, R x φ). Proof. intros (A & H1 & H2 & H3); exists (fol_quant fol_ex A); msplit 2; auto. intro; simpl; apply exists_equiv. intro; rewrite H3; simpl; tauto. Qed. Fact fol_def_list_fa K l (R : K -> (nat -> X) -> Prop) : (forall k, In k l -> fol_definable (R k)) -> fol_definable (fun φ => forall k, In k l -> R k φ). Proof. intros H. set (f := fun k Hk => proj1_sig (H k Hk)). exists (fol_lconj (list_in_map l f)); msplit 2. + rewrite fol_syms_bigop. intros s; simpl; rewrite <- app_nil_end. rewrite in_flat_map. intros (A & H1 & H2). apply In_list_in_map_inv in H1. destruct H1 as (k & Hk & ->). revert H2; apply (proj2_sig (H k Hk)); auto. + rewrite fol_rels_bigop. intros s; simpl; rewrite <- app_nil_end. rewrite in_flat_map. intros (A & H1 & H2). apply In_list_in_map_inv in H1. destruct H1 as (k & Hk & ->). revert H2; apply (proj2_sig (H k Hk)); auto. + intros phi. rewrite fol_sem_lconj; split. * intros H1 k Hk; apply (proj2_sig (H k Hk)), H1. change (In (f k Hk) (list_in_map l f)). apply In_list_in_map. * intros H1 A H2. apply In_list_in_map_inv in H2. destruct H2 as (k & Hk & ->). apply (proj2_sig (H k Hk)); auto. Qed. Fact fol_def_bounded_fa m (R : nat -> (nat -> X) -> Prop) : (forall n, n < m -> fol_definable (R n)) -> fol_definable (fun φ => forall n, n < m -> R n φ). Proof. intros H. apply fol_def_equiv with (R := fun φ => forall n, In n (list_an 0 m) -> R n φ). + intros phi; apply forall_equiv; intro; rewrite list_an_spec; simpl; split; try tauto. intros H1 ?; apply H1; lia. + apply fol_def_list_fa. intros n Hn; apply H; revert Hn; rewrite list_an_spec; lia. Qed. Fact fol_def_list_ex K l (R : K -> (nat -> X) -> Prop) : (forall k, In k l -> fol_definable (R k)) -> fol_definable (fun φ => exists k, In k l /\ R k φ). Proof. intros H. set (f := fun k Hk => proj1_sig (H k Hk)). exists (fol_ldisj (list_in_map l f)); msplit 2. + rewrite fol_syms_bigop. intros s; simpl; rewrite <- app_nil_end. rewrite in_flat_map. intros (A & H1 & H2). apply In_list_in_map_inv in H1. destruct H1 as (k & Hk & ->). revert H2; apply (proj2_sig (H k Hk)); auto. + rewrite fol_rels_bigop. intros s; simpl; rewrite <- app_nil_end. rewrite in_flat_map. intros (A & H1 & H2). apply In_list_in_map_inv in H1. destruct H1 as (k & Hk & ->). revert H2; apply (proj2_sig (H k Hk)); auto. + intros phi. rewrite fol_sem_ldisj; split. * intros (A & H1 & HA). apply In_list_in_map_inv in H1. destruct H1 as (k & Hk & ->). exists k; split; auto. apply (proj2_sig (H k Hk)); auto. * intros (k & Hk & H1). exists (f k Hk); split. - apply In_list_in_map. - apply (proj2_sig (H k Hk)); auto. Qed. Fact fol_def_subst (R : (nat -> X) -> Prop) (f : nat -> (nat -> X) -> X) : (forall n, fot_definable (f n)) -> fol_definable R -> fol_definable (fun φ => R (fun n => f n φ)). Proof. intros H1 H2. generalize (fol_def_ext H2); intros H3. destruct H2 as (A & G1 & G2 & HA). set (rho := fun n => proj1_sig (H1 n)). exists (fol_subst rho A); msplit 2. + red; apply Forall_forall; apply fol_syms_subst. * intros n Hn; rewrite Forall_forall. intro; apply (fun n => proj2_sig (H1 n)). * apply Forall_forall, G1. + rewrite fol_rels_subst; auto. + intros phi. rewrite fol_sem_subst, HA. apply H3; intro; unfold rho; rew fot. apply (fun n => proj2_sig (H1 n)). Qed. End fo_definability. Create HintDb fol_def_db. #[export] Hint Resolve fot_def_proj fot_def_map fot_def_comp fol_def_True fol_def_False : fol_def_db. Tactic Notation "fol" "def" := repeat (( apply fol_def_conj || apply fol_def_disj || apply fol_def_imp || apply fol_def_ex || apply fol_def_fa || (apply fol_def_atom; intro) || apply fol_def_subst); auto with fol_def_db); auto with fol_def_db. Section extra. Variable (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ)) (X : Type) (M : fo_model Σ X). (* More closure properties *) Fact fol_def_iff R T : fol_definable ls lr M R -> fol_definable ls lr M T -> fol_definable ls lr M (fun φ => R φ <-> T φ). Proof. intros; fol def. Qed. Fact fol_def_subst2 R t1 t2 : fol_definable ls lr M (fun φ => R (φ 0) (φ 1)) -> fot_definable ls M t1 -> fot_definable ls M t2 -> fol_definable ls lr M (fun φ => R (t1 φ) (t2 φ)). Proof. intros H1 H2 H3. set (f n := match n with | 0 => t1 | 1 => t2 | _ => fun φ => φ 0 end). change (fol_definable ls lr M (fun φ => R (f 0 φ) (f 1 φ))). apply fol_def_subst with (2 := H1) (f := f). intros [ | [ | n ] ]; simpl; fol def. Qed. Let env_vec (φ : nat -> X) n := vec_set_pos (fun p => φ (@pos2nat n p)). Let env_env (φ : nat -> X) n k := φ (n+k). Fact fol_def_vec_fa n (R : vec X n -> (nat -> X) -> Prop) : (fol_definable ls lr M (fun φ => R (env_vec φ n) (env_env φ n))) -> fol_definable ls lr M (fun φ => forall v, R v φ). Proof. revert R; induction n as [ | n IHn ]; intros R HR. + revert HR; apply fol_def_equiv; intros phi; simpl. split; auto; intros ? v; vec nil v; auto. + set (T φ := forall v x, R (x##v) φ). apply fol_def_equiv with (R := T). * intros phi; unfold T; split. - intros H v; vec split v with x; auto. - intros H ? ?; apply (H (_##_)). * unfold T; apply IHn, fol_def_fa, HR. Qed. Fact fol_def_vec_ex n (R : vec X n -> (nat -> X) -> Prop) : (fol_definable ls lr M (fun φ => R (env_vec φ n) (env_env φ n))) -> fol_definable ls lr M (fun φ => exists v, R v φ). Proof. revert R; induction n as [ | n IHn ]; intros R HR. + revert HR; apply fol_def_equiv; intros phi; simpl. split. * exists vec_nil; auto. * intros (v & Hv); revert Hv; vec nil v; auto. + set (T φ := exists v x, R (x##v) φ). apply fol_def_equiv with (R := T). * intros phi; unfold T; split. - intros (v & x & Hv); exists (x##v); auto. - intros (v & Hv); revert Hv; vec split v with x; exists v, x; auto. * unfold T; apply IHn, fol_def_ex, HR. Qed. Fact fol_def_finite_fa I (R : I -> (nat -> X) -> Prop) : finite_t I -> (forall i, fol_definable ls lr M (R i)) -> fol_definable ls lr M (fun φ => forall i : I, R i φ). Proof. intros (l & Hl) H. apply fol_def_equiv with (R := fun φ => forall i, In i l -> R i φ). + intros phi; apply forall_equiv; intro; split; auto. + apply fol_def_list_fa; auto. Qed. Fact fol_def_finite_ex I (R : I -> (nat -> X) -> Prop) : finite_t I -> (forall i, fol_definable ls lr M (R i)) -> fol_definable ls lr M (fun φ => exists i : I, R i φ). Proof. intros (l & Hl) H. apply fol_def_equiv with (R := fun φ => exists i, In i l /\ R i φ). + intros phi; apply exists_equiv; intro; split; auto; tauto. + apply fol_def_list_ex; auto. Qed. End extra.
(* Title: JinjaThreads/Framework/FWState.thy Author: Andreas Lochbihler *) chapter \<open>The generic multithreaded semantics\<close> section \<open>State of the multithreaded semantics\<close> theory FWState imports "../Basic/Auxiliary" begin datatype lock_action = Lock | Unlock | UnlockFail | ReleaseAcquire datatype ('t,'x,'m) new_thread_action = NewThread 't 'x 'm | ThreadExists 't bool datatype 't conditional_action = Join 't | Yield datatype ('t, 'w) wait_set_action = Suspend 'w | Notify 'w | NotifyAll 'w | WakeUp 't | Notified | WokenUp datatype 't interrupt_action = IsInterrupted 't bool | Interrupt 't | ClearInterrupt 't type_synonym 'l lock_actions = "'l \<Rightarrow>f lock_action list" translations (type) "'l lock_actions" <= (type) "'l \<Rightarrow>f lock_action list" type_synonym ('l,'t,'x,'m,'w,'o) thread_action = "'l lock_actions \<times> ('t,'x,'m) new_thread_action list \<times> 't conditional_action list \<times> ('t, 'w) wait_set_action list \<times> 't interrupt_action list \<times> 'o list" (* pretty printing for thread_action type *) print_translation \<open> let fun tr' [Const (@{type_syntax finfun}, _) $ l $ (Const (@{type_syntax list}, _) $ Const (@{type_syntax lock_action}, _)), Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax new_thread_action}, _) $ t1 $ x $ m)) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax conditional_action}, _) $ t2)) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax wait_set_action}, _) $ t3 $ w)) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax "list"}, _) $ (Const (@{type_syntax "interrupt_action"}, _) $ t4)) $ (Const (@{type_syntax "list"}, _) $ o1))))] = if t1 = t2 andalso t2 = t3 andalso t3 = t4 then Syntax.const @{type_syntax thread_action} $ l $ t1 $ x $ m $ w $ o1 else raise Match; in [(@{type_syntax "prod"}, K tr')] end \<close> typ "('l,'t,'x,'m,'w,'o) thread_action" definition locks_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 'l lock_actions" ("\<lbrace>_\<rbrace>\<^bsub>l\<^esub>" [0] 1000) where "locks_a \<equiv> fst" definition thr_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('t,'x,'m) new_thread_action list" ("\<lbrace>_\<rbrace>\<^bsub>t\<^esub>" [0] 1000) where "thr_a \<equiv> fst o snd" definition cond_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 't conditional_action list" ("\<lbrace>_\<rbrace>\<^bsub>c\<^esub>" [0] 1000) where "cond_a = fst o snd o snd" definition wset_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('t, 'w) wait_set_action list" ("\<lbrace>_\<rbrace>\<^bsub>w\<^esub>" [0] 1000) where "wset_a = fst o snd o snd o snd" definition interrupt_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 't interrupt_action list" ("\<lbrace>_\<rbrace>\<^bsub>i\<^esub>" [0] 1000) where "interrupt_a = fst o snd o snd o snd o snd" definition obs_a :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 'o list" ("\<lbrace>_\<rbrace>\<^bsub>o\<^esub>" [0] 1000) where "obs_a \<equiv> snd o snd o snd o snd o snd" lemma locks_a_conv [simp]: "locks_a (ls, ntsjswss) = ls" by(simp add:locks_a_def) lemma thr_a_conv [simp]: "thr_a (ls, nts, jswss) = nts" by(simp add: thr_a_def) lemma cond_a_conv [simp]: "cond_a (ls, nts, js, wws) = js" by(simp add: cond_a_def) lemma wset_a_conv [simp]: "wset_a (ls, nts, js, wss, isobs) = wss" by(simp add: wset_a_def) lemma interrupt_a_conv [simp]: "interrupt_a (ls, nts, js, ws, is, obs) = is" by(simp add: interrupt_a_def) lemma obs_a_conv [simp]: "obs_a (ls, nts, js, wss, is, obs) = obs" by(simp add: obs_a_def) fun ta_update_locks :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> lock_action \<Rightarrow> 'l \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_locks (ls, nts, js, wss, obs) lta l = (ls(l $:= ls $ l @ [lta]), nts, js, wss, obs)" fun ta_update_NewThread :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('t,'x,'m) new_thread_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_NewThread (ls, nts, js, wss, is, obs) nt = (ls, nts @ [nt], js, wss, is, obs)" fun ta_update_Conditional :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 't conditional_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_Conditional (ls, nts, js, wss, is, obs) j = (ls, nts, js @ [j], wss, is, obs)" fun ta_update_wait_set :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('t, 'w) wait_set_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_wait_set (ls, nts, js, wss, is, obs) ws = (ls, nts, js, wss @ [ws], is, obs)" fun ta_update_interrupt :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 't interrupt_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_interrupt (ls, nts, js, wss, is, obs) i = (ls, nts, js, wss, is @ [i], obs)" fun ta_update_obs :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 'o \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "ta_update_obs (ls, nts, js, wss, is, obs) ob = (ls, nts, js, wss, is, obs @ [ob])" abbreviation empty_ta :: "('l,'t,'x,'m,'w,'o) thread_action" where "empty_ta \<equiv> (K$ [], [], [], [], [], [])" notation (input) empty_ta ("\<epsilon>") text \<open> Pretty syntax for specifying thread actions: Write \<open>\<lbrace> Lock\<rightarrow>l, Unlock\<rightarrow>l, Suspend w, Interrupt t\<rbrace>\<close> instead of @{term "((K$ [])(l $:= [Lock, Unlock]), [], [Suspend w], [Interrupt t], [])"}. \<open>thread_action'\<close> is a type that contains of all basic thread actions. Automatically coerce basic thread actions into that type and then dispatch to the right update function by pattern matching. For coercion, adhoc overloading replaces the generic injection \<open>inject_thread_action\<close> by the specific ones, i.e. constructors. To avoid ambiguities with observable actions, the observable actions must be of sort \<open>obs_action\<close>, which the basic thread action types are not. \<close> class obs_action datatype ('l,'t,'x,'m,'w,'o) thread_action' = LockAction "lock_action \<times> 'l" | NewThreadAction "('t,'x,'m) new_thread_action" | ConditionalAction "'t conditional_action" | WaitSetAction "('t, 'w) wait_set_action" | InterruptAction "'t interrupt_action" | ObsAction 'o setup \<open> Sign.add_const_constraint (@{const_name ObsAction}, SOME @{typ "'o :: obs_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action'"}) \<close> fun thread_action'_to_thread_action :: "('l,'t,'x,'m,'w,'o :: obs_action) thread_action' \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action" where "thread_action'_to_thread_action (LockAction (la, l)) ta = ta_update_locks ta la l" | "thread_action'_to_thread_action (NewThreadAction nt) ta = ta_update_NewThread ta nt" | "thread_action'_to_thread_action (ConditionalAction ca) ta = ta_update_Conditional ta ca" | "thread_action'_to_thread_action (WaitSetAction wa) ta = ta_update_wait_set ta wa" | "thread_action'_to_thread_action (InterruptAction ia) ta = ta_update_interrupt ta ia" | "thread_action'_to_thread_action (ObsAction ob) ta = ta_update_obs ta ob" consts inject_thread_action :: "'a \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action'" nonterminal ta_let and ta_lets syntax "_ta_snoc" :: "ta_lets \<Rightarrow> ta_let \<Rightarrow> ta_lets" ("_,/ _") "_ta_block" :: "ta_lets \<Rightarrow> 'a" ("\<lbrace>_\<rbrace>" [0] 1000) "_ta_empty" :: "ta_lets" ("") "_ta_single" :: "ta_let \<Rightarrow> ta_lets" ("_") "_ta_inject" :: "logic \<Rightarrow> ta_let" ("(_)") "_ta_lock" :: "logic \<Rightarrow> logic \<Rightarrow> ta_let" ("_\<rightarrow>_") translations "_ta_block _ta_empty" == "CONST empty_ta" "_ta_block (_ta_single bta)" == "_ta_block (_ta_snoc _ta_empty bta)" "_ta_inject bta" == "CONST inject_thread_action bta" "_ta_lock la l" == "CONST inject_thread_action (CONST Pair la l)" "_ta_block (_ta_snoc btas bta)" == "CONST thread_action'_to_thread_action bta (_ta_block btas)" adhoc_overloading inject_thread_action NewThreadAction ConditionalAction WaitSetAction InterruptAction ObsAction LockAction lemma ta_upd_proj_simps [simp]: shows ta_obs_proj_simps: "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>ta_update_obs ta obs\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub> @ [obs]" and ta_lock_proj_simps: "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>l\<^esub> = (let ls = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub> in ls(l $:= ls $ l @ [x]))" "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>ta_update_locks ta x l\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" and ta_thread_proj_simps: "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub> @ [t]" "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>ta_update_NewThread ta t\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" and ta_wset_proj_simps: "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub> @ [w]" "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>ta_update_wait_set ta w\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" and ta_cond_proj_simps: "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub> @ [c]" "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>ta_update_Conditional ta c\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" and ta_interrupt_proj_simps: "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub> @ [i]" "\<lbrace>ta_update_interrupt ta i\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" by(cases ta, simp)+ lemma thread_action'_to_thread_action_proj_simps [simp]: shows thread_action'_to_thread_action_proj_locks_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>l\<^esub>" and thread_action'_to_thread_action_proj_nt_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>t\<^esub>" and thread_action'_to_thread_action_proj_cond_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>c\<^esub>" and thread_action'_to_thread_action_proj_wset_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>w\<^esub>" and thread_action'_to_thread_action_proj_interrupt_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>i\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>i\<^esub>" and thread_action'_to_thread_action_proj_obs_simps: "\<lbrace>thread_action'_to_thread_action (LockAction (la, l)) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_locks ta la l\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>thread_action'_to_thread_action (NewThreadAction nt) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_NewThread ta nt\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>thread_action'_to_thread_action (ConditionalAction ca) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_Conditional ta ca\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>thread_action'_to_thread_action (WaitSetAction wa) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_wait_set ta wa\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>thread_action'_to_thread_action (InterruptAction ia) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_interrupt ta ia\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>thread_action'_to_thread_action (ObsAction ob) ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta_update_obs ta ob\<rbrace>\<^bsub>o\<^esub>" by(simp_all) lemmas ta_upd_simps = ta_update_locks.simps ta_update_NewThread.simps ta_update_Conditional.simps ta_update_wait_set.simps ta_update_interrupt.simps ta_update_obs.simps thread_action'_to_thread_action.simps declare ta_upd_simps [simp del] hide_const (open) LockAction NewThreadAction ConditionalAction WaitSetAction InterruptAction ObsAction thread_action'_to_thread_action hide_type (open) thread_action' datatype wake_up_status = WSNotified | WSWokenUp datatype 'w wait_set_status = InWS 'w | PostWS wake_up_status type_synonym 't lock = "('t \<times> nat) option" type_synonym ('l,'t) locks = "'l \<Rightarrow>f 't lock" type_synonym 'l released_locks = "'l \<Rightarrow>f nat" type_synonym ('l,'t,'x) thread_info = "'t \<rightharpoonup> ('x \<times> 'l released_locks)" type_synonym ('w,'t) wait_sets = "'t \<rightharpoonup> 'w wait_set_status" type_synonym 't interrupts = "'t set" type_synonym ('l,'t,'x,'m,'w) state = "('l,'t) locks \<times> (('l,'t,'x) thread_info \<times> 'm) \<times> ('w,'t) wait_sets \<times> 't interrupts" translations (type) "('l, 't) locks" <= (type) "'l \<Rightarrow>f ('t \<times> nat) option" (type) "('l, 't, 'x) thread_info" <= (type) "'t \<rightharpoonup> ('x \<times> ('l \<Rightarrow>f nat))" (* pretty printing for state type *) print_translation \<open> let fun tr' [Const (@{type_syntax finfun}, _) $ l1 $ (Const (@{type_syntax option}, _) $ (Const (@{type_syntax "prod"}, _) $ t1 $ Const (@{type_syntax nat}, _))), Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax fun}, _) $ t2 $ (Const (@{type_syntax option}, _) $ (Const (@{type_syntax "prod"}, _) $ x $ (Const (@{type_syntax finfun}, _) $ l2 $ Const (@{type_syntax nat}, _))))) $ m) $ (Const (@{type_syntax prod}, _) $ (Const (@{type_syntax fun}, _) $ t3 $ (Const (@{type_syntax option}, _) $ (Const (@{type_syntax wait_set_status}, _) $ w))) $ (Const (@{type_syntax fun}, _) $ t4 $ (Const (@{type_syntax bool}, _))))] = if t1 = t2 andalso t1 = t3 andalso t1 = t4 andalso l1 = l2 then Syntax.const @{type_syntax state} $ l1 $ t1 $ x $ m $ w else raise Match; in [(@{type_syntax "prod"}, K tr')] end \<close> typ "('l,'t,'x,'m,'w) state" abbreviation no_wait_locks :: "'l \<Rightarrow>f nat" where "no_wait_locks \<equiv> (K$ 0)" lemma neq_no_wait_locks_conv: "\<And>ln. ln \<noteq> no_wait_locks \<longleftrightarrow> (\<exists>l. ln $ l > 0)" by(auto simp add: expand_finfun_eq fun_eq_iff) lemma neq_no_wait_locksE: fixes ln assumes "ln \<noteq> no_wait_locks" obtains l where "ln $ l > 0" using assms by(auto simp add: neq_no_wait_locks_conv) text \<open> Use type variables for components instead of @{typ "('l,'t,'x,'m,'w) state"} in types for state projections to allow to reuse them for refined state implementations for code generation. \<close> definition locks :: "('locks \<times> ('thread_info \<times> 'm) \<times> 'wsets \<times> 'interrupts) \<Rightarrow> 'locks" where "locks lstsmws \<equiv> fst lstsmws" definition thr :: "('locks \<times> ('thread_info \<times> 'm) \<times> 'wsets \<times> 'interrupts) \<Rightarrow> 'thread_info" where "thr lstsmws \<equiv> fst (fst (snd lstsmws))" definition shr :: "('locks \<times> ('thread_info \<times> 'm) \<times> 'wsets \<times> 'interrupts) \<Rightarrow> 'm" where "shr lstsmws \<equiv> snd (fst (snd lstsmws))" definition wset :: "('locks \<times> ('thread_info \<times> 'm) \<times> 'wsets \<times> 'interrupts) \<Rightarrow> 'wsets" where "wset lstsmws \<equiv> fst (snd (snd lstsmws))" definition interrupts :: "('locks \<times> ('thread_info \<times> 'm) \<times> 'wsets \<times> 'interrupts) \<Rightarrow> 'interrupts" where "interrupts lstsmws \<equiv> snd (snd (snd lstsmws))" lemma locks_conv [simp]: "locks (ls, tsmws) = ls" by(simp add: locks_def) lemma thr_conv [simp]: "thr (ls, (ts, m), ws) = ts" by(simp add: thr_def) lemma shr_conv [simp]: "shr (ls, (ts, m), ws, is) = m" by(simp add: shr_def) lemma wset_conv [simp]: "wset (ls, (ts, m), ws, is) = ws" by(simp add: wset_def) lemma interrupts_conv [simp]: "interrupts (ls, (ts, m), ws, is) = is" by(simp add: interrupts_def) primrec convert_new_thread_action :: "('x \<Rightarrow> 'x') \<Rightarrow> ('t,'x,'m) new_thread_action \<Rightarrow> ('t,'x','m) new_thread_action" where "convert_new_thread_action f (NewThread t x m) = NewThread t (f x) m" | "convert_new_thread_action f (ThreadExists t b) = ThreadExists t b" lemma convert_new_thread_action_inv [simp]: "NewThread t x h = convert_new_thread_action f nta \<longleftrightarrow> (\<exists>x'. nta = NewThread t x' h \<and> x = f x')" "ThreadExists t b = convert_new_thread_action f nta \<longleftrightarrow> nta = ThreadExists t b" "convert_new_thread_action f nta = NewThread t x h \<longleftrightarrow> (\<exists>x'. nta = NewThread t x' h \<and> x = f x')" "convert_new_thread_action f nta = ThreadExists t b \<longleftrightarrow> nta = ThreadExists t b" by(cases nta, auto)+ lemma convert_new_thread_action_eqI: "\<lbrakk> \<And>t x m. nta = NewThread t x m \<Longrightarrow> nta' = NewThread t (f x) m; \<And>t b. nta = ThreadExists t b \<Longrightarrow> nta' = ThreadExists t b \<rbrakk> \<Longrightarrow> convert_new_thread_action f nta = nta'" apply(cases nta) apply fastforce+ done lemma convert_new_thread_action_compose [simp]: "convert_new_thread_action f (convert_new_thread_action g ta) = convert_new_thread_action (f o g) ta" apply(cases ta) apply(simp_all add: convert_new_thread_action_def) done lemma inj_convert_new_thread_action [simp]: "inj (convert_new_thread_action f) = inj f" apply(rule iffI) apply(rule injI) apply(drule_tac x="NewThread undefined x undefined" in injD) apply auto[2] apply(rule injI) apply(case_tac x) apply(auto dest: injD) done lemma convert_new_thread_action_id: "convert_new_thread_action id = (id :: ('t, 'x, 'm) new_thread_action \<Rightarrow> ('t, 'x, 'm) new_thread_action)" (is ?thesis1) "convert_new_thread_action (\<lambda>x. x) = (id :: ('t, 'x, 'm) new_thread_action \<Rightarrow> ('t, 'x, 'm) new_thread_action)" (is ?thesis2) proof - show ?thesis1 by(rule ext)(case_tac x, simp_all) thus ?thesis2 by(simp add: id_def) qed definition convert_extTA :: "('x \<Rightarrow> 'x') \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('l,'t,'x','m,'w,'o) thread_action" where "convert_extTA f ta = (\<lbrace>ta\<rbrace>\<^bsub>l\<^esub>, map (convert_new_thread_action f) \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>, snd (snd ta))" lemma convert_extTA_simps [simp]: "convert_extTA f \<epsilon> = \<epsilon>" "\<lbrace>convert_extTA f ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>convert_extTA f ta\<rbrace>\<^bsub>t\<^esub> = map (convert_new_thread_action f) \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>convert_extTA f ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>convert_extTA f ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>convert_extTA f ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" "convert_extTA f (las, tas, was, cas, is, obs) = (las, map (convert_new_thread_action f) tas, was, cas, is, obs)" apply(simp_all add: convert_extTA_def) apply(cases ta, simp)+ done lemma convert_extTA_eq_conv: "convert_extTA f ta = ta' \<longleftrightarrow> \<lbrace>ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta'\<rbrace>\<^bsub>l\<^esub> \<and> \<lbrace>ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta'\<rbrace>\<^bsub>c\<^esub> \<and> \<lbrace>ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta'\<rbrace>\<^bsub>w\<^esub> \<and> \<lbrace>ta\<rbrace>\<^bsub>o\<^esub> = \<lbrace>ta'\<rbrace>\<^bsub>o\<^esub> \<and> \<lbrace>ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta'\<rbrace>\<^bsub>i\<^esub> \<and> length \<lbrace>ta\<rbrace>\<^bsub>t\<^esub> = length \<lbrace>ta'\<rbrace>\<^bsub>t\<^esub> \<and> (\<forall>n < length \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>. convert_new_thread_action f (\<lbrace>ta\<rbrace>\<^bsub>t\<^esub> ! n) = \<lbrace>ta'\<rbrace>\<^bsub>t\<^esub> ! n)" apply(cases ta, cases ta') apply(auto simp add: convert_extTA_def map_eq_all_nth_conv) done lemma convert_extTA_compose [simp]: "convert_extTA f (convert_extTA g ta) = convert_extTA (f o g) ta" by(simp add: convert_extTA_def) lemma obs_a_convert_extTA [simp]: "obs_a (convert_extTA f ta) = obs_a ta" by(cases ta) simp text \<open>Actions for thread start/finish\<close> datatype 'o action = NormalAction 'o | InitialThreadAction | ThreadFinishAction instance action :: (type) obs_action proof qed definition convert_obs_initial :: "('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> ('l,'t,'x,'m,'w,'o action) thread_action" where "convert_obs_initial ta = (\<lbrace>ta\<rbrace>\<^bsub>l\<^esub>, \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>, \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>, \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>, \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>, map NormalAction \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>)" lemma inj_NormalAction [simp]: "inj NormalAction" by(rule injI) auto lemma convert_obs_initial_inject [simp]: "convert_obs_initial ta = convert_obs_initial ta' \<longleftrightarrow> ta = ta'" by(cases ta)(cases ta', auto simp add: convert_obs_initial_def) lemma convert_obs_initial_empty_TA [simp]: "convert_obs_initial \<epsilon> = \<epsilon>" by(simp add: convert_obs_initial_def) lemma convert_obs_initial_eq_empty_TA [simp]: "convert_obs_initial ta = \<epsilon> \<longleftrightarrow> ta = \<epsilon>" "\<epsilon> = convert_obs_initial ta \<longleftrightarrow> ta = \<epsilon>" by(case_tac [!] ta)(auto simp add: convert_obs_initial_def) lemma convert_obs_initial_simps [simp]: "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>o\<^esub> = map NormalAction \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>l\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>l\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>t\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>t\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>c\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>c\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>w\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>w\<^esub>" "\<lbrace>convert_obs_initial ta\<rbrace>\<^bsub>i\<^esub> = \<lbrace>ta\<rbrace>\<^bsub>i\<^esub>" by(simp_all add: convert_obs_initial_def) type_synonym ('l,'t,'x,'m,'w,'o) semantics = "'t \<Rightarrow> 'x \<times> 'm \<Rightarrow> ('l,'t,'x,'m,'w,'o) thread_action \<Rightarrow> 'x \<times> 'm \<Rightarrow> bool" (* pretty printing for semantics *) print_translation \<open> let fun tr' [t4, Const (@{type_syntax fun}, _) $ (Const (@{type_syntax "prod"}, _) $ x1 $ m1) $ (Const (@{type_syntax fun}, _) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax finfun}, _) $ l $ (Const (@{type_syntax list}, _) $ Const (@{type_syntax lock_action}, _))) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax new_thread_action}, _) $ t1 $ x2 $ m2)) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax conditional_action}, _) $ t2)) $ (Const (@{type_syntax "prod"}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax wait_set_action}, _) $ t3 $ w)) $ (Const (@{type_syntax prod}, _) $ (Const (@{type_syntax list}, _) $ (Const (@{type_syntax interrupt_action}, _) $ t5)) $ (Const (@{type_syntax list}, _) $ o1)))))) $ (Const (@{type_syntax fun}, _) $ (Const (@{type_syntax "prod"}, _) $ x3 $ m3) $ Const (@{type_syntax bool}, _)))] = if x1 = x2 andalso x1 = x3 andalso m1 = m2 andalso m1 = m3 andalso t1 = t2 andalso t2 = t3 andalso t3 = t4 andalso t4 = t5 then Syntax.const @{type_syntax semantics} $ l $ t1 $ x1 $ m1 $ w $ o1 else raise Match; in [(@{type_syntax fun}, K tr')] end \<close> typ "('l,'t,'x,'m,'w,'o) semantics" end
#include "targetver.hpp" #include "../../include/warmane/armory/http.hpp" #include "../../include/warmane/armory/api.hpp" #include "../../include/warmane/armory/site.hpp" #include "../../include/warmane/armory/character.hpp" //#include "../../include/warmane/armory/site/parser/html_parser.hpp" #include "../../include/warmane/armory/site/parser/lex.hpp" //#include "../../include/warmane/armory/guild.hpp" #include <iostream> #include <fstream> #include <thread> #include <boost/range/algorithm/find_if.hpp> #include <fmt/format.h> namespace asio = boost::asio; namespace armory = warmane::armory; void test_api(armory::http::connection& connection, const std::string& name) { //const auto character = armory::load_character(connection, name); ////armory::armory::json obj; ////std::ifstream{"act.json"} >> obj; ////const armory::character character{std::move(obj)}; //std::cout << "name: " << character.name() << '\n'; //std::cout << "class: " << character.player_class() << '\n'; //std::cout << "gender: " << character.gender() << '\n'; //std::cout << "realm: " << character.realm() << '\n'; //std::cout << "online: " << character.online() << '\n'; //std::cout << "level: " << character.level() << '\n'; //std::cout << "faction: " << character.faction() << '\n'; //std::cout << "honorablekills: " << character.honorable_kills() << '\n'; //std::cout << "guild1: " << character.guild() << '\n'; //std::cout << "achievementpoints: " << character.achievement_points() << '\n'; //const auto equipment = character.equipment(); //const auto professions = character.professions(); //for (const auto& item : equipment) // std::cout << "item: " << item.name() << '\n'; //for (const auto& profession : professions) // std::cout << "profession: " << profession.name() << '\n'; //std::cout << "\n"; ////std::ifstream{"carpe.json"} >> obj; ////const armory::guild guild{std::move(obj)}; //const auto guild = armory::load_guild(connection, character); //std::cout << "guild2: " << guild.name() << '\n'; //std::cout << "realm: " << guild.realm() << '\n'; //const auto roster = guild.roster(); //for (const auto& character : roster) //{ // if (character.online()) // std::cout << character.name() << '\n'; //} } int main(int argc, char* argv[]) { namespace chrono = std::chrono; namespace parser = armory::site::parser; try { //auto connection = armory::connect(); std::stringstream html_stream; html_stream << std::ifstream{"profile.html"}.rdbuf(); const std::string html = html_stream.str(); //const auto parser = parser::html_parser{ // parser::patterns::talent1(), // parser::patterns::talent2(), //}; const auto start = chrono::steady_clock::now(); const auto tokens = parser::lex(html); const auto stop = chrono::steady_clock::now(); fmt::print("Took {} milliseconds to lex\n", chrono::duration_cast<chrono::milliseconds>(stop - start).count() ); //boost::find_if(tokens, [](const std::unique_ptr<parser::token>& token) //{ //return token-> //}); //const auto& it = boost::range::find_if(tokens, [](const auto& token) //{ // return token.symbol() == parser::symbol::div; //}); //const auto character // = armory::api::load<armory::character>(connection, "Act"); //const auto character2 //= armory::site::load<armory::character>(connection, "Act"); //std::cout << "hks: " << character.honorable_kills() << "\n\n"; } catch (boost::system::system_error& e) { if (e.code() == asio::error::host_not_found) std::cout << "Unable to resolve hostname: " << armory::hostname << '\n'; else std::cout << "Error: " << e.what() << '\n'; } catch (armory::api::api_error& e) { std::cout << e.what() << '\n'; } catch (armory::json_error& e) { std::cout << e.what() << '\n'; } catch (std::exception& e) { std::cout << e.what(); } return 0; }
Hands on care such as; soft tissue mobilization, myofascial release, joint mobilization, muscle energy techniques and corrective and prescriptive exercises. Thank goodness I found WHPT! She helped me when I thought there was nothing that could be done to alleviate my pain and discomfort. Mansi took the time to really get to know me, my body and my lifestyle so she could provide therapy that was tailored to my needs. She is knowledgable and professional, and she taught me so much about my body that I never knew before. Because of Mansi, I feel like myself again!
[GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n : ℕ h : p ∣ a ^ n ⊢ p ∣ a [PROOFSTEP] induction' n with n ih [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n : ℕ h✝ : p ∣ a ^ n h : p ∣ a ^ Nat.zero ⊢ p ∣ a [PROOFSTEP] rw [pow_zero] at h [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n : ℕ h✝ : p ∣ a ^ n h : p ∣ 1 ⊢ p ∣ a [PROOFSTEP] have := isUnit_of_dvd_one h [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n : ℕ h✝ : p ∣ a ^ n h : p ∣ 1 this : IsUnit p ⊢ p ∣ a [PROOFSTEP] have := not_unit hp [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n : ℕ h✝ : p ∣ a ^ n h : p ∣ 1 this✝ : IsUnit p this : ¬IsUnit p ⊢ p ∣ a [PROOFSTEP] contradiction [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n✝ : ℕ h✝ : p ∣ a ^ n✝ n : ℕ ih : p ∣ a ^ n → p ∣ a h : p ∣ a ^ Nat.succ n ⊢ p ∣ a [PROOFSTEP] rw [pow_succ] at h [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n✝ : ℕ h✝ : p ∣ a ^ n✝ n : ℕ ih : p ∣ a ^ n → p ∣ a h : p ∣ a * a ^ n ⊢ p ∣ a [PROOFSTEP] cases' dvd_or_dvd hp h with dvd_a dvd_pow [GOAL] case succ.inl α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n✝ : ℕ h✝ : p ∣ a ^ n✝ n : ℕ ih : p ∣ a ^ n → p ∣ a h : p ∣ a * a ^ n dvd_a : p ∣ a ⊢ p ∣ a [PROOFSTEP] assumption [GOAL] case succ.inr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α hp✝ hp : Prime p a : α n✝ : ℕ h✝ : p ∣ a ^ n✝ n : ℕ ih : p ∣ a ^ n → p ∣ a h : p ∣ a * a ^ n dvd_pow : p ∣ a ^ n ⊢ p ∣ a [PROOFSTEP] exact ih dvd_pow [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) h : p = 0 ⊢ ↑f p = 0 [PROOFSTEP] simp [h] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h : p ∣ a * b ⊢ p ∣ a ∨ p ∣ b [PROOFSTEP] refine' (hp.2.2 (f a) (f b) <| by convert map_dvd f h simp).imp _ _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h : p ∣ a * b ⊢ ↑f p ∣ ↑f a * ↑f b [PROOFSTEP] convert map_dvd f h [GOAL] case h.e'_4 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h : p ∣ a * b ⊢ ↑f a * ↑f b = ↑f (a * b) [PROOFSTEP] simp [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h : p ∣ a * b ⊢ ↑f p ∣ ↑f a → p ∣ a [PROOFSTEP] intro h [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f a ⊢ p ∣ a [PROOFSTEP] convert ← map_dvd g h [GOAL] case h.e'_3 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f a ⊢ ↑g (↑f p) = p [PROOFSTEP] apply hinv [GOAL] case h.e'_4 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f a ⊢ ↑g (↑f a) = a [PROOFSTEP] apply hinv [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h : p ∣ a * b ⊢ ↑f p ∣ ↑f b → p ∣ b [PROOFSTEP] intro h [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f b ⊢ p ∣ b [PROOFSTEP] convert ← map_dvd g h [GOAL] case h.e'_3 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f b ⊢ ↑g (↑f p) = p [PROOFSTEP] apply hinv [GOAL] case h.e'_4 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α hinv : ∀ (a : α), ↑g (↑f a) = a hp : Prime (↑f p) a b : α h✝ : p ∣ a * b h : ↑f p ∣ ↑f b ⊢ ↑g (↑f b) = b [PROOFSTEP] apply hinv [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α e : α ≃* β h : Prime p a : β ⊢ ↑e (↑(symm e) a) = a [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : CommMonoidWithZero α inst✝² : CommMonoidWithZero β F : Type u_5 G : Type u_6 inst✝¹ : MonoidWithZeroHomClass F α β inst✝ : MulHomClass G β α f : F g : G p : α e : α ≃* β a : α ⊢ ↑(symm e) (↑e a) = a [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α hp : Prime p a b : α ⊢ a ∣ p * b → p ∣ a ∨ a ∣ b [PROOFSTEP] rintro ⟨c, hc⟩ [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α hp : Prime p a b c : α hc : p * b = a * c ⊢ p ∣ a ∨ a ∣ b [PROOFSTEP] rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with (h | ⟨x, rfl⟩) [GOAL] case intro.inl α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α hp : Prime p a b c : α hc : p * b = a * c h : p ∣ a ⊢ p ∣ a ∨ a ∣ b [PROOFSTEP] exact Or.inl h [GOAL] case intro.inr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α hp : Prime p a b x : α hc : p * b = a * (p * x) ⊢ p ∣ a ∨ a ∣ b [PROOFSTEP] rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc [GOAL] case intro.inr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α hp : Prime p a b x : α hc : b = a * x ⊢ p ∣ a ∨ a ∣ b [PROOFSTEP] exact Or.inr (hc.symm ▸ dvd_mul_right _ _) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n : ℕ h : ¬p ∣ a h' : p ^ n ∣ a * b ⊢ p ^ n ∣ b [PROOFSTEP] induction' n with n ih [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n : ℕ h : ¬p ∣ a h'✝ : p ^ n ∣ a * b h' : p ^ Nat.zero ∣ a * b ⊢ p ^ Nat.zero ∣ b [PROOFSTEP] rw [pow_zero] [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n : ℕ h : ¬p ∣ a h'✝ : p ^ n ∣ a * b h' : p ^ Nat.zero ∣ a * b ⊢ 1 ∣ b [PROOFSTEP] exact one_dvd b [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n✝ : ℕ h : ¬p ∣ a h'✝ : p ^ n✝ ∣ a * b n : ℕ ih : p ^ n ∣ a * b → p ^ n ∣ b h' : p ^ Nat.succ n ∣ a * b ⊢ p ^ Nat.succ n ∣ b [PROOFSTEP] obtain ⟨c, rfl⟩ := ih (dvd_trans (pow_dvd_pow p n.le_succ) h') [GOAL] case succ.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α hp : Prime p n✝ : ℕ h : ¬p ∣ a n : ℕ c : α h'✝ : p ^ n✝ ∣ a * (p ^ n * c) ih : p ^ n ∣ a * (p ^ n * c) → p ^ n ∣ p ^ n * c h' : p ^ Nat.succ n ∣ a * (p ^ n * c) ⊢ p ^ Nat.succ n ∣ p ^ n * c [PROOFSTEP] rw [pow_succ'] [GOAL] case succ.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α hp : Prime p n✝ : ℕ h : ¬p ∣ a n : ℕ c : α h'✝ : p ^ n✝ ∣ a * (p ^ n * c) ih : p ^ n ∣ a * (p ^ n * c) → p ^ n ∣ p ^ n * c h' : p ^ Nat.succ n ∣ a * (p ^ n * c) ⊢ p ^ n * p ∣ p ^ n * c [PROOFSTEP] apply mul_dvd_mul_left _ ((hp.dvd_or_dvd _).resolve_left h) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α hp : Prime p n✝ : ℕ h : ¬p ∣ a n : ℕ c : α h'✝ : p ^ n✝ ∣ a * (p ^ n * c) ih : p ^ n ∣ a * (p ^ n * c) → p ^ n ∣ p ^ n * c h' : p ^ Nat.succ n ∣ a * (p ^ n * c) ⊢ p ∣ a * c [PROOFSTEP] rwa [← mul_dvd_mul_iff_left (pow_ne_zero n hp.ne_zero), ← pow_succ', mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n : ℕ h : ¬p ∣ b h' : p ^ n ∣ a * b ⊢ p ^ n ∣ a [PROOFSTEP] rw [mul_comm] at h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α hp : Prime p n : ℕ h : ¬p ∣ b h' : p ^ n ∣ b * a ⊢ p ^ n ∣ a [PROOFSTEP] exact hp.pow_dvd_of_dvd_mul_left n h h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α n : ℕ hp : Prime p hpow : p ^ Nat.succ n ∣ a ^ Nat.succ n * b ^ n hb : ¬p ^ 2 ∣ b ⊢ p ∣ a [PROOFSTEP] cases' hp.dvd_or_dvd ((dvd_pow_self p (Nat.succ_ne_zero n)).trans hpow) with H hbdiv [GOAL] case inl α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α n : ℕ hp : Prime p hpow : p ^ Nat.succ n ∣ a ^ Nat.succ n * b ^ n hb : ¬p ^ 2 ∣ b H : p ∣ a ^ Nat.succ n ⊢ p ∣ a [PROOFSTEP] exact hp.dvd_of_dvd_pow H [GOAL] case inr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a b : α n : ℕ hp : Prime p hpow : p ^ Nat.succ n ∣ a ^ Nat.succ n * b ^ n hb : ¬p ^ 2 ∣ b hbdiv : p ∣ b ^ n ⊢ p ∣ a [PROOFSTEP] obtain ⟨x, rfl⟩ := hp.dvd_of_dvd_pow hbdiv [GOAL] case inr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hpow : p ^ Nat.succ n ∣ a ^ Nat.succ n * (p * x) ^ n hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n ⊢ p ∣ a [PROOFSTEP] obtain ⟨y, hy⟩ := hpow [GOAL] case inr.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n y : α hy : a ^ Nat.succ n * (p * x) ^ n = p ^ Nat.succ n * y ⊢ p ∣ a [PROOFSTEP] have : a ^ n.succ * x ^ n = p * y := by refine' mul_left_cancel₀ (pow_ne_zero n hp.ne_zero) _ rw [← mul_assoc _ p, ← pow_succ', ← hy, mul_pow, ← mul_assoc (a ^ n.succ), mul_comm _ (p ^ n), mul_assoc] -- So `p ∣ a` (and we're done) or `p ∣ x`, which can't be the case since it implies `p^2 ∣ b`. [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n y : α hy : a ^ Nat.succ n * (p * x) ^ n = p ^ Nat.succ n * y ⊢ a ^ Nat.succ n * x ^ n = p * y [PROOFSTEP] refine' mul_left_cancel₀ (pow_ne_zero n hp.ne_zero) _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n y : α hy : a ^ Nat.succ n * (p * x) ^ n = p ^ Nat.succ n * y ⊢ p ^ n * (a ^ Nat.succ n * x ^ n) = p ^ n * (p * y) [PROOFSTEP] rw [← mul_assoc _ p, ← pow_succ', ← hy, mul_pow, ← mul_assoc (a ^ n.succ), mul_comm _ (p ^ n), mul_assoc] -- So `p ∣ a` (and we're done) or `p ∣ x`, which can't be the case since it implies `p^2 ∣ b`. [GOAL] case inr.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n y : α hy : a ^ Nat.succ n * (p * x) ^ n = p ^ Nat.succ n * y this : a ^ Nat.succ n * x ^ n = p * y ⊢ p ∣ a [PROOFSTEP] refine' hp.dvd_of_dvd_pow ((hp.dvd_or_dvd ⟨_, this⟩).resolve_right fun hdvdx => hb _) [GOAL] case inr.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p x : α hb : ¬p ^ 2 ∣ p * x hbdiv : p ∣ (p * x) ^ n y : α hy : a ^ Nat.succ n * (p * x) ^ n = p ^ Nat.succ n * y this : a ^ Nat.succ n * x ^ n = p * y hdvdx : p ∣ x ^ n ⊢ p ^ 2 ∣ p * x [PROOFSTEP] obtain ⟨z, rfl⟩ := hp.dvd_of_dvd_pow hdvdx [GOAL] case inr.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p y z : α hb : ¬p ^ 2 ∣ p * (p * z) hbdiv : p ∣ (p * (p * z)) ^ n hy : a ^ Nat.succ n * (p * (p * z)) ^ n = p ^ Nat.succ n * y this : a ^ Nat.succ n * (p * z) ^ n = p * y hdvdx : p ∣ (p * z) ^ n ⊢ p ^ 2 ∣ p * (p * z) [PROOFSTEP] rw [pow_two, ← mul_assoc] [GOAL] case inr.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p a : α n : ℕ hp : Prime p y z : α hb : ¬p ^ 2 ∣ p * (p * z) hbdiv : p ∣ (p * (p * z)) ^ n hy : a ^ Nat.succ n * (p * (p * z)) ^ n = p ^ Nat.succ n * y this : a ^ Nat.succ n * (p * z) ^ n = p * y hdvdx : p ∣ (p * z) ^ n ⊢ p * p ∣ p * p * z [PROOFSTEP] exact dvd_mul_right _ _ [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x y : α h : Prime p i : ℕ hxy : p ^ (i + 1) ∣ x * y ⊢ p ^ (i + 1) ∣ x ∨ p ∣ y [PROOFSTEP] rw [or_iff_not_imp_right] [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x y : α h : Prime p i : ℕ hxy : p ^ (i + 1) ∣ x * y ⊢ ¬p ∣ y → p ^ (i + 1) ∣ x [PROOFSTEP] intro hy [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x y : α h : Prime p i : ℕ hxy : p ^ (i + 1) ∣ x * y hy : ¬p ∣ y ⊢ p ^ (i + 1) ∣ x [PROOFSTEP] induction' i with i ih generalizing x [GOAL] case zero α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x✝ y : α h : Prime p i : ℕ hxy✝ : p ^ (i + 1) ∣ x✝ * y hy : ¬p ∣ y x : α hxy : p ^ (Nat.zero + 1) ∣ x * y ⊢ p ^ (Nat.zero + 1) ∣ x [PROOFSTEP] rw [pow_one] at hxy ⊢ [GOAL] case zero α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x✝ y : α h : Prime p i : ℕ hxy✝ : p ^ (i + 1) ∣ x✝ * y hy : ¬p ∣ y x : α hxy : p ∣ x * y ⊢ p ∣ x [PROOFSTEP] exact (h.dvd_or_dvd hxy).resolve_right hy [GOAL] case succ α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x✝ y : α h : Prime p i✝ : ℕ hxy✝ : p ^ (i✝ + 1) ∣ x✝ * y hy : ¬p ∣ y i : ℕ ih : ∀ {x : α}, p ^ (i + 1) ∣ x * y → p ^ (i + 1) ∣ x x : α hxy : p ^ (Nat.succ i + 1) ∣ x * y ⊢ p ^ (Nat.succ i + 1) ∣ x [PROOFSTEP] rw [pow_succ] at hxy ⊢ [GOAL] case succ α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x✝ y : α h : Prime p i✝ : ℕ hxy✝ : p ^ (i✝ + 1) ∣ x✝ * y hy : ¬p ∣ y i : ℕ ih : ∀ {x : α}, p ^ (i + 1) ∣ x * y → p ^ (i + 1) ∣ x x : α hxy : p * p ^ (i + 1) ∣ x * y ⊢ p * p ^ (i + 1) ∣ x [PROOFSTEP] obtain ⟨x', rfl⟩ := (h.dvd_or_dvd (dvd_of_mul_right_dvd hxy)).resolve_right hy [GOAL] case succ.intro α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x y : α h : Prime p i✝ : ℕ hxy✝ : p ^ (i✝ + 1) ∣ x * y hy : ¬p ∣ y i : ℕ ih : ∀ {x : α}, p ^ (i + 1) ∣ x * y → p ^ (i + 1) ∣ x x' : α hxy : p * p ^ (i + 1) ∣ p * x' * y ⊢ p * p ^ (i + 1) ∣ p * x' [PROOFSTEP] rw [mul_assoc] at hxy [GOAL] case succ.intro α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : CancelCommMonoidWithZero α p x y : α h : Prime p i✝ : ℕ hxy✝ : p ^ (i✝ + 1) ∣ x * y hy : ¬p ∣ y i : ℕ ih : ∀ {x : α}, p ^ (i + 1) ∣ x * y → p ^ (i + 1) ∣ x x' : α hxy : p * p ^ (i + 1) ∣ p * (x' * y) ⊢ p * p ^ (i + 1) ∣ p * x' [PROOFSTEP] exact mul_dvd_mul_left p (ih ((mul_dvd_mul_iff_left h.ne_zero).mp hxy)) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α ⊢ ¬Irreducible 1 [PROOFSTEP] simp [irreducible_iff] [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α n : ℕ hn : n ≠ 1 ⊢ Irreducible (x ^ n) → IsUnit x [PROOFSTEP] obtain hn | hn := hn.lt_or_lt [GOAL] case inl α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α n : ℕ hn✝ : n ≠ 1 hn : n < 1 ⊢ Irreducible (x ^ n) → IsUnit x [PROOFSTEP] simp only [Nat.lt_one_iff.mp hn, IsEmpty.forall_iff, not_irreducible_one, pow_zero] [GOAL] case inr α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α n : ℕ hn✝ : n ≠ 1 hn : 1 < n ⊢ Irreducible (x ^ n) → IsUnit x [PROOFSTEP] intro h [GOAL] case inr α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α n : ℕ hn✝ : n ≠ 1 hn : 1 < n h : Irreducible (x ^ n) ⊢ IsUnit x [PROOFSTEP] obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_lt hn [GOAL] case inr.intro α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α k : ℕ hn✝ : 1 + k + 1 ≠ 1 hn : 1 < 1 + k + 1 h : Irreducible (x ^ (1 + k + 1)) ⊢ IsUnit x [PROOFSTEP] rw [pow_succ, add_comm] at h [GOAL] case inr.intro α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α k : ℕ hn✝ : 1 + k + 1 ≠ 1 hn : 1 < 1 + k + 1 h : Irreducible (x * x ^ (k + 1)) ⊢ IsUnit x [PROOFSTEP] exact (or_iff_left_of_imp isUnit_pow_succ_iff.mp).mp (of_irreducible_mul h) [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h : ¬IsUnit x ⊢ Irreducible x ∨ ∃ a b, ¬IsUnit a ∧ ¬IsUnit b ∧ a * b = x [PROOFSTEP] haveI := Classical.dec [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h : ¬IsUnit x this : (p : Prop) → Decidable p ⊢ Irreducible x ∨ ∃ a b, ¬IsUnit a ∧ ¬IsUnit b ∧ a * b = x [PROOFSTEP] refine' or_iff_not_imp_right.2 fun H => _ [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h : ¬IsUnit x this : (p : Prop) → Decidable p H : ¬∃ a b, ¬IsUnit a ∧ ¬IsUnit b ∧ a * b = x ⊢ Irreducible x [PROOFSTEP] simp [h, irreducible_iff] at H ⊢ [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h : ¬IsUnit x this : (p : Prop) → Decidable p H : ∀ (x_1 : α), ¬IsUnit x_1 → ∀ (x_2 : α), ¬IsUnit x_2 → ¬x_1 * x_2 = x ⊢ ∀ (a b : α), x = a * b → IsUnit a ∨ IsUnit b [PROOFSTEP] refine' fun a b h => by_contradiction fun o => _ [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h✝ : ¬IsUnit x this : (p : Prop) → Decidable p H : ∀ (x_1 : α), ¬IsUnit x_1 → ∀ (x_2 : α), ¬IsUnit x_2 → ¬x_1 * x_2 = x a b : α h : x = a * b o : ¬(IsUnit a ∨ IsUnit b) ⊢ False [PROOFSTEP] simp [not_or] at o [GOAL] α✝ : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 α : Type u_5 inst✝ : Monoid α x : α h✝ : ¬IsUnit x this : (p : Prop) → Decidable p H : ∀ (x_1 : α), ¬IsUnit x_1 → ∀ (x_2 : α), ¬IsUnit x_2 → ¬x_1 * x_2 = x a b : α h : x = a * b o : ¬IsUnit a ∧ ¬IsUnit b ⊢ False [PROOFSTEP] exact H _ o.1 _ o.2 h.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p q : α hp : Irreducible p hq : Irreducible q ⊢ p ∣ q → q ∣ p [PROOFSTEP] rintro ⟨q', rfl⟩ [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p : α hp : Irreducible p q' : α hq : Irreducible (p * q') ⊢ p * q' ∣ p [PROOFSTEP] rw [IsUnit.mul_right_dvd (Or.resolve_left (of_irreducible_mul hq) hp.not_unit)] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α ⊢ Irreducible (↑a * b) ↔ Irreducible b [PROOFSTEP] simp only [irreducible_iff, Units.isUnit_units_mul, and_congr_right_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α ⊢ ¬IsUnit b → ((∀ (a_2 b_1 : α), ↑a * b = a_2 * b_1 → IsUnit a_2 ∨ IsUnit b_1) ↔ ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1) [PROOFSTEP] refine' fun _ => ⟨fun h A B HAB => _, fun h A B HAB => _⟩ [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), ↑a * b = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ IsUnit A ∨ IsUnit B [PROOFSTEP] rw [← a.isUnit_units_mul] [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), ↑a * b = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ IsUnit (↑a * A) ∨ IsUnit B [PROOFSTEP] apply h [GOAL] case refine'_1.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), ↑a * b = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ ↑a * b = ↑a * A * B [PROOFSTEP] rw [mul_assoc, ← HAB] [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : ↑a * b = A * B ⊢ IsUnit A ∨ IsUnit B [PROOFSTEP] rw [← a⁻¹.isUnit_units_mul] [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : ↑a * b = A * B ⊢ IsUnit (↑a⁻¹ * A) ∨ IsUnit B [PROOFSTEP] apply h [GOAL] case refine'_2.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : ↑a * b = A * B ⊢ b = ↑a⁻¹ * A * B [PROOFSTEP] rw [mul_assoc, ← HAB, Units.inv_mul_cancel_left] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α ⊢ Irreducible (b * ↑a) ↔ Irreducible b [PROOFSTEP] simp only [irreducible_iff, Units.isUnit_mul_units, and_congr_right_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α ⊢ ¬IsUnit b → ((∀ (a_2 b_1 : α), b * ↑a = a_2 * b_1 → IsUnit a_2 ∨ IsUnit b_1) ↔ ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1) [PROOFSTEP] refine' fun _ => ⟨fun h A B HAB => _, fun h A B HAB => _⟩ [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), b * ↑a = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ IsUnit A ∨ IsUnit B [PROOFSTEP] rw [← Units.isUnit_mul_units B a] [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), b * ↑a = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ IsUnit A ∨ IsUnit (B * ↑a) [PROOFSTEP] apply h [GOAL] case refine'_1.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a_1 b_1 : α), b * ↑a = a_1 * b_1 → IsUnit a_1 ∨ IsUnit b_1 A B : α HAB : b = A * B ⊢ b * ↑a = A * (B * ↑a) [PROOFSTEP] rw [← mul_assoc, ← HAB] [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : b * ↑a = A * B ⊢ IsUnit A ∨ IsUnit B [PROOFSTEP] rw [← Units.isUnit_mul_units B a⁻¹] [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : b * ↑a = A * B ⊢ IsUnit A ∨ IsUnit (B * ↑a⁻¹) [PROOFSTEP] apply h [GOAL] case refine'_2.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : αˣ b : α x✝ : ¬IsUnit b h : ∀ (a b_1 : α), b = a * b_1 → IsUnit a ∨ IsUnit b_1 A B : α HAB : b * ↑a = A * B ⊢ b = A * (B * ↑a⁻¹) [PROOFSTEP] rw [← mul_assoc, ← HAB, Units.mul_inv_cancel_right] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α ⊢ Irreducible (a * b) ↔ Irreducible a ∧ IsUnit b ∨ Irreducible b ∧ IsUnit a [PROOFSTEP] constructor [GOAL] case mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α ⊢ Irreducible (a * b) → Irreducible a ∧ IsUnit b ∨ Irreducible b ∧ IsUnit a [PROOFSTEP] refine' fun h => Or.imp (fun h' => ⟨_, h'⟩) (fun h' => ⟨_, h'⟩) (h.isUnit_or_isUnit rfl).symm [GOAL] case mp.refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α h : Irreducible (a * b) h' : IsUnit b ⊢ Irreducible a [PROOFSTEP] rwa [irreducible_mul_isUnit h'] at h [GOAL] case mp.refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α h : Irreducible (a * b) h' : IsUnit a ⊢ Irreducible b [PROOFSTEP] rwa [irreducible_isUnit_mul h'] at h [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α ⊢ Irreducible a ∧ IsUnit b ∨ Irreducible b ∧ IsUnit a → Irreducible (a * b) [PROOFSTEP] rintro (⟨ha, hb⟩ | ⟨hb, ha⟩) [GOAL] case mpr.inl.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α ha : Irreducible a hb : IsUnit b ⊢ Irreducible (a * b) [PROOFSTEP] rwa [irreducible_mul_isUnit hb] [GOAL] case mpr.inr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α hb : Irreducible b ha : IsUnit a ⊢ Irreducible (a * b) [PROOFSTEP] rwa [irreducible_isUnit_mul ha] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : α ha : Irreducible a ⊢ ¬IsSquare a [PROOFSTEP] rintro ⟨b, rfl⟩ [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α b : α ha : Irreducible (b * b) ⊢ False [PROOFSTEP] simp only [irreducible_mul_iff, or_self_iff] at ha [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α b : α ha : Irreducible b ∧ IsUnit b ⊢ False [PROOFSTEP] exact ha.1.not_unit ha.2 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x h : a = 0 ⊢ False [PROOFSTEP] simp [Prime] at * [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x h : a = 0 ⊢ False [PROOFSTEP] rw [h, zero_mul] at hab [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = 0 x✝ : a * b ∣ a x : α hx : a = a * b * x h : a = 0 ⊢ False [PROOFSTEP] have := hp.left [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = 0 x✝ : a * b ∣ a x : α hx : a = a * b * x h : a = 0 this : ¬p = 0 ⊢ False [PROOFSTEP] contradiction [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x ⊢ 1 * a = b * x * a [PROOFSTEP] conv => lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x | 1 * a = b * x * a [PROOFSTEP] lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x | 1 * a = b * x * a [PROOFSTEP] lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x | 1 * a = b * x * a [PROOFSTEP] lhs [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x | 1 * a [PROOFSTEP] rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ a x : α hx : a = a * b * x ⊢ 1 * (a * b * x) = b * x * a [PROOFSTEP] simp [mul_comm, mul_assoc, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x h : b = 0 ⊢ False [PROOFSTEP] simp [Prime] at * [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x h : b = 0 ⊢ False [PROOFSTEP] rw [h, mul_zero] at hab [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = 0 x✝ : a * b ∣ b x : α hx : b = a * b * x h : b = 0 ⊢ False [PROOFSTEP] have := hp.left [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : ¬p = 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b a b : α hab : p = 0 x✝ : a * b ∣ b x : α hx : b = a * b * x h : b = 0 this : ¬p = 0 ⊢ False [PROOFSTEP] contradiction [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x ⊢ 1 * b = a * x * b [PROOFSTEP] conv => lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x | 1 * b = a * x * b [PROOFSTEP] lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x | 1 * b = a * x * b [PROOFSTEP] lhs rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x | 1 * b = a * x * b [PROOFSTEP] lhs [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x | 1 * b [PROOFSTEP] rw [hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α hab : p = a * b x✝ : a * b ∣ b x : α hx : b = a * b * x ⊢ 1 * (a * b * x) = a * x * b [PROOFSTEP] simp [mul_comm, mul_assoc, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α k l : ℕ x✝² : p ^ k ∣ a x✝¹ : p ^ l ∣ b x✝ : p ^ (k + l + 1) ∣ a * b x : α hx : a = p ^ k * x y : α hy : b = p ^ l * y z : α hz : a * b = p ^ (k + l + 1) * z ⊢ p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z) [PROOFSTEP] simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α k l : ℕ x✝² : p ^ k ∣ a x✝¹ : p ^ l ∣ b x✝ : p ^ (k + l + 1) ∣ a * b x : α hx : a = p ^ k * x y : α hy : b = p ^ l * y z : α hz : a * b = p ^ (k + l + 1) * z h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z) hp0 : p ^ (k + l) ≠ 0 ⊢ x * y = p * z [PROOFSTEP] rwa [mul_right_inj' hp0] at h [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α k l : ℕ x✝³ : p ^ k ∣ a x✝² : p ^ l ∣ b x✝¹ : p ^ (k + l + 1) ∣ a * b x : α hx : a = p ^ k * x y : α hy : b = p ^ l * y z : α hz : a * b = p ^ (k + l + 1) * z h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z) hp0 : p ^ (k + l) ≠ 0 hpd : p ∣ x * y x✝ : p ∣ x d : α hd : x = p * d ⊢ a = p ^ (k + 1) * d [PROOFSTEP] simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a✝ p : α hp : Prime p a b : α k l : ℕ x✝³ : p ^ k ∣ a x✝² : p ^ l ∣ b x✝¹ : p ^ (k + l + 1) ∣ a * b x : α hx : a = p ^ k * x y : α hy : b = p ^ l * y z : α hz : a * b = p ^ (k + l + 1) * z h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z) hp0 : p ^ (k + l) ≠ 0 hpd : p ∣ x * y x✝ : p ∣ y d : α hd : y = p * d ⊢ b = p ^ (l + 1) * d [PROOFSTEP] simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α x : α ⊢ x * ↑1 = x [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α x : α u : αˣ ⊢ x * ↑u * ↑u⁻¹ = x [PROOFSTEP] rw [mul_assoc, Units.mul_inv, mul_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α x : α u v : αˣ ⊢ x * ↑(u * v) = x * ↑u * ↑v [PROOFSTEP] rw [Units.val_mul, mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a : α x✝ : IsUnit a c : αˣ h : ↑c = a ⊢ 1 * ↑c = a [PROOFSTEP] simp [h] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a : α h : a ~ᵤ 0 ⊢ a = 0 [PROOFSTEP] let ⟨u, h⟩ := h.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a : α h✝ : a ~ᵤ 0 u : αˣ h : 0 * ↑u = a ⊢ a = 0 [PROOFSTEP] simpa using h.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α u : αˣ h : a * b * ↑u = 1 ⊢ a * (b * ↑u) = 1 [PROOFSTEP] simpa [mul_assoc] using h [GOAL] α : Type u_1 β✝ : Type u_2 γ : Type u_3 δ : Type u_4 β : Type u_5 inst✝ : CommMonoid β a u : β hu : IsUnit u ⊢ u * a ~ᵤ a [PROOFSTEP] rw [mul_comm] [GOAL] α : Type u_1 β✝ : Type u_2 γ : Type u_3 δ : Type u_4 β : Type u_5 inst✝ : CommMonoid β a u : β hu : IsUnit u ⊢ a * u ~ᵤ a [PROOFSTEP] exact associated_mul_unit_left _ _ hu [GOAL] α : Type u_1 β✝ : Type u_2 γ : Type u_3 δ : Type u_4 β : Type u_5 inst✝ : CommMonoid β u a b : β hu : IsUnit u ⊢ u * a ~ᵤ b ↔ a ~ᵤ b [PROOFSTEP] rw [mul_comm] [GOAL] α : Type u_1 β✝ : Type u_2 γ : Type u_3 δ : Type u_4 β : Type u_5 inst✝ : CommMonoid β u a b : β hu : IsUnit u ⊢ a * u ~ᵤ b ↔ a ~ᵤ b [PROOFSTEP] exact associated_mul_isUnit_left_iff hu [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a₁ a₂ b₁ b₂ : α c₁ : αˣ h₁ : a₁ * ↑c₁ = b₁ c₂ : αˣ h₂ : a₂ * ↑c₂ = b₂ ⊢ a₁ * a₂ * ↑(c₁ * c₂) = b₁ * b₂ [PROOFSTEP] simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α n : ℕ h : a ~ᵤ b ⊢ a ^ n ~ᵤ b ^ n [PROOFSTEP] induction' n with n ih [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α h : a ~ᵤ b ⊢ a ^ Nat.zero ~ᵤ b ^ Nat.zero [PROOFSTEP] simp [h] [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α h : a ~ᵤ b ⊢ 1 ~ᵤ 1 [PROOFSTEP] rfl [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α h : a ~ᵤ b n : ℕ ih : a ^ n ~ᵤ b ^ n ⊢ a ^ Nat.succ n ~ᵤ b ^ Nat.succ n [PROOFSTEP] convert h.mul_mul ih [GOAL] case h.e'_3 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α h : a ~ᵤ b n : ℕ ih : a ^ n ~ᵤ b ^ n ⊢ a ^ Nat.succ n = a * a ^ n [PROOFSTEP] rw [pow_succ] [GOAL] case h.e'_4 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α h : a ~ᵤ b n : ℕ ih : a ^ n ~ᵤ b ^ n ⊢ b ^ Nat.succ n = b * b ^ n [PROOFSTEP] rw [pow_succ] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a b : α hab : a ∣ b hba : b ∣ a ⊢ a ~ᵤ b [PROOFSTEP] rcases hab with ⟨c, rfl⟩ [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c : α hba : a * c ∣ a ⊢ a ~ᵤ a * c [PROOFSTEP] rcases hba with ⟨d, a_eq⟩ [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ⊢ a ~ᵤ a * c [PROOFSTEP] by_cases ha0 : a = 0 [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : a = 0 ⊢ a ~ᵤ a * c [PROOFSTEP] simp_all [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α ha0 : a = 0 ⊢ 0 ~ᵤ 0 [PROOFSTEP] rfl [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 ⊢ a ~ᵤ a * c [PROOFSTEP] have hac0 : a * c ≠ 0 := by intro con rw [con, zero_mul] at a_eq apply ha0 a_eq [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 ⊢ a * c ≠ 0 [PROOFSTEP] intro con [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 con : a * c = 0 ⊢ False [PROOFSTEP] rw [con, zero_mul] at a_eq [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = 0 ha0 : ¬a = 0 con : a * c = 0 ⊢ False [PROOFSTEP] apply ha0 a_eq [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 ⊢ a ~ᵤ a * c [PROOFSTEP] have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 ⊢ a * (c * d) = a * 1 [PROOFSTEP] rw [← mul_assoc, ← a_eq, mul_one] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 this : a * (c * d) = a * 1 ⊢ a ~ᵤ a * c [PROOFSTEP] have hcd : c * d = 1 := mul_left_cancel₀ ha0 this [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 this : a * (c * d) = a * 1 hcd : c * d = 1 ⊢ a ~ᵤ a * c [PROOFSTEP] have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 this : a * (c * d) = a * 1 hcd : c * d = 1 ⊢ a * c * (d * c) = a * c * 1 [PROOFSTEP] rw [← mul_assoc, ← a_eq, mul_one] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 this✝ : a * (c * d) = a * 1 hcd : c * d = 1 this : a * c * (d * c) = a * c * 1 ⊢ a ~ᵤ a * c [PROOFSTEP] have hdc : d * c = 1 := mul_left_cancel₀ hac0 this [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelMonoidWithZero α a c d : α a_eq : a = a * c * d ha0 : ¬a = 0 hac0 : a * c ≠ 0 this✝ : a * (c * d) = a * 1 hcd : c * d = 1 this : a * c * (d * c) = a * c * 1 hdc : d * c = 1 ⊢ a ~ᵤ a * c [PROOFSTEP] exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a b : α h : a ~ᵤ b ha : a = 0 ⊢ b = 0 [PROOFSTEP] let ⟨u, hu⟩ := h [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a b : α h : a ~ᵤ b ha : a = 0 u : αˣ hu : a * ↑u = b ⊢ b = 0 [PROOFSTEP] simp [hu.symm, ha] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a b : α h : a ~ᵤ b hb : b = 0 ⊢ a = 0 [PROOFSTEP] let ⟨u, hu⟩ := h.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : MonoidWithZero α a b : α h : a ~ᵤ b hb : b = 0 u : αˣ hu : b * ↑u = a ⊢ a = 0 [PROOFSTEP] simp [hu.symm, hb] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α h : p ~ᵤ q hp : Prime p u : αˣ hu : p * ↑u = q x✝ : IsUnit q v : αˣ hv : ↑v = q ⊢ ↑(v * u⁻¹) = p [PROOFSTEP] simp [hv, hu.symm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α h : p ~ᵤ q hp : Prime p u : αˣ hu : p * ↑u = q ⊢ ∀ (a b : α), p * ↑u ∣ a * b → p * ↑u ∣ a ∨ p * ↑u ∣ b [PROOFSTEP] simp [Units.mul_right_dvd] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α h : p ~ᵤ q hp : Prime p u : αˣ hu : p * ↑u = q ⊢ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] intro a b [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α h : p ~ᵤ q hp : Prime p u : αˣ hu : p * ↑u = q a b : α ⊢ p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] exact hp.dvd_or_dvd [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α a b : α h : a ~ᵤ b u : αˣ hu : a * ↑u = b x✝ : IsUnit a v : αˣ hv : ↑v = a ⊢ ↑(v * u) = b [PROOFSTEP] simp [hv, hu.symm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p q : α h : p ~ᵤ q hp : Irreducible p u : αˣ hu : p * ↑u = q a b : α hab : q = a * b ⊢ p = p * ↑u * ↑u⁻¹ [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p q : α h : p ~ᵤ q hp : Irreducible p u : αˣ hu : p * ↑u = q a b : α hab : q = a * b ⊢ p * ↑u * ↑u⁻¹ = a * (b * ↑u⁻¹) [PROOFSTEP] rw [hu] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p q : α h : p ~ᵤ q hp : Irreducible p u : αˣ hu : p * ↑u = q a b : α hab : q = a * b ⊢ q * ↑u⁻¹ = a * (b * ↑u⁻¹) [PROOFSTEP] simp [hab, mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : Monoid α p q : α h : p ~ᵤ q hp : Irreducible p u : αˣ hu : p * ↑u = q a b : α hab : q = a * b hpab : p = a * (b * ↑u⁻¹) x✝ : IsUnit (b * ↑u⁻¹) v : αˣ hv : ↑v = b * ↑u⁻¹ ⊢ ↑(v * u) = b [PROOFSTEP] simp [hv] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a b c d : α h : a * b ~ᵤ c * d h₁ : a ~ᵤ c ha : a ≠ 0 u : αˣ hu : a * b * ↑u = c * d v : αˣ hv : c * ↑v = a ⊢ a * (b * ↑(u * v)) = a * d [PROOFSTEP] rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a b c d : α h : a * b ~ᵤ c * d h₁ : a ~ᵤ c ha : a ≠ 0 u : αˣ hu : a * b * ↑u = c * d v : αˣ hv : c * ↑v = a ⊢ c * ↑v * (b * ↑(u * v)) = ↑v * (a * b * ↑u) [PROOFSTEP] simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a b c d : α ⊢ a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c [PROOFSTEP] rw [mul_comm a, mul_comm c] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a b c d : α ⊢ b * a ~ᵤ d * c → b ~ᵤ d → b ≠ 0 → a ~ᵤ c [PROOFSTEP] exact Associated.of_mul_left [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p₁ p₂ : α k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ ⊢ p₁ ~ᵤ p₂ [PROOFSTEP] have : p₁ ∣ p₂ ^ k₂ := by rw [← h.dvd_iff_dvd_right] apply dvd_pow_self _ hk₁.ne' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p₁ p₂ : α k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ ⊢ p₁ ∣ p₂ ^ k₂ [PROOFSTEP] rw [← h.dvd_iff_dvd_right] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p₁ p₂ : α k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ ⊢ p₁ ∣ p₁ ^ k₁ [PROOFSTEP] apply dvd_pow_self _ hk₁.ne' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p₁ p₂ : α k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ this : p₁ ∣ p₂ ^ k₂ ⊢ p₁ ~ᵤ p₂ [PROOFSTEP] rw [← hp₁.dvd_prime_iff_associated hp₂] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p₁ p₂ : α k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ this : p₁ ∣ p₂ ^ k₂ ⊢ p₁ ∣ p₂ [PROOFSTEP] exact hp₁.dvd_of_dvd_pow this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x y : α ⊢ x ~ᵤ y ↔ x = y [PROOFSTEP] constructor [GOAL] case mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x y : α ⊢ x ~ᵤ y → x = y [PROOFSTEP] rintro ⟨c, rfl⟩ [GOAL] case mp.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x : α c : αˣ ⊢ x = x * ↑c [PROOFSTEP] rw [units_eq_one c, Units.val_one, mul_one] [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x y : α ⊢ x = y → x ~ᵤ y [PROOFSTEP] rintro rfl [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x : α ⊢ x ~ᵤ x [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ ⊢ Associated = Eq [PROOFSTEP] ext [GOAL] case h.h.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Unique αˣ x✝¹ x✝ : α ⊢ x✝¹ ~ᵤ x✝ ↔ x✝¹ = x✝ [PROOFSTEP] rw [associated_iff_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝³ : Monoid α inst✝² : Unique αˣ M : Type u_5 inst✝¹ : CancelCommMonoidWithZero M inst✝ : Unique Mˣ p q : M pp : Prime p qp : Prime q ⊢ p ∣ q ↔ p = q [PROOFSTEP] rw [pp.dvd_prime_iff_associated qp, ← associated_eq_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 R : Type u_5 inst✝¹ : CancelCommMonoidWithZero R inst✝ : Unique Rˣ p₁ p₂ : R k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h : p₁ ^ k₁ = p₂ ^ k₂ ⊢ p₁ = p₂ [PROOFSTEP] rw [← associated_iff_eq] at h ⊢ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 R : Type u_5 inst✝¹ : CancelCommMonoidWithZero R inst✝ : Unique Rˣ p₁ p₂ : R k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₁ h✝ : p₁ ^ k₁ = p₂ ^ k₂ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ ⊢ p₁ ~ᵤ p₂ [PROOFSTEP] apply h.of_pow_associated_of_prime hp₁ hp₂ hk₁ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 R : Type u_5 inst✝¹ : CancelCommMonoidWithZero R inst✝ : Unique Rˣ p₁ p₂ : R k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₂ h : p₁ ^ k₁ = p₂ ^ k₂ ⊢ p₁ = p₂ [PROOFSTEP] rw [← associated_iff_eq] at h ⊢ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 R : Type u_5 inst✝¹ : CancelCommMonoidWithZero R inst✝ : Unique Rˣ p₁ p₂ : R k₁ k₂ : ℕ hp₁ : Prime p₁ hp₂ : Prime p₂ hk₁ : 0 < k₂ h✝ : p₁ ^ k₁ = p₂ ^ k₂ h : p₁ ^ k₁ ~ᵤ p₂ ^ k₂ ⊢ p₁ ~ᵤ p₂ [PROOFSTEP] apply h.of_pow_associated_of_prime' hp₁ hp₂ hk₁ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Subsingleton α a : Associates α ⊢ a = default [PROOFSTEP] apply Quotient.recOnSubsingleton₂ [GOAL] case g α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Subsingleton α a : Associates α ⊢ ∀ (a b : α), Quotient.mk (Associated.setoid α) a = Quotient.mk (Associated.setoid α) b [PROOFSTEP] intro a b [GOAL] case g α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Subsingleton α a✝ : Associates α a b : α ⊢ Quotient.mk (Associated.setoid α) a = Quotient.mk (Associated.setoid α) b [PROOFSTEP] congr [GOAL] case g.e_a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : Monoid α inst✝ : Subsingleton α a✝ : Associates α a b : α ⊢ a = b [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' b' : Associates α a₁ a₂ b₁ b₂ : α x✝¹ : a₁ ≈ b₁ x✝ : a₂ ≈ b₂ c₁ : αˣ h₁ : a₁ * ↑c₁ = b₁ c₂ : αˣ h₂ : a₂ * ↑c₂ = b₂ ⊢ a₁ * a₂ * ↑(c₁ * c₂) = b₁ * b₂ [PROOFSTEP] rw [← h₁, ← h₂] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' b' : Associates α a₁ a₂ b₁ b₂ : α x✝¹ : a₁ ≈ b₁ x✝ : a₂ ≈ b₂ c₁ : αˣ h₁ : a₁ * ↑c₁ = b₁ c₂ : αˣ h₂ : a₂ * ↑c₂ = b₂ ⊢ a₁ * a₂ * ↑(c₁ * c₂) = a₁ * ↑c₁ * (a₂ * ↑c₂) [PROOFSTEP] simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' b' c' : Associates α a b c : α ⊢ Quotient.mk (Associated.setoid α) (a * b * c) = Quotient.mk (Associated.setoid α) (a * (b * c)) [PROOFSTEP] rw [mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' : Associates α a : α ⊢ Quotient.mk (Associated.setoid α) (1 * a) = Quotient.mk (Associated.setoid α) a [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' : Associates α a : α ⊢ Quotient.mk (Associated.setoid α) (a * 1) = Quotient.mk (Associated.setoid α) a [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a' b' : Associates α a b : α ⊢ Quotient.mk (Associated.setoid α) (a * b) = Quotient.mk (Associated.setoid α) (b * a) [PROOFSTEP] rw [mul_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : α n : ℕ ⊢ Associates.mk (a ^ n) = Associates.mk a ^ n [PROOFSTEP] induction n [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : α ⊢ Associates.mk (a ^ Nat.zero) = Associates.mk a ^ Nat.zero [PROOFSTEP] simp [*, pow_succ, Associates.mk_mul_mk.symm] [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : α n✝ : ℕ n_ih✝ : Associates.mk (a ^ n✝) = Associates.mk a ^ n✝ ⊢ Associates.mk (a ^ Nat.succ n✝) = Associates.mk a ^ Nat.succ n✝ [PROOFSTEP] simp [*, pow_succ, Associates.mk_mul_mk.symm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α x y : Associates α a b : α h : Quotient.mk (Associated.setoid α) a * Quotient.mk (Associated.setoid α) b = 1 this : a * b ~ᵤ 1 ⊢ b * ?m.284131 a b h this ~ᵤ 1 [PROOFSTEP] rwa [mul_comm] at this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α x y : Associates α ⊢ x = 1 ∧ y = 1 → x * y = 1 [PROOFSTEP] simp (config := { contextual := true }) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α u : (Associates α)ˣ ⊢ ↑u = 1 [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : Associates α ⊢ IsUnit a ↔ a = ⊥ [PROOFSTEP] rw [Associates.isUnit_iff_eq_one, bot_eq_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a : α ⊢ IsUnit (Associates.mk a) ↔ a ~ᵤ 1 [PROOFSTEP] rw [isUnit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b c d : Associates α h₁ : a ≤ b h₂ : c ≤ d x : Associates α hx : b = a * x y : Associates α hy : d = c * y ⊢ b * d = a * c * (x * y) [PROOFSTEP] simp [hx, hy, mul_comm, mul_assoc, mul_left_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : Associates α ⊢ a ≤ b * a [PROOFSTEP] rw [mul_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : Associates α ⊢ a ≤ a * b [PROOFSTEP] exact le_mul_right [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α c' : Associates α hc' : Associates.mk b = Associates.mk a * c' ⊢ ∀ (c : α), Associates.mk b = Associates.mk a * Quotient.mk (Associated.setoid α) c → a ∣ b [PROOFSTEP] intro c hc [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α c' : Associates α hc' : Associates.mk b = Associates.mk a * c' c : α hc : Associates.mk b = Associates.mk a * Quotient.mk (Associated.setoid α) c ⊢ a ∣ b [PROOFSTEP] let ⟨d, hd⟩ := (Quotient.exact hc).symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α c' : Associates α hc' : Associates.mk b = Associates.mk a * c' c : α hc : Associates.mk b = Associates.mk a * Quotient.mk (Associated.setoid α) c d : αˣ hd : a * c * ↑d = b ⊢ a ∣ b [PROOFSTEP] exact ⟨↑d * c, calc b = a * c * ↑d := hd.symm _ = a * (↑d * c) := by ac_rfl⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α c' : Associates α hc' : Associates.mk b = Associates.mk a * c' c : α hc : Associates.mk b = Associates.mk a * Quotient.mk (Associated.setoid α) c d : αˣ hd : a * c * ↑d = b ⊢ a * c * ↑d = a * (↑d * c) [PROOFSTEP] ac_rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α x✝ : a ∣ b c : α hc : b = a * c ⊢ Associates.mk b = Associates.mk a * Associates.mk c [PROOFSTEP] simp [hc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoid α a b : α x✝ : a ∣ b c : α hc : b = a * c ⊢ Associates.mk (a * c) = Associates.mk a * Associates.mk c [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α ⊢ ∀ (a : Associates α), 0 * a = 0 [PROOFSTEP] rintro ⟨a⟩ [GOAL] case mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a✝ : Associates α a : α ⊢ 0 * Quot.mk Setoid.r a = 0 [PROOFSTEP] show Associates.mk (0 * a) = Associates.mk 0 [GOAL] case mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a✝ : Associates α a : α ⊢ Associates.mk (0 * a) = Associates.mk 0 [PROOFSTEP] rw [zero_mul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α ⊢ ∀ (a : Associates α), a * 0 = 0 [PROOFSTEP] rintro ⟨a⟩ [GOAL] case mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a✝ : Associates α a : α ⊢ Quot.mk Setoid.r a * 0 = 0 [PROOFSTEP] show Associates.mk (a * 0) = Associates.mk 0 [GOAL] case mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a✝ : Associates α a : α ⊢ Associates.mk (a * 0) = Associates.mk 0 [PROOFSTEP] rw [mul_zero] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prime (Associates.mk p) ↔ Prime p [PROOFSTEP] rw [Prime, _root_.Prime, forall_associated] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (Associates.mk p ≠ 0 ∧ ¬IsUnit (Associates.mk p) ∧ ∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ p ≠ 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] trans [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (Associates.mk p ≠ 0 ∧ ¬IsUnit (Associates.mk p) ∧ ∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?m.311388 [PROOFSTEP] apply and_congr [GOAL] case h₁ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Associates.mk p ≠ 0 ↔ ?c case h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (¬IsUnit (Associates.mk p) ∧ ∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?d case c α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop case d α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop [PROOFSTEP] rfl [GOAL] case h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (¬IsUnit (Associates.mk p) ∧ ∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?d case d α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop [PROOFSTEP] apply and_congr [GOAL] case h₂.h₁ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ ¬IsUnit (Associates.mk p) ↔ ?h₂.c case h₂.h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?h₂.d case h₂.c α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop case h₂.d α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop [PROOFSTEP] rfl [GOAL] case h₂.h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (∀ (a : α) (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?h₂.d case h₂.d α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ Prop [PROOFSTEP] apply forall_congr' [GOAL] case h₂.h₂.h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ ∀ (a : α), (∀ (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?h₂.h₂.q a case h₂.h₂.q α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ α → Prop [PROOFSTEP] intro a [GOAL] case h₂.h₂.h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p a : α ⊢ (∀ (b : Associates α), Associates.mk p ∣ Associates.mk a * b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ b) ↔ ?h₂.h₂.q a case h₂.h₂.q α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ α → Prop [PROOFSTEP] exact forall_associated [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (Associates.mk p ≠ 0 ∧ ¬IsUnit (Associates.mk p) ∧ ∀ (a a_1 : α), Associates.mk p ∣ Associates.mk a * Associates.mk a_1 → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ Associates.mk a_1) ↔ p ≠ 0 ∧ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] apply and_congr mk_ne_zero [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (¬IsUnit (Associates.mk p) ∧ ∀ (a a_1 : α), Associates.mk p ∣ Associates.mk a * Associates.mk a_1 → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ Associates.mk a_1) ↔ ¬IsUnit p ∧ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] apply and_congr [GOAL] case h₁ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ ¬IsUnit (Associates.mk p) ↔ ¬IsUnit p [PROOFSTEP] rw [isUnit_mk] [GOAL] case h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p : α ⊢ (∀ (a a_1 : α), Associates.mk p ∣ Associates.mk a * Associates.mk a_1 → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ Associates.mk a_1) ↔ ∀ (a b : α), p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] refine' forall₂_congr fun a b => _ [GOAL] case h₂ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p a b : α ⊢ Associates.mk p ∣ Associates.mk a * Associates.mk b → Associates.mk p ∣ Associates.mk a ∨ Associates.mk p ∣ Associates.mk b ↔ p ∣ a * b → p ∣ a ∨ p ∣ b [PROOFSTEP] rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α ⊢ Irreducible (Associates.mk a) ↔ Irreducible a [PROOFSTEP] simp only [irreducible_iff, isUnit_mk] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α ⊢ (¬IsUnit a ∧ ∀ (a_1 b : Associates α), Associates.mk a = a_1 * b → IsUnit a_1 ∨ IsUnit b) ↔ ¬IsUnit a ∧ ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b [PROOFSTEP] apply and_congr Iff.rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α ⊢ (∀ (a_1 b : Associates α), Associates.mk a = a_1 * b → IsUnit a_1 ∨ IsUnit b) ↔ ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b [PROOFSTEP] constructor [GOAL] case mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α ⊢ (∀ (a_1 b : Associates α), Associates.mk a = a_1 * b → IsUnit a_1 ∨ IsUnit b) → ∀ (a_2 b : α), a = a_2 * b → IsUnit a_2 ∨ IsUnit b [PROOFSTEP] rintro h x y rfl [GOAL] case mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α x y : α h : ∀ (a b : Associates α), Associates.mk (x * y) = a * b → IsUnit a ∨ IsUnit b ⊢ IsUnit x ∨ IsUnit y [PROOFSTEP] simpa [isUnit_mk] using h (Associates.mk x) (Associates.mk y) rfl [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α ⊢ (∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b) → ∀ (a_2 b : Associates α), Associates.mk a = a_2 * b → IsUnit a_2 ∨ IsUnit b [PROOFSTEP] intro h x y [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α h : ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b x y : Associates α ⊢ Associates.mk a = x * y → IsUnit x ∨ IsUnit y [PROOFSTEP] refine' Quotient.inductionOn₂ x y fun x y a_eq => _ [GOAL] case mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α h : ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b x✝ y✝ : Associates α x y : α a_eq : Associates.mk a = Quotient.mk (Associated.setoid α) x * Quotient.mk (Associated.setoid α) y ⊢ IsUnit (Quotient.mk (Associated.setoid α) x) ∨ IsUnit (Quotient.mk (Associated.setoid α) y) [PROOFSTEP] rcases Quotient.exact a_eq.symm with ⟨u, a_eq⟩ [GOAL] case mpr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α h : ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b x✝ y✝ : Associates α x y : α a_eq✝ : Associates.mk a = Quotient.mk (Associated.setoid α) x * Quotient.mk (Associated.setoid α) y u : αˣ a_eq : x * y * ↑u = a ⊢ IsUnit (Quotient.mk (Associated.setoid α) x) ∨ IsUnit (Quotient.mk (Associated.setoid α) y) [PROOFSTEP] rw [mul_assoc] at a_eq [GOAL] case mpr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α h : ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b x✝ y✝ : Associates α x y : α a_eq✝ : Associates.mk a = Quotient.mk (Associated.setoid α) x * Quotient.mk (Associated.setoid α) y u : αˣ a_eq : x * (y * ↑u) = a ⊢ IsUnit (Quotient.mk (Associated.setoid α) x) ∨ IsUnit (Quotient.mk (Associated.setoid α) y) [PROOFSTEP] show IsUnit (Associates.mk x) ∨ IsUnit (Associates.mk y) [GOAL] case mpr.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α h : ∀ (a_1 b : α), a = a_1 * b → IsUnit a_1 ∨ IsUnit b x✝ y✝ : Associates α x y : α a_eq✝ : Associates.mk a = Quotient.mk (Associated.setoid α) x * Quotient.mk (Associated.setoid α) y u : αˣ a_eq : x * (y * ↑u) = a ⊢ IsUnit (Associates.mk x) ∨ IsUnit (Associates.mk y) [PROOFSTEP] simpa [isUnit_mk] using h _ _ a_eq.symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α ⊢ DvdNotUnit (Associates.mk a) (Associates.mk b) ↔ DvdNotUnit a b [PROOFSTEP] rw [DvdNotUnit, DvdNotUnit, mk_ne_zero] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α ⊢ (a ≠ 0 ∧ ∃ x, ¬IsUnit x ∧ Associates.mk b = Associates.mk a * x) ↔ a ≠ 0 ∧ ∃ x, ¬IsUnit x ∧ b = a * x [PROOFSTEP] apply and_congr_right [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α ⊢ a ≠ 0 → ((∃ x, ¬IsUnit x ∧ Associates.mk b = Associates.mk a * x) ↔ ∃ x, ¬IsUnit x ∧ b = a * x) [PROOFSTEP] intro [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 ⊢ (∃ x, ¬IsUnit x ∧ Associates.mk b = Associates.mk a * x) ↔ ∃ x, ¬IsUnit x ∧ b = a * x [PROOFSTEP] constructor [GOAL] case h.mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 ⊢ (∃ x, ¬IsUnit x ∧ Associates.mk b = Associates.mk a * x) → ∃ x, ¬IsUnit x ∧ b = a * x [PROOFSTEP] contrapose! [GOAL] case h.mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 ⊢ (∀ (x : α), ¬IsUnit x → b ≠ a * x) → ∀ (x : Associates α), ¬IsUnit x → Associates.mk b ≠ Associates.mk a * x [PROOFSTEP] rw [forall_associated] [GOAL] case h.mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 ⊢ (∀ (x : α), ¬IsUnit x → b ≠ a * x) → ∀ (a_2 : α), ¬IsUnit (Associates.mk a_2) → Associates.mk b ≠ Associates.mk a * Associates.mk a_2 [PROOFSTEP] intro h x hx hbax [GOAL] case h.mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit (Associates.mk x) hbax : Associates.mk b = Associates.mk a * Associates.mk x ⊢ False [PROOFSTEP] rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax [GOAL] case h.mp α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit (Associates.mk x) hbax : b ~ᵤ a * x ⊢ False [PROOFSTEP] cases' hbax with u hu [GOAL] case h.mp.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit (Associates.mk x) u : αˣ hu : b * ↑u = a * x ⊢ False [PROOFSTEP] apply h (x * ↑u⁻¹) [GOAL] case h.mp.intro._ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit (Associates.mk x) u : αˣ hu : b * ↑u = a * x ⊢ ¬IsUnit (x * ↑u⁻¹) [PROOFSTEP] rw [isUnit_mk] at hx [GOAL] case h.mp.intro._ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ ¬IsUnit (x * ↑u⁻¹) [PROOFSTEP] rw [Associated.isUnit_iff] [GOAL] case h.mp.intro._ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ ¬IsUnit ?m.316875 case h.mp.intro._ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ x * ↑u⁻¹ ~ᵤ ?m.316875 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ α [PROOFSTEP] apply hx [GOAL] case h.mp.intro._ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ x * ↑u⁻¹ ~ᵤ x [PROOFSTEP] use u [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit x u : αˣ hu : b * ↑u = a * x ⊢ x * ↑u⁻¹ * ↑u = x [PROOFSTEP] simp [GOAL] case h.mp.intro.a α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 h : ∀ (x : α), ¬IsUnit x → b ≠ a * x x : α hx : ¬IsUnit (Associates.mk x) u : αˣ hu : b * ↑u = a * x ⊢ b = a * (x * ↑u⁻¹) [PROOFSTEP] simp [← mul_assoc, ← hu] [GOAL] case h.mpr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : α a✝ : a ≠ 0 ⊢ (∃ x, ¬IsUnit x ∧ b = a * x) → ∃ x, ¬IsUnit x ∧ Associates.mk b = Associates.mk a * x [PROOFSTEP] rintro ⟨x, ⟨hx, rfl⟩⟩ [GOAL] case h.mpr.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α a✝ : a ≠ 0 x : α hx : ¬IsUnit x ⊢ ∃ x_1, ¬IsUnit x_1 ∧ Associates.mk (a * x) = Associates.mk a * x_1 [PROOFSTEP] use Associates.mk x [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : α a✝ : a ≠ 0 x : α hx : ¬IsUnit x ⊢ ¬IsUnit (Associates.mk x) ∧ Associates.mk (a * x) = Associates.mk a * Associates.mk x [PROOFSTEP] simp [isUnit_mk, mk_mul_mk, hx] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : Associates α hlt : a < b ⊢ DvdNotUnit a b [PROOFSTEP] constructor [GOAL] case left α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : Associates α hlt : a < b ⊢ a ≠ 0 [PROOFSTEP] rintro rfl [GOAL] case left α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α b : Associates α hlt : 0 < b ⊢ False [PROOFSTEP] apply not_lt_of_le _ hlt [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α b : Associates α hlt : 0 < b ⊢ b ≤ 0 [PROOFSTEP] apply dvd_zero [GOAL] case right α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a b : Associates α hlt : a < b ⊢ ∃ x, ¬IsUnit x ∧ b = a * x [PROOFSTEP] rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩ [GOAL] case right.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : Associates α x : Associates α ndvd : ¬a * x ∣ a ⊢ ∃ x_1, ¬IsUnit x_1 ∧ a * x = a * x_1 [PROOFSTEP] refine' ⟨x, _, rfl⟩ [GOAL] case right.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : Associates α x : Associates α ndvd : ¬a * x ∣ a ⊢ ¬IsUnit x [PROOFSTEP] contrapose! ndvd [GOAL] case right.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : Associates α x : Associates α ndvd : IsUnit x ⊢ a * x ∣ a [PROOFSTEP] rcases ndvd with ⟨u, rfl⟩ [GOAL] case right.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α a : Associates α u : (Associates α)ˣ ⊢ a * ↑u ∣ a [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α ⊢ (∀ (a : α), Irreducible a ↔ Prime a) ↔ ∀ (a : Associates α), Irreducible a ↔ Prime a [PROOFSTEP] simp_rw [forall_associated, irreducible_mk, prime_mk] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α ⊢ CommMonoidWithZero (Associates α) [PROOFSTEP] infer_instance [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α src✝ : CommMonoidWithZero (Associates α) := inferInstance ⊢ ∀ {a b c : Associates α}, a ≠ 0 → a * b = a * c → b = c [PROOFSTEP] rintro ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h [GOAL] case mk.mk.mk α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α src✝ : CommMonoidWithZero (Associates α) := inferInstance a✝ : Associates α a : α b✝ : Associates α b : α c✝ : Associates α c : α ha : Quot.mk Setoid.r a ≠ 0 h : Quot.mk Setoid.r a * Quot.mk Setoid.r b = Quot.mk Setoid.r a * Quot.mk Setoid.r c ⊢ Quot.mk Setoid.r b = Quot.mk Setoid.r c [PROOFSTEP] rcases Quotient.exact' h with ⟨u, hu⟩ [GOAL] case mk.mk.mk.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α src✝ : CommMonoidWithZero (Associates α) := inferInstance a✝ : Associates α a : α b✝ : Associates α b : α c✝ : Associates α c : α ha : Quot.mk Setoid.r a ≠ 0 h : Quot.mk Setoid.r a * Quot.mk Setoid.r b = Quot.mk Setoid.r a * Quot.mk Setoid.r c u : αˣ hu : a * b * ↑u = a * c ⊢ Quot.mk Setoid.r b = Quot.mk Setoid.r c [PROOFSTEP] have hu : a * (b * ↑u) = a * c := by rwa [← mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α src✝ : CommMonoidWithZero (Associates α) := inferInstance a✝ : Associates α a : α b✝ : Associates α b : α c✝ : Associates α c : α ha : Quot.mk Setoid.r a ≠ 0 h : Quot.mk Setoid.r a * Quot.mk Setoid.r b = Quot.mk Setoid.r a * Quot.mk Setoid.r c u : αˣ hu : a * b * ↑u = a * c ⊢ a * (b * ↑u) = a * c [PROOFSTEP] rwa [← mul_assoc] [GOAL] case mk.mk.mk.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α src✝ : CommMonoidWithZero (Associates α) := inferInstance a✝ : Associates α a : α b✝ : Associates α b : α c✝ : Associates α c : α ha : Quot.mk Setoid.r a ≠ 0 h : Quot.mk Setoid.r a * Quot.mk Setoid.r b = Quot.mk Setoid.r a * Quot.mk Setoid.r c u : αˣ hu✝ : a * b * ↑u = a * c hu : a * (b * ↑u) = a * c ⊢ Quot.mk Setoid.r b = Quot.mk Setoid.r c [PROOFSTEP] exact Quotient.sound' ⟨u, mul_left_cancel₀ (mk_ne_zero.1 ha) hu⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α ⊢ NoZeroDivisors (Associates α) [PROOFSTEP] infer_instance [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α a b c : Associates α ha : a ≠ 0 d : Associates α hd : a * c = a * b * d ⊢ a * c = a * (b * d) [PROOFSTEP] rwa [← mul_assoc] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d ⊢ m = 1 ∨ m = p [PROOFSTEP] have dvd_rfl' : p ∣ m * d := by rw [r] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d ⊢ p ∣ m * d [PROOFSTEP] rw [r] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d ⊢ m = 1 ∨ m = p [PROOFSTEP] rw [r] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d ⊢ m = 1 ∨ m = m * d [PROOFSTEP] match h m d dvd_rfl' with | Or.inl h' => by_cases h : m = 0 case pos => simp [h, zero_mul] case neg => rw [r] at h' have : m * d ≤ m * 1 := by simpa using h' have : d ≤ 1 := Associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this have : d = 1 := bot_unique this simp [this] | Or.inr h' => by_cases h : d = 0 case pos => rw [r] at hp0 have : m * d = 0 := by rw [h]; simp contradiction case neg => rw [r] at h' have : d * m ≤ d * 1 := by simpa [mul_comm] using h' exact Or.inl <| bot_unique <| Associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m ⊢ m = 1 ∨ m = m * d [PROOFSTEP] by_cases h : m = 0 [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : m = 0 ⊢ m = 1 ∨ m = m * d case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : ¬m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case pos => simp [h, zero_mul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case pos => simp [h, zero_mul] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] simp [h, zero_mul] [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : ¬m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case neg => rw [r] at h' have : m * d ≤ m * 1 := by simpa using h' have : d ≤ 1 := Associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this have : d = 1 := bot_unique this simp [this] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : ¬m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case neg => rw [r] at h' have : m * d ≤ m * 1 := by simpa using h' have : d ≤ 1 := Associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this have : d = 1 := bot_unique this simp [this] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ m h : ¬m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] rw [r] at h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ m h : ¬m = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] have : m * d ≤ m * 1 := by simpa using h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ m h : ¬m = 0 ⊢ m * d ≤ m * 1 [PROOFSTEP] simpa using h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ m h : ¬m = 0 this : m * d ≤ m * 1 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] have : d ≤ 1 := Associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ m h : ¬m = 0 this✝ : m * d ≤ m * 1 this : d ≤ 1 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] have : d = 1 := bot_unique this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ m h : ¬m = 0 this✝¹ : m * d ≤ m * 1 this✝ : d ≤ 1 this : d = 1 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] simp [this] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d ⊢ m = 1 ∨ m = m * d [PROOFSTEP] by_cases h : d = 0 [GOAL] case pos α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m = 1 ∨ m = m * d case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : ¬d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case pos => rw [r] at hp0 have : m * d = 0 := by rw [h]; simp contradiction [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case pos => rw [r] at hp0 have : m * d = 0 := by rw [h]; simp contradiction [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] rw [r] at hp0 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α hp0 : m * d ≠ 0 r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] have : m * d = 0 := by rw [h]; simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α hp0 : m * d ≠ 0 r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m * d = 0 [PROOFSTEP] rw [h] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α hp0 : m * d ≠ 0 r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 ⊢ m * 0 = 0 [PROOFSTEP] simp [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α hp0 : m * d ≠ 0 r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : d = 0 this : m * d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] contradiction [GOAL] case neg α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : ¬d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case neg => rw [r] at h' have : d * m ≤ d * 1 := by simpa [mul_comm] using h' exact Or.inl <| bot_unique <| Associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : ¬d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] case neg => rw [r] at h' have : d * m ≤ d * 1 := by simpa [mul_comm] using h' exact Or.inl <| bot_unique <| Associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : p ∣ d h : ¬d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] rw [r] at h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ d h : ¬d = 0 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] have : d * m ≤ d * 1 := by simpa [mul_comm] using h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ d h : ¬d = 0 ⊢ d * m ≤ d * 1 [PROOFSTEP] simpa [mul_comm] using h' [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p m : Associates α hp0 : p ≠ 0 left✝ : ¬IsUnit p h✝ : ∀ (a b : Associates α), p ∣ a * b → p ∣ a ∨ p ∣ b d : Associates α r : p = m * d dvd_rfl' : p ∣ m * d h' : m * d ∣ d h : ¬d = 0 this : d * m ≤ d * 1 ⊢ m = 1 ∨ m = m * d [PROOFSTEP] exact Or.inl <| bot_unique <| Associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : Associates α ⊢ p ≤ 1 ↔ p = 1 [PROOFSTEP] rw [← Associates.bot_eq_one, le_bot_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α h : DvdNotUnit p q hq : Irreducible q ⊢ IsUnit p [PROOFSTEP] obtain ⟨_, x, hx, hx'⟩ := h [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α hq : Irreducible q left✝ : p ≠ 0 x : α hx : ¬IsUnit x hx' : q = p * x ⊢ IsUnit p [PROOFSTEP] exact Or.resolve_right ((irreducible_iff.1 hq).right p x hx') hx [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p q : α hp : DvdNotUnit p q ⊢ ¬IsUnit q [PROOFSTEP] obtain ⟨-, x, hx, rfl⟩ := hp [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CommMonoidWithZero α p x : α hx : ¬IsUnit x ⊢ ¬IsUnit (p * x) [PROOFSTEP] exact fun hc => hx (isUnit_iff_dvd_one.mpr (dvd_of_mul_left_dvd (isUnit_iff_dvd_one.mp hc))) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : CommMonoidWithZero α inst✝ : Nontrivial α p q r : α h : DvdNotUnit p q h' : q ~ᵤ r ⊢ DvdNotUnit p r [PROOFSTEP] obtain ⟨u, rfl⟩ := Associated.symm h' [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : CommMonoidWithZero α inst✝ : Nontrivial α p r : α u : αˣ h : DvdNotUnit p (r * ↑u) h' : r * ↑u ~ᵤ r ⊢ DvdNotUnit p r [PROOFSTEP] obtain ⟨hp, x, hx⟩ := h [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : CommMonoidWithZero α inst✝ : Nontrivial α p r : α u : αˣ h' : r * ↑u ~ᵤ r hp : p ≠ 0 x : α hx : ¬IsUnit x ∧ r * ↑u = p * x ⊢ DvdNotUnit p r [PROOFSTEP] refine' ⟨hp, x * ↑u⁻¹, DvdNotUnit.not_unit ⟨u⁻¹.ne_zero, x, hx.left, mul_comm _ _⟩, _⟩ [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝¹ : CommMonoidWithZero α inst✝ : Nontrivial α p r : α u : αˣ h' : r * ↑u ~ᵤ r hp : p ≠ 0 x : α hx : ¬IsUnit x ∧ r * ↑u = p * x ⊢ r = p * (x * ↑u⁻¹) [PROOFSTEP] rw [← mul_assoc, ← hx.right, mul_assoc, Units.mul_inv, mul_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p b : α h : p * b ~ᵤ p hp : p ≠ 0 ⊢ IsUnit b [PROOFSTEP] cases' h with a ha [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p b : α hp : p ≠ 0 a : αˣ ha : p * b * ↑a = p ⊢ IsUnit b [PROOFSTEP] refine' isUnit_of_mul_eq_one b a ((mul_right_inj' hp).mp _) [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p b : α hp : p ≠ 0 a : αˣ ha : p * b * ↑a = p ⊢ p * (b * ↑a) = p * 1 [PROOFSTEP] rwa [← mul_assoc, mul_one] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α h : DvdNotUnit p q ⊢ ¬p ~ᵤ q [PROOFSTEP] rintro ⟨a, rfl⟩ [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α a : αˣ h : DvdNotUnit p (p * ↑a) ⊢ False [PROOFSTEP] obtain ⟨hp, x, hx, hx'⟩ := h [GOAL] case intro.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α a : αˣ hp : p ≠ 0 x : α hx : ¬IsUnit x hx' : p * ↑a = p * x ⊢ False [PROOFSTEP] rcases(mul_right_inj' hp).mp hx' with rfl [GOAL] case intro.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p : α a : αˣ hp : p ≠ 0 hx : ¬IsUnit ↑a hx' : p * ↑a = p * ↑a ⊢ False [PROOFSTEP] exact hx a.isUnit [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α h : DvdNotUnit p q ⊢ p ≠ q [PROOFSTEP] by_contra hcontra [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α h : DvdNotUnit p q hcontra : p = q ⊢ False [PROOFSTEP] obtain ⟨hp, x, hx', hx''⟩ := h [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit x hx'' : q = p * x ⊢ False [PROOFSTEP] conv_lhs at hx'' => rw [← hcontra, ← mul_one p] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit x hx'' : q = p * x | q [PROOFSTEP] rw [← hcontra, ← mul_one p] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit x hx'' : q = p * x | q [PROOFSTEP] rw [← hcontra, ← mul_one p] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit x hx'' : q = p * x | q [PROOFSTEP] rw [← hcontra, ← mul_one p] [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit x hx'' : p * 1 = p * x ⊢ False [PROOFSTEP] rw [(mul_left_cancel₀ hp hx'').symm] at hx' [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hcontra : p = q hp : p ≠ 0 x : α hx' : ¬IsUnit 1 hx'' : p * 1 = p * x ⊢ False [PROOFSTEP] exact hx' isUnit_one [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α q : α hq : ¬IsUnit q hq' : q ≠ 0 ⊢ Function.Injective fun n => q ^ n [PROOFSTEP] refine' injective_of_lt_imp_ne fun n m h => DvdNotUnit.ne ⟨pow_ne_zero n hq', q ^ (m - n), _, _⟩ [GOAL] case refine'_1 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α q : α hq : ¬IsUnit q hq' : q ≠ 0 n m : ℕ h : n < m ⊢ ¬IsUnit (q ^ (m - n)) [PROOFSTEP] exact not_isUnit_of_not_isUnit_dvd hq (dvd_pow (dvd_refl _) (Nat.sub_pos_of_lt h).ne') [GOAL] case refine'_2 α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α q : α hq : ¬IsUnit q hq' : q ≠ 0 n m : ℕ h : n < m ⊢ q ^ m = q ^ n * q ^ (m - n) [PROOFSTEP] exact (pow_mul_pow_sub q h.le).symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q : α hp : Prime p n : ℕ ⊢ q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i [PROOFSTEP] induction' n with n ih generalizing q [GOAL] case zero α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p q : α ⊢ q ∣ p ^ Nat.zero ↔ ∃ i, i ≤ Nat.zero ∧ q ~ᵤ p ^ i [PROOFSTEP] simp [← isUnit_iff_dvd_one, associated_one_iff_isUnit] [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α ⊢ q ∣ p ^ Nat.succ n ↔ ∃ i, i ≤ Nat.succ n ∧ q ~ᵤ p ^ i [PROOFSTEP] refine' ⟨fun h => _, fun ⟨i, hi, hq⟩ => hq.dvd.trans (pow_dvd_pow p hi)⟩ [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : q ∣ p ^ Nat.succ n ⊢ ∃ i, i ≤ Nat.succ n ∧ q ~ᵤ p ^ i [PROOFSTEP] rw [pow_succ] at h [GOAL] case succ α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : q ∣ p * p ^ n ⊢ ∃ i, i ≤ Nat.succ n ∧ q ~ᵤ p ^ i [PROOFSTEP] rcases hp.left_dvd_or_dvd_right_of_dvd_mul h with (⟨q, rfl⟩ | hno) [GOAL] case succ.inl.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : p * q ∣ p * p ^ n ⊢ ∃ i, i ≤ Nat.succ n ∧ p * q ~ᵤ p ^ i [PROOFSTEP] rw [mul_dvd_mul_iff_left hp.ne_zero, ih] at h [GOAL] case succ.inl.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : ∃ i, i ≤ n ∧ q ~ᵤ p ^ i ⊢ ∃ i, i ≤ Nat.succ n ∧ p * q ~ᵤ p ^ i [PROOFSTEP] rcases h with ⟨i, hi, hq⟩ [GOAL] case succ.inl.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α i : ℕ hi : i ≤ n hq : q ~ᵤ p ^ i ⊢ ∃ i, i ≤ Nat.succ n ∧ p * q ~ᵤ p ^ i [PROOFSTEP] refine' ⟨i + 1, Nat.succ_le_succ hi, (hq.mul_left p).trans _⟩ [GOAL] case succ.inl.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α i : ℕ hi : i ≤ n hq : q ~ᵤ p ^ i ⊢ p * p ^ i ~ᵤ p ^ (i + 1) [PROOFSTEP] rw [pow_succ] [GOAL] case succ.inl.intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α i : ℕ hi : i ≤ n hq : q ~ᵤ p ^ i ⊢ p * p ^ i ~ᵤ p * p ^ i [PROOFSTEP] rfl [GOAL] case succ.inr α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : q ∣ p * p ^ n hno : q ∣ p ^ n ⊢ ∃ i, i ≤ Nat.succ n ∧ q ~ᵤ p ^ i [PROOFSTEP] obtain ⟨i, hi, hq⟩ := ih.mp hno [GOAL] case succ.inr.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 δ : Type u_4 inst✝ : CancelCommMonoidWithZero α p q✝ : α hp : Prime p n : ℕ ih : ∀ {q : α}, q ∣ p ^ n ↔ ∃ i, i ≤ n ∧ q ~ᵤ p ^ i q : α h : q ∣ p * p ^ n hno : q ∣ p ^ n i : ℕ hi : i ≤ n hq : q ~ᵤ p ^ i ⊢ ∃ i, i ≤ Nat.succ n ∧ q ~ᵤ p ^ i [PROOFSTEP] exact ⟨i, hi.trans n.le_succ, hq⟩
lemma is_interval_simply_connected_1: fixes S :: "real set" shows "is_interval S \<longleftrightarrow> simply_connected S"
State Before: R : Type u inst✝² : Semiring R ι : Type v dec_ι : DecidableEq ι M : Type u_1 inst✝¹ : AddCommMonoid M inst✝ : Module R M A✝ A : ι → Submodule R M i j : ι hij : i ≠ j h : Set.univ = {i, j} hi : IsInternal A ⊢ iSup A = A i ⊔ A j State After: no goals Tactic: rw [← sSup_pair, iSup, ← Set.image_univ, h, Set.image_insert_eq, Set.image_singleton]
#!/usr/bin/env Rscript # # Use generalized linear mixed models to test for differences in allele # frequency. # # Each read is treated as an observation, and pools are treated as random # effects. A likelihood ratio test is used to produce a p-value. # # Usage: # # snp_by_snp_glmm_test.r <sync file> <file with pool names> # <group 1 pools> <group 2 pools> # # The names of the pools in each group should be separated by commas. # #==============================================================================# library(data.table) library(lme4) options(warn=1) #==============================================================================# ## From a sync file row, get read counts. get_counts = function(sync_row, pools, pool_names) { contig = sync_row[[1]] pos = sync_row[[2]] ref_allele = toupper(sync_row[[3]]) counts = structure(vector('list', length=length(pools)), names=pools) for(pn in pools) { x = sync_row[[which(pool_names == pn) + 3]] cnts = as.numeric(unlist(strsplit(x, ':'))) names(cnts) = c('A', 'T', 'C', 'G', 'N', 'D') ref_cnt = cnts[ref_allele] alt_cnt = (sum(cnts) - cnts['N']) - ref_cnt counts[[pn]] = c('ref'=ref_cnt, 'alt'=alt_cnt) } counts } ## Test if this set of counts is variable is_variable = function(counts) { ref = sum(sapply(counts, function(x) x[1])) alt = sum(sapply(counts, function(x) x[2])) return((ref != 0) && (alt != 0)) } null_result = list('p'=NaN, 'effect'=NaN, term=NA, converged=NA, 'wald_p'=NaN, 'freqs0'=NA, 'freqs1'=NA) ## Run a GLMM with pool as a random effect. Use the default ## Wald Z-test and likelihood ratio test to get p-values test = function(counts, groups) { resp = unlist(sapply(counts, function(x) c(rep(0, x[1]), rep(1, x[2])))) n_reads = sapply(counts, sum) freqs = structure(round(sapply(counts, function(x) x[1] / sum(x)), 4), names=names(counts)) pools = factor(rep(names(counts), n_reads)) trt = rep(names(groups), sapply(groups, function(x) sum(n_reads[x]))) freqs0 = paste(freqs[names(freqs) %in% groups[[1]]], collapse=',') freqs1 = paste(freqs[names(freqs) %in% groups[[2]]], collapse=',') ret = null_result if(length(unique(trt)) > 1) { ## Random intercept for each pool m = glmer(resp ~ trt + (1|pools), family=binomial('logit')) mnull = glmer(resp ~ (1|pools), family=binomial('logit')) lrt_p = anova(m, mnull)[['Pr(>Chisq)']][2] s = summary(m) conv = (length(s$optinfo$conv$lme4) == 0) && (length(mnull@optinfo$conv$lme4) == 0) p = s$coefficients[2, 4] fe = fixef(m)[2] ret = list('p'=lrt_p, 'wald_p'=p, 'effect'=fe, 'term'=names(fe), 'converged'=as.numeric(conv), 'freqs0'=freqs0, 'freqs1'=freqs1) } ret } #==============================================================================# ## Get arguments to the script cargs = commandArgs(trailingOnly=TRUE) sync_file_name = cargs[1] pool_file_name = cargs[2] group_1 = Filter(function(x) x != '', unlist(strsplit(cargs[3], ','))) group_2 = Filter(function(x) x != '', unlist(strsplit(cargs[4], ','))) ## Read in data read_counts = fread(sync_file_name, sep='\t', stringsAsFactors=FALSE) pool_names = scan(pool_file_name, what='character') trts = list('group1'=group_1, 'group2'=group_2) ## Test every SNP and print results cat('contig\tpos\tref\tp\twald_p\teffect\tterm\tconverged\tfreqs0\tfreqs1\n', file=stdout()) for(i in 1:nrow(read_counts)) { row_data = read_counts[i] contig = row_data[[1]] pos = row_data[[2]] ref = row_data[[3]] counts = get_counts(row_data, unlist(trts), pool_names) if(is_variable(counts)) { test_results = tryCatch(test(counts, trts), error=function(e) null_result) } else { test_results = null_result } cat(paste(contig, pos, ref, test_results$p, test_results$wald_p, test_results$effect, test_results$term, test_results$converged, test_results$freqs0, test_results$freqs1, sep='\t'), '\n', sep='', file=stdout()) }
theory Ex03_ imports Main "~~/src/HOL/IMP/AExp" begin inductive is_aval :: "aexp \<Rightarrow> state \<Rightarrow> val \<Rightarrow> bool" where N: "is_aval (N n) s n" | V: "is_aval (V x) s (s x)" | P: "\<lbrakk> is_aval a1 s v1; is_aval a2 s v2 \<rbrakk> \<Longrightarrow> is_aval (Plus a1 a2) s (v1 + v2)" lemma "is_aval (Plus (N 2) (Plus (V x) (N 3))) s (2 + (s x + 3))" apply(rule is_aval.intros)+ done lemma aval1: "is_aval a s v \<Longrightarrow> aval a s = v" apply(induction a) apply() end
/* * Copyright (c) 2011-2022, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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 THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. */ #ifndef DART_CONSTRAINT_BOXEDLCPSOLVER_HPP_ #define DART_CONSTRAINT_BOXEDLCPSOLVER_HPP_ #include <string> #include <Eigen/Core> #include "dart/common/Castable.hpp" namespace dart { namespace constraint { class BoxedLcpSolver : public common::Castable<BoxedLcpSolver> { public: /// Destructor virtual ~BoxedLcpSolver() = default; /// Returns the type virtual const std::string& getType() const = 0; /// Solves constriant impulses for a constrained group. The LCP formulation /// setting that this function solve is A*x = b + w where each x[i], w[i] /// satisfies one of /// (1) x = lo, w >= 0 /// (2) x = hi, w <= 0 /// (3) lo < x < hi, w = 0 /// /// \param[in] n Dimension of constraints. /// \param[in] A A term of the LCP formulation. /// \param[in] x x term of the LCP formulation. /// \param[in] b b term of the LCP formulation. /// \param[in] nub Number of the first unbounded constraints. /// \param[in] lo Lower bound of x where it's restricted to be lo <= 0. /// \param[in] hi Upper bound of x where it's enforced to be hi >= 0. /// \param[in] findex Indices to corresponding normal contact constraint. Set /// the index to itself (e.g., findex[k] = k) for normal contacts or /// non-contact constraints. For friction constraint, set the cooresponding /// normal contact constraint. /// \param[in] earlyTermination Set true to return false as soon as the solver /// find the solution doesn't exist. Otherwise, the solver will continue to /// push hard to solve the problem using some hacks. /// /// \return Success. // Note: The function signature is ODE specific for now. Consider changing // this to Eigen friendly version once own Dantzig LCP solver is available. virtual bool solve( int n, double* A, double* x, double* b, int nub, double* lo, double* hi, int* findex, bool earlyTermination = false) = 0; #ifndef NDEBUG virtual bool canSolve(int n, const double* A) = 0; #endif }; } // namespace constraint } // namespace dart #endif // DART_CONSTRAINT_BOXEDLCPSOLVER_HPP_
/* rng/transputer.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> /* This is the INMOS Transputer Development System generator. The sequence is, x_{n+1} = (a x_n) mod m with a = 1664525 and m = 2^32. The seed specifies the initial value, x_1. The theoretical value of x_{10001} is 1244127297. The period of this generator is 2^30. */ static inline unsigned long int transputer_get (void *vstate); static double transputer_get_double (void *vstate); static void transputer_set (void *state, unsigned long int s); typedef struct { unsigned long int x; } transputer_state_t; static unsigned long int transputer_get (void *vstate) { transputer_state_t *state = (transputer_state_t *) vstate; state->x = (1664525 * state->x) & 0xffffffffUL; return state->x; } static double transputer_get_double (void *vstate) { return transputer_get (vstate) / 4294967296.0 ; } static void transputer_set (void *vstate, unsigned long int s) { transputer_state_t *state = (transputer_state_t *) vstate; if (s == 0) s = 1 ; /* default seed is 1. */ state->x = s; return; } static const gsl_rng_type transputer_type = {"transputer", /* name */ 0xffffffffUL, /* RAND_MAX */ 1, /* RAND_MIN */ sizeof (transputer_state_t), &transputer_set, &transputer_get, &transputer_get_double}; const gsl_rng_type *gsl_rng_transputer = &transputer_type;
#' @title kml.style #' @description unknown #' @family abysmally documented #' @author unknown, \email{<unknown>@@dfo-mpo.gc.ca} #' @export kml.style = function( con, style.id="default", colour="ff00ffff", scale=0.5, href='' ) { writeLines( kml.placemark( 'style', style.id=style.id, colour=colour, scale=scale, href=href), con ) }
(* Title: HOL/Word/Word_Miscellaneous.thy Author: Miscellaneous *) section \<open>Miscellaneous lemmas, of at least doubtful value\<close> theory Word_Miscellaneous imports Main "~~/src/HOL/Library/Bit" Misc_Numeric begin lemma power_minus_simp: "0 < n \<Longrightarrow> a ^ n = a * a ^ (n - 1)" by (auto dest: gr0_implies_Suc) lemma funpow_minus_simp: "0 < n \<Longrightarrow> f ^^ n = f \<circ> f ^^ (n - 1)" by (auto dest: gr0_implies_Suc) lemma power_numeral: "a ^ numeral k = a * a ^ (pred_numeral k)" by (simp add: numeral_eq_Suc) lemma funpow_numeral [simp]: "f ^^ numeral k = f \<circ> f ^^ (pred_numeral k)" by (simp add: numeral_eq_Suc) lemma replicate_numeral [simp]: "replicate (numeral k) x = x # replicate (pred_numeral k) x" by (simp add: numeral_eq_Suc) lemma rco_alt: "(f o g) ^^ n o f = f o (g o f) ^^ n" apply (rule ext) apply (induct n) apply (simp_all add: o_def) done lemma list_exhaust_size_gt0: assumes y: "\<And>a list. y = a # list \<Longrightarrow> P" shows "0 < length y \<Longrightarrow> P" apply (cases y, simp) apply (rule y) apply fastforce done lemma list_exhaust_size_eq0: assumes y: "y = [] \<Longrightarrow> P" shows "length y = 0 \<Longrightarrow> P" apply (cases y) apply (rule y, simp) apply simp done lemma size_Cons_lem_eq: "y = xa # list ==> size y = Suc k ==> size list = k" by auto lemmas ls_splits = prod.split prod.split_asm if_split_asm lemma not_B1_is_B0: "y \<noteq> (1::bit) \<Longrightarrow> y = (0::bit)" by (cases y) auto lemma B1_ass_B0: assumes y: "y = (0::bit) \<Longrightarrow> y = (1::bit)" shows "y = (1::bit)" apply (rule classical) apply (drule not_B1_is_B0) apply (erule y) done \<comment> "simplifications for specific word lengths" lemmas n2s_ths [THEN eq_reflection] = add_2_eq_Suc add_2_eq_Suc' lemmas s2n_ths = n2s_ths [symmetric] lemma and_len: "xs = ys ==> xs = ys & length xs = length ys" by auto lemma size_if: "size (if p then xs else ys) = (if p then size xs else size ys)" by auto lemma tl_if: "tl (if p then xs else ys) = (if p then tl xs else tl ys)" by auto lemma hd_if: "hd (if p then xs else ys) = (if p then hd xs else hd ys)" by auto lemma if_Not_x: "(if p then ~ x else x) = (p = (~ x))" by auto lemma if_x_Not: "(if p then x else ~ x) = (p = x)" by auto lemma if_same_and: "(If p x y & If p u v) = (if p then x & u else y & v)" by auto lemma if_same_eq: "(If p x y = (If p u v)) = (if p then x = (u) else y = (v))" by auto lemma if_same_eq_not: "(If p x y = (~ If p u v)) = (if p then x = (~u) else y = (~v))" by auto (* note - if_Cons can cause blowup in the size, if p is complex, so make a simproc *) lemma if_Cons: "(if p then x # xs else y # ys) = If p x y # If p xs ys" by auto lemma if_single: "(if xc then [xab] else [an]) = [if xc then xab else an]" by auto lemma if_bool_simps: "If p True y = (p | y) & If p False y = (~p & y) & If p y True = (p --> y) & If p y False = (p & y)" by auto lemmas if_simps = if_x_Not if_Not_x if_cancel if_True if_False if_bool_simps lemmas seqr = eq_reflection [where x = "size w"] for w (* FIXME: delete *) lemma the_elemI: "y = {x} ==> the_elem y = x" by simp lemma nonemptyE: "S ~= {} ==> (!!x. x : S ==> R) ==> R" by auto lemma gt_or_eq_0: "0 < y \<or> 0 = (y::nat)" by arith lemmas xtr1 = xtrans(1) lemmas xtr2 = xtrans(2) lemmas xtr3 = xtrans(3) lemmas xtr4 = xtrans(4) lemmas xtr5 = xtrans(5) lemmas xtr6 = xtrans(6) lemmas xtr7 = xtrans(7) lemmas xtr8 = xtrans(8) lemmas nat_simps = diff_add_inverse2 diff_add_inverse lemmas nat_iffs = le_add1 le_add2 lemma sum_imp_diff: "j = k + i ==> j - i = (k :: nat)" by arith lemmas pos_mod_sign2 = zless2 [THEN pos_mod_sign [where b = "2::int"]] lemmas pos_mod_bound2 = zless2 [THEN pos_mod_bound [where b = "2::int"]] lemma nmod2: "n mod (2::int) = 0 | n mod 2 = 1" by arith lemmas eme1p = emep1 [simplified add.commute] lemma le_diff_eq': "(a \<le> c - b) = (b + a \<le> (c::int))" by arith lemma less_diff_eq': "(a < c - b) = (b + a < (c::int))" by arith lemma diff_less_eq': "(a - b < c) = (a < b + (c::int))" by arith lemmas m1mod22k = mult_pos_pos [OF zless2 zless2p, THEN zmod_minus1] lemma z1pdiv2: "(2 * b + 1) div 2 = (b::int)" by arith lemmas zdiv_le_dividend = xtr3 [OF div_by_1 [symmetric] zdiv_mono2, simplified int_one_le_iff_zero_less, simplified] lemma axxbyy: "a + m + m = b + n + n ==> (a = 0 | a = 1) ==> (b = 0 | b = 1) ==> a = b & m = (n :: int)" by arith lemma axxmod2: "(1 + x + x) mod 2 = (1 :: int) & (0 + x + x) mod 2 = (0 :: int)" by arith lemma axxdiv2: "(1 + x + x) div 2 = (x :: int) & (0 + x + x) div 2 = (x :: int)" by arith lemmas iszero_minus = trans [THEN trans, OF iszero_def neg_equal_0_iff_equal iszero_def [symmetric]] lemmas zadd_diff_inverse = trans [OF diff_add_cancel [symmetric] add.commute] lemmas add_diff_cancel2 = add.commute [THEN diff_eq_eq [THEN iffD2]] lemmas rdmods [symmetric] = mod_minus_eq mod_diff_left_eq mod_diff_right_eq mod_add_left_eq mod_add_right_eq mod_mult_right_eq mod_mult_left_eq lemma mod_plus_right: "((a + x) mod m = (b + x) mod m) = (a mod m = b mod (m :: nat))" apply (induct x) apply (simp_all add: mod_Suc) apply arith done lemma nat_minus_mod: "(n - n mod m) mod m = (0 :: nat)" by (induct n) (simp_all add : mod_Suc) lemmas nat_minus_mod_plus_right = trans [OF nat_minus_mod mod_0 [symmetric], THEN mod_plus_right [THEN iffD2], simplified] lemmas push_mods' = mod_add_eq mod_mult_eq mod_diff_eq mod_minus_eq lemmas push_mods = push_mods' [THEN eq_reflection] lemmas pull_mods = push_mods [symmetric] rdmods [THEN eq_reflection] lemmas mod_simps = mod_mult_self2_is_0 [THEN eq_reflection] mod_mult_self1_is_0 [THEN eq_reflection] mod_mod_trivial [THEN eq_reflection] lemma nat_mod_eq: "!!b. b < n ==> a mod n = b mod n ==> a mod n = (b :: nat)" by (induct a) auto lemmas nat_mod_eq' = refl [THEN [2] nat_mod_eq] lemma nat_mod_lem: "(0 :: nat) < n ==> b < n = (b mod n = b)" apply safe apply (erule nat_mod_eq') apply (erule subst) apply (erule mod_less_divisor) done lemma mod_nat_add: "(x :: nat) < z ==> y < z ==> (x + y) mod z = (if x + y < z then x + y else x + y - z)" apply (rule nat_mod_eq) apply auto apply (rule trans) apply (rule le_mod_geq) apply simp apply (rule nat_mod_eq') apply arith done lemma mod_nat_sub: "(x :: nat) < z ==> (x - y) mod z = x - y" by (rule nat_mod_eq') arith lemma int_mod_eq: "(0 :: int) <= b ==> b < n ==> a mod n = b mod n ==> a mod n = b" by (metis mod_pos_pos_trivial) lemmas int_mod_eq' = mod_pos_pos_trivial (* FIXME delete *) lemma int_mod_le: "(0::int) <= a ==> a mod n <= a" by (fact Divides.semiring_numeral_div_class.mod_less_eq_dividend) (* FIXME: delete *) lemma mod_add_if_z: "(x :: int) < z ==> y < z ==> 0 <= y ==> 0 <= x ==> 0 <= z ==> (x + y) mod z = (if x + y < z then x + y else x + y - z)" by (auto intro: int_mod_eq) lemma mod_sub_if_z: "(x :: int) < z ==> y < z ==> 0 <= y ==> 0 <= x ==> 0 <= z ==> (x - y) mod z = (if y <= x then x - y else x - y + z)" by (auto intro: int_mod_eq) lemmas zmde = mult_div_mod_eq [symmetric, THEN diff_eq_eq [THEN iffD2], symmetric] lemmas mcl = mult_cancel_left [THEN iffD1, THEN make_pos_rule] (* already have this for naturals, div_mult_self1/2, but not for ints *) lemma zdiv_mult_self: "m ~= (0 :: int) ==> (a + m * n) div m = a div m + n" apply (rule mcl) prefer 2 apply (erule asm_rl) apply (simp add: zmde ring_distribs) done lemma mod_power_lem: "a > 1 ==> a ^ n mod a ^ m = (if m <= n then 0 else (a :: int) ^ n)" apply clarsimp apply safe apply (simp add: dvd_eq_mod_eq_0 [symmetric]) apply (drule le_iff_add [THEN iffD1]) apply (force simp: power_add) apply (rule mod_pos_pos_trivial) apply (simp) apply (rule power_strict_increasing) apply auto done lemma pl_pl_rels: "a + b = c + d ==> a >= c & b <= d | a <= c & b >= (d :: nat)" by arith lemmas pl_pl_rels' = add.commute [THEN [2] trans, THEN pl_pl_rels] lemma minus_eq: "(m - k = m) = (k = 0 | m = (0 :: nat))" by arith lemma pl_pl_mm: "(a :: nat) + b = c + d ==> a - c = d - b" by arith lemmas pl_pl_mm' = add.commute [THEN [2] trans, THEN pl_pl_mm] lemmas dme = div_mult_mod_eq lemmas dtle = xtr3 [OF dme [symmetric] le_add1] lemmas th2 = order_trans [OF order_refl [THEN [2] mult_le_mono] dtle] lemma td_gal: "0 < c ==> (a >= b * c) = (a div c >= (b :: nat))" apply safe apply (erule (1) xtr4 [OF div_le_mono div_mult_self_is_m]) apply (erule th2) done lemmas td_gal_lt = td_gal [simplified not_less [symmetric], simplified] lemma div_mult_le: "(a :: nat) div b * b <= a" by (fact dtle) lemmas sdl = split_div_lemma [THEN iffD1, symmetric] lemma given_quot: "f > (0 :: nat) ==> (f * l + (f - 1)) div f = l" by (rule sdl, assumption) (simp (no_asm)) lemma given_quot_alt: "f > (0 :: nat) ==> (l * f + f - Suc 0) div f = l" apply (frule given_quot) apply (rule trans) prefer 2 apply (erule asm_rl) apply (rule_tac f="%n. n div f" in arg_cong) apply (simp add : ac_simps) done lemma diff_mod_le: "(a::nat) < d ==> b dvd d ==> a - a mod b <= d - b" apply (unfold dvd_def) apply clarify apply (case_tac k) apply clarsimp apply clarify apply (cases "b > 0") apply (drule mult.commute [THEN xtr1]) apply (frule (1) td_gal_lt [THEN iffD1]) apply (clarsimp simp: le_simps) apply (rule minus_mod_eq_mult_div [symmetric, THEN [2] xtr4]) apply (rule mult_mono) apply auto done lemma less_le_mult': "w * c < b * c ==> 0 \<le> c ==> (w + 1) * c \<le> b * (c::int)" apply (rule mult_right_mono) apply (rule zless_imp_add1_zle) apply (erule (1) mult_right_less_imp_less) apply assumption done lemma less_le_mult: "w * c < b * c \<Longrightarrow> 0 \<le> c \<Longrightarrow> w * c + c \<le> b * (c::int)" using less_le_mult' [of w c b] by (simp add: algebra_simps) lemmas less_le_mult_minus = iffD2 [OF le_diff_eq less_le_mult, simplified left_diff_distrib] lemma gen_minus: "0 < n ==> f n = f (Suc (n - 1))" by auto lemma mpl_lem: "j <= (i :: nat) ==> k < j ==> i - j + k < i" by arith lemma nonneg_mod_div: "0 <= a ==> 0 <= b ==> 0 <= (a mod b :: int) & 0 <= a div b" apply (cases "b = 0", clarsimp) apply (auto intro: pos_imp_zdiv_nonneg_iff [THEN iffD2]) done declare iszero_0 [intro] lemma min_pm [simp]: "min a b + (a - b) = (a :: nat)" by arith lemma min_pm1 [simp]: "a - b + min a b = (a :: nat)" by arith lemma rev_min_pm [simp]: "min b a + (a - b) = (a :: nat)" by arith lemma rev_min_pm1 [simp]: "a - b + min b a = (a :: nat)" by arith lemma min_minus [simp]: "min m (m - k) = (m - k :: nat)" by arith lemma min_minus' [simp]: "min (m - k) m = (m - k :: nat)" by arith end
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) (* prefix: gga_x_ak13_params *params; assert(p->params != NULL); params = (gga_x_ak13_params * )(p->params); *) ak13_f0 := s -> 1 + params_a_B1*s*log(1 + s) + params_a_B2*s*log(1 + log(1 + s)): ak13_f := x -> ak13_f0(X2S*x): f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(ak13_f, rs, zeta, xs0, xs1):
module mod_diagnostics ! Provides various diagnostic functions. use mod_kinds, only: ik, rk implicit none private public :: ke, mean interface mean module procedure :: mean_1d, mean_2d end interface mean contains pure elemental real(rk) function ke(u, v) ! Computes the kinetic energy as 1/2 (u^2 + v^2) real(rk), intent(in) :: u, v ke = 0.5_rk * sqrt(u**2 + v**2) end function ke pure real(rk) function mean_1d(x) result(mean) real(rk), intent(in) :: x(:) mean = sum(x) / size(x) end function mean_1d pure real(rk) function mean_2d(x) result(mean) real(rk), intent(in) :: x(:, :) mean = sum(x) / size(x) end function mean_2d end module mod_diagnostics
# Ferreira et.al. 2018 Following is its notation and description | Parameter | description | | :------------------: | :----------------------------------------------------------- | | $K$ | Total number of available price vectors | | $N$ | Total number of products | | $M$ | Total number of kinds of resource | | $T$ | Total number of periods | | $[x]$ | We define $[x]$ as a set, $[x]=\{1,2,\cdots, x\}$ | | $i$ | Index of products | | $j$ | Index of resources | | $t$ | Index of period | | $I_j,I_j(t)$ | $I_j$ is the initial inventory for each resource $j\in [M]$, $I_j(t)$ is the inventory at the end of period $t$. $I_j(0)=I_j$ | | $a_{ij}$ | When we produced one unit item $i$, it would consume $a_{ij}$ unit $j$ | | $c_j$ | we define $c_j=\frac{I_j}{t}$ | | $p_k$ | We define $\{p_1,p_2,\cdots,p_K\}$ as the admissible price vectors, each $p_k$ is a $N\times 1$ vector, specifying the price of each product, $p_k=(p_{1k},\cdots,p_{Nk})$, where $p_{ik}$ is the price of product $i$, for $i\in [N]$. We define $p_{\infty}$ as a "shut-off" price, such that the demand for any product under this price is zero. | | $P(t)$ | We denote by $P(t)=(P_1(t),\cdots,P_N(t))$ the prices chosen by the retailer in this period, and require that $P(t)\in \{p_1,p_2,\cdots,p_K,p_{\infty}\}$ | | $D(t)$ | We denote by $D(t) = (D_1(t),\cdots,D_N(t))$ the demand of each product at period $t$. We assume that given $P(t)=p_k$, the demand $D(t)$ is sampled from a probability distribution on $\mathbb{R}^{N}_+$ with joint cumulative distribution function (CDF) $F (x_1,\cdots,x_N, pk, \theta )$. $D(t)$ is independent of the history $\mathcal{H}_{t-1}$, given $P(t)$ | | $\theta$ | $\theta$ is the parameter of demand distribution, takes values in the parameter space $\Theta\subset\mathbb{R}^l$. The nature would sample $\theta$ from a prior distribution at the beginning form the process. The distribution is assumed to be subexponential; | | $\mathcal{H}_{t }$ | $\mathcal{H}_{t}=(P(1),D(1),\cdots,P(t),D(t))$ | | $\xi(t)$ | At the beginning of each period $t\in[T]$, the retailer observes some context $\xi(t)$, $\xi(t)$ belongs to some discrete set $\mathcal{X}$. We assume $\xi(t)$ is sampled i.i.d from a known distribution. | | $d_{ik}(\xi|\theta)$ | The mean demand of product $i\in [N]$ under price vector $p_k$, $\forall k\in[K]$, given context $\xi$ and parameter $\theta$ | ## 1 st algorithm We implement the 4th algorithm of Ferreira et.al. 2018 The most difficult task in the implementation of this algorithm is the update rule of posterior. In fact, for most of the prior distribution, it is nearly impossible to derive the explict expression of posterior distribution. Here, we would like to simplify this process. We generate K * N matrix from beta(1, 1), in other words, uniform distribution in $[0, 1]$. Each entry corresponds to a product in each pricing vector. We let $d_{k,i}$ denote the demand of $i^{th}$ product given $k^{th}$ pricing vector. We assume $$ \begin{align} Pr(d_{k,i} = 1) & = \Theta_{k,i}\\ Pr(d_{k,i} = 0) & = 1 - \Theta_{k,i}\\ \end{align} $$ In this case, it would be quite easy to update the posterior distribution. Assume we adopt $k^{th}$ price vector $p_k$ in period $t_1, t_2, \cdots, t_\tau$, For each $k\in [K], i\in [N]$, the poseterior density function of $\Theta_{k,i}$ is $$ \begin{align} f(\theta_{k,i} | (p^{(t_1)}_{k},d^{(t_1)}_k),\cdots, (p^{(t_\tau)}_{k},d^{(t_\tau)}_k)) & = \frac{Pr(d^{(t_1)}_k,\cdots, ,d^{(t_\tau)}_k \ | \ \theta_{k,i}) * 1}{\int_{0}^{1}Pr(d^{(t_1)}_k,\cdots, ,d^{(t_\tau)}_k \ | \ \theta)*1d\theta}\\ &=\frac{\prod_{j=1}^\tau Pr(d^{(t_j)}_k| \ \theta_{k,i}) * 1}{\int_{0}^{1}\prod_{j=1}^\tau Pr(d^{(t_j)}_k| \ \theta)*1d\theta}\\ &=\frac{\theta_{k,i}^{\sum_{j=1}^\tau d^{(t_j)}_k} (1-\theta_{k,i})^{\tau-\sum_{j=1}^\tau d^{(t_j)}_k}}{\int_{0}^{1}\theta^{\sum_{j=1}^\tau d^{(t_j)}_k} (1-\theta)^{\tau-\sum_{j=1}^\tau d^{(t_j)}_k}d\theta}\\ &=beta(\sum_{j=1}^\tau d^{(t_j)}_k, \tau-\sum_{j=1}^\tau d^{(t_j)}_k) \end{align} $$ $d^{(i)}_j$ is the demand of $j^{th}$ product in $i^{th}$ period Well, there are also tough problems. That is, there would be counter-intuitive random number. For example, **higher price lead to higher demand**. But anyway, I tried my best to find a suitable prior distribution, but I failed to do so. So I decided to just use this easier one. ```python %reset -f import numpy as np import pandas as pd # we would restore our result in csv file .\\Result_Ferreira et.al. 2018 Algorithm 1\\ import datetime import pyscipopt from pyscipopt import quicksum random_seed = 12345 np.random.seed(random_seed) ``` ```python # Generate parameters K = np.random.randint(low = 1, high = 5) # Total number of available price vectors N = np.random.randint(low = 1, high = 5) # Total number of products M = np.random.randint(low = 1, high = 5) # Total number of kinds of resource T = 1000 # Total number of periods # each row represent an admissible pricing strategy P_list = np.float64(np.random.randint(low = 1, high = 10, size = (K, N))) # initialize inventory I_0 = np.float64(np.random.randint(low = 9000, high = 11000, size = M))# 如果要改变T的话,这里也要对应改变 # resource 应该和T有线性关系 c = I_0 / T # c is the average cost of each resource # initialize a_ij A = np.float64(np.random.randint(low = 5, high = 15, size = (N,M))) # initialize real parameter theta theta = np.random.beta(a = 1, b = 1, size = (K,N)) # initialize history H_P = np.zeros(shape = T) # the index of pricing vector we used in each period H_D = np.zeros(shape = (T, N)) # the demand of products in each period H_I = np.zeros(shape = (T + 1, M)) # avaliable inventory in each period H_I[0, :] = np.float64(I_0) H_bestX = np.zeros(shape = (T, K + 1)) # the best solution in each optimization H_reward = np.zeros(T) # the reward in each period # each realization of price vector, index of period, # corresponds to a estimate of theta H_alpha = np.zeros(shape = (T + 1,K,N)) H_beta = np.zeros(shape = (T + 1,K,N)) H_alpha[0, :, :] = 1 * np.ones(shape = (K,N)) H_beta[0, :, :] = 1 * np.ones(shape = (K,N)) # initialize the constraint value in each round # M kinds of resources correspond to M constraints, and one more constraint is x1 + ... + xN <=1 H_constraint_value = np.zeros(shape = (T, M + 1)) # vectorize beta sample function to accelerate mybeta = np.vectorize(np.random.beta) H_theta = np.zeros(shape = (T,K,N)) # vectorize binomial sample function to accelerate mybinomial = np.vectorize(np.random.binomial) ``` ```python # implementation of algorithm 1 for t in range(1, T+1): # for t in range(1, 2): # first step, sample from posterior distribution # H_alpha[t-1, :, :], H_beta[t-1, :, :] is the history data from 0 to t # H_theta[t-1, :, :] is the sample theta we used in round t H_theta[t-1, :, :] = mybeta(H_alpha[t-1, :, :], H_beta[t-1, :, :]) # first step, calculate the mean demand given sample theta demand_mean = H_theta[t-1, :, :] # second step, optimize a linear function model = pyscipopt.Model("Optimization in Rount {:d}".format(t)) # generate decision variable x = {} for xindex in range(1, K+1): x[xindex] = model.addVar(vtype="C", lb = 0, ub = 1, name="x{:d}".format(xindex)) # second step, generate object function obj_coefficient = np.sum(demand_mean * P_list, axis = 1)# obj_coefficient[k] = $\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1}$ model.setObjective(quicksum(x[xindex]*obj_coefficient[xindex-1] for xindex in range(1, K+1)), "maximize") # objective = $\sum_{k=1}^K(\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1})x_{k}$ # second step, add constraint x_1+...+x_k<=1 constraint_index = {} constraint_index[0] = model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j for jj in range(1, M+1): # size(A) = [N, M], size(demand_mean) = [K, N] con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ constraint_index[jj] = model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[jj - 1]) # second step, optimize the problem model.optimize() bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero for xindex in range(1,K+1): bestx[xindex - 1] = model.getVal(x[xindex]) bestx[K] = 1 - np.sum(bestx[0:K]) eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution bestx = np.array([eliminate_error(x) for x in bestx]) bestx = bestx / np.sum(bestx) # third step, offer price price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the constraint value in optimization H_constraint_value[t - 1, 0] = np.sum(bestx[0:K]) for jj in range(1, M+1): con_coefficient = np.array(list(model.getValsLinear(constraint_index[jj]).values())) H_constraint_value[t - 1, jj] = np.sum(bestx[0:K] * con_coefficient) # fourth step, record the optimal solution in this round H_bestX[t - 1, :] = bestx # fourth step, record the realization of demand if price_offered_index < K + 1: H_D[t - 1, :] = mybinomial(np.ones(N), theta[price_offered_index - 1, :]) # record the realization of demand else: # the demand must be zero H_D[t - 1, :] = np.zeros(N) # fourth step, record the reward in this period if price_offered_index < K + 1: H_reward[t - 1] = P_list[price_offered_index - 1, :].dot(H_D[t - 1, :]) # record the realization of demand else: # the demand must be zero H_reward[t - 1] = 0 # fourth step, record the remain inventory, size(A) = [N, M] H_I[t] = H_I[t - 1] - np.transpose(A).dot(H_D[t - 1, :]) if not all(H_I[t] >= 0): break # fourth step, record the new estimate of alpha and beta if price_offered_index < K + 1: # if demand = 1, then alpha plus 1; if demand = 0, then alpha remain unchanged H_alpha[t, :, :] = H_alpha[t - 1, :, :] H_alpha[t, price_offered_index - 1, :] = H_alpha[t, price_offered_index - 1, :] + H_D[t - 1, :] # if demand = 1, then beta remained unchanged; if demand = 0, then beta plus 1 H_beta[t, :, :] = H_beta[t - 1, :, :] H_beta[t, price_offered_index - 1, :] = H_beta[t - 1, price_offered_index - 1, :] + np.ones(N) - H_D[t - 1, :] else: # the demand must be zero, then all the estimate remain unchanged H_alpha[t, :, :] = H_alpha[t - 1, :, :] H_beta[t, :, :] = H_beta[t - 1, :, :] print("Total reward of algorithm = {:f}".format(np.sum(H_reward))) ``` Total reward of algorithm = 3624.000000 t, M, N, K constraint_index model.getValsLinear(constraint_index [1]), model.getValsLinear(constraint_index [2]) x model.getVal(x[1]), model.getVal(x[2]), model.getVal(x[3]) bestx 0.530018723612461 * 10.376003106593089, 0.530018723612461 * 17.74088269167503, c model.getValsLinear(constraint_index [1]) model.getValsLinear(constraint_index [2]) model.getConss() model.getNConss() model.getValsLinear(model.getConss()[0]) model.getValsLinear(model.getConss()[1]) ```python c ``` array([10.393, 10.339]) ```python # generate the csv data file and restore it into csv file from datetime import datetime moment = str(datetime.now()).replace(':', '-').replace(' ', '_')[:-7] # the value of moment: '2021-10-21_11-39-24', we used this varibale to name our files # we firstly input the parameter into txt file prameter_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_ParameterList.txt".format(K, N, M, T, random_seed) with open(".\\Result_Ferreira et.al. 2018 Algorithm 1\\" + prameter_filename, 'w') as f: f.write("K = {:d}\n".format(K)) f.write("N = {:d}\n".format(N)) f.write("M = {:d}\n".format(M)) f.write("randomseed = {:d}\n".format(random_seed)) f.write("-----Admissible Prive Vector------\n") for kindex in range(K): f.write("Price vector {:d} : {:s}\n".format(kindex, str(P_list[kindex, :]))) f.write("-----Initial Inventory------\n") f.write("Initial Inventory: {:s}\n".format(str(I_0))) f.write("-----Resource Consumption------\n") for nindex in range(N): f.write("Cost of resource of product {:d}: {:s}\n".format(nindex + 1, str(A[nindex, :]))) f.write("-----Resouce Constraint in each round------\n") for nindex in range(N): f.write("c : {:s}\n".format(str(c))) f.write("-----Real theta------\n") for kindex in range(K): f.write("Given price vector {:d}, the real theta is {:s}\n".format(kindex + 1, str(theta[kindex, :]))) # then we input the experiment into csc file, we use period as index data = pd.DataFrame({"Pricing_index": H_P, "Reward": H_reward}) data['Period_index'] = range(1, T+1) # add the demand of each product data = pd.concat([data, pd.DataFrame(H_D, columns = ["product_{:d}_demand".format(nindex) for nindex in range(1,N+1)])], axis = 1) # add the remain invetory of each resource data = pd.concat([data, pd.DataFrame(H_I[0:T, :], columns = ["resouce_{:d}".format(mindex) for mindex in range(1,M+1)])], axis = 1) # add the constraint value data = pd.concat([data, pd.DataFrame(H_constraint_value[0:T, :], columns = ["constraint_{:d}".format(conindex) for conindex in range(0,M+1)])], axis = 1) # add the best solution in each round data = pd.concat([data, pd.DataFrame(H_bestX,\ columns = ["use_price_index_{:d}".format(kindex) for kindex in range(1,K+1)] + ["use_infinite_price"])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_alpha[0:T, :, :], newshape =(T, K * N)), columns = ["alpha_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_beta[0:T, :, :], newshape =(T, K * N)), columns = ["beta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of theta data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_theta[0:T, :, :], newshape =(T, K * N)), columns = ["theta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) exp_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_Experiment.csv".format(K, N, M, T, random_seed) data.to_csv(".\\Result_Ferreira et.al. 2018 Algorithm 1\\" + exp_filename, index = False) ``` ```python # clear the memory H_reward = np.zeros(T) # the reward in each period H_bestX = np.zeros(shape = (T, K + 1)) # the best solution in each optimization H_P = np.zeros(shape = T) # the index of pricing vector we used in each period H_D = np.zeros(shape = (T, N)) # the demand of products in each period H_I = np.zeros(shape = (T + 1, M)) # avaliable inventory in each period H_I[0, :] = np.float64(I_0) ``` ```python # if we replace step 1 with true theta for t in range(1, T+1): # first step, sample from posterior distribution # H_alpha[t-1, :, :], H_beta[t-1, :, :] is the history data from 0 to t # H_theta[t-1, :, :] is the sample theta we used in round t # H_theta[t-1, :, :] = mybeta(H_alpha[t-1, :, :], H_beta[t-1, :, :]) # first step, calculate the mean demand given sample theta demand_mean = theta # second step, optimize a linear function model = pyscipopt.Model("Optimization in Rount {:d}".format(t)) # generate decision variable x = {} for xindex in range(1, K+1): x[xindex] = model.addVar(vtype="C", lb = 0, ub = 1, name="x{:d}".format(xindex)) # second step, generate object function obj_coefficient = np.sum(demand_mean * P_list, axis = 1)# obj_coefficient[k] = $\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1}$ model.setObjective(quicksum(x[xindex]*obj_coefficient[xindex-1] for xindex in range(1, K+1)), "maximize") # objective = $\sum_{k=1}^K(\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1})x_{k}$ # # second step, add constraint x_1+...+x_k<=1 # model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j # for jj in range(1, M+1): # # size(A) = [N, M], size(demand_mean) = [K, N] # con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ # model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[jj - 1]) # # second step, optimize the problem # model.optimize() # bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero # for xindex in range(1,K+1): # bestx[xindex - 1] = model.getVal(x[xindex]) # bestx[K] = 1 - np.sum(bestx[0:K]) # eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution # bestx = np.array([eliminate_error(x) for x in bestx]) # bestx = bestx / np.sum(bestx) # # third step, offer price # price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # second step, add constraint x_1+...+x_k<=1 constraint_index = {} constraint_index[0] = model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j for jj in range(1, M+1): # size(A) = [N, M], size(demand_mean) = [K, N] con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ constraint_index[jj] = model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[jj - 1]) # second step, optimize the problem model.optimize() bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero for xindex in range(1,K+1): bestx[xindex - 1] = model.getVal(x[xindex]) bestx[K] = 1 - np.sum(bestx[0:K]) eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution bestx = np.array([eliminate_error(x) for x in bestx]) bestx = bestx / np.sum(bestx) # third step, offer price price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the constraint value in optimization H_constraint_value[t - 1, 0] = np.sum(bestx[0:K]) for jj in range(1, M+1): con_coefficient = np.array(list(model.getValsLinear(constraint_index[jj]).values())) H_constraint_value[t - 1, jj] = np.sum(bestx[0:K] * con_coefficient) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the optimal solution in this round H_bestX[t - 1, :] = bestx # fourth step, record the realization of demand if price_offered_index < K + 1: H_D[t - 1, :] = mybinomial(np.ones(N), theta[price_offered_index - 1, :]) # record the realization of demand else: # the demand must be zero H_D[t - 1, :] = np.zeros(N) # fourth step, record the reward in this period if price_offered_index < K + 1: H_reward[t - 1] = P_list[price_offered_index - 1, :].dot(H_D[t - 1, :]) # record the realization of demand else: # the demand must be zero H_reward[t - 1] = 0 # fourth step, record the remain inventory, size(A) = [N, M] H_I[t, :] = H_I[t - 1, :] - np.transpose(A).dot(H_D[t - 1, :]) if not all(H_I[t, :] >= 0): break print("Total reward of known distribution: {:f}".format(np.sum(H_reward))) ``` Total reward of known distribution: 4254.000000 ```python # then input the experiment into csc file, we use period as index data = pd.DataFrame({"Pricing_index": H_P, "Reward": H_reward}) data['Period_index'] = range(1, T+1) # add the demand of each product data = pd.concat([data, pd.DataFrame(H_D, columns = ["product_{:d}_demand".format(nindex) for nindex in range(1,N+1)])], axis = 1) # add the remain invetory of each resource data = pd.concat([data, pd.DataFrame(H_I[0:T, :], columns = ["resouce_{:d}".format(mindex) for mindex in range(1,M+1)])], axis = 1) # add the constraint value data = pd.concat([data, pd.DataFrame(H_constraint_value[0:T, :], columns = ["constraint_{:d}".format(conindex) for conindex in range(0,M+1)])], axis = 1) # add the best solution in each round data = pd.concat([data, pd.DataFrame(H_bestX,\ columns = ["use_price_index_{:d}".format(kindex) for kindex in range(1,K+1)] + ["use_infinite_price"])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_alpha[0:T, :, :], newshape =(T, K * N)), columns = ["alpha_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_beta[0:T, :, :], newshape =(T, K * N)), columns = ["beta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of theta data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_theta[0:T, :, :], newshape =(T, K * N)), columns = ["theta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) exp_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_RealThetaExperiment.csv".format(K, N, M, T, random_seed) data.to_csv(".\\Result_Ferreira et.al. 2018 Algorithm 1\\" + exp_filename, index = False) ``` ## 2 nd algorithm We implement the 4th algorithm of Ferreira et.al. 2018 $c_j(t) = \frac{I_j(t-1)}{T-t+1}$ ```python %reset -f import numpy as np import pandas as pd import pyscipopt from pyscipopt import quicksum random_seed = 12345 np.random.seed(random_seed) ``` ```python # Generate parameters K = np.random.randint(low = 1, high = 5) # Total number of available price vectors N = np.random.randint(low = 1, high = 5) # Total number of products M = np.random.randint(low = 1, high = 5) # Total number of kinds of resource T = 1000 # Total number of periods # generate the demand # each row represent an admissible pricing strategy P_list = np.float64(np.random.randint(low = 1, high = 10, size = (K, N))) # initialize inventory I_0 = np.float64(np.random.randint(low = 9000, high = 11000, size = M)) c = np.zeros(shape = (T, M)) # we would update c in each period # initialize a_ij A = np.float64(np.random.randint(low = 5, high = 15, size = (N,M))) # initialize real parameter theta theta = np.random.beta(a = 1, b = 1, size = (K,N)) # initialize history H_P = np.zeros(shape = T) # the index of pricing vector we used in each period H_D = np.zeros(shape = (T, N)) # the demand of products in each period H_I = np.zeros(shape = (T + 1, M)) # avaliable inventory in each period H_I[0, :] = np.float64(I_0) H_bestX = np.zeros(shape = (T, K + 1)) # the best solution in each optimization H_reward = np.zeros(T) # the reward in each period # each realization of price vector, index of period, # corresponds to a estimate of theta H_alpha = np.zeros(shape = (T + 1,K,N)) H_beta = np.zeros(shape = (T + 1,K,N)) H_alpha[0, :, :] = 1*np.ones(shape = (K,N)) H_beta[0, :, :] = 1*np.ones(shape = (K,N)) # initialize the constraint value in each round # M kinds of resources correspond to M constraints, and one more constraint is x1 + ... + xN <=1 H_constraint_value = np.zeros(shape = (T, M + 1)) # vectorize beta sample function to accelerate mybeta = np.vectorize(np.random.beta) H_theta = np.zeros(shape = (T,K,N)) # vectorize binomial sample function to accelerate mybinomial = np.vectorize(np.random.binomial) ``` ```python # implementation of algorithm 2 for t in range(1, T+1): # first step, sample from posterior distribution # H_alpha[t-1, :, :], H_beta[t-1, :, :] is the history data from 0 to t # H_theta[t-1, :, :] is the sample theta we used in round t H_theta[t-1, :, :] = mybeta(H_alpha[t-1, :, :], H_beta[t-1, :, :]) # first step, calculate the mean demand given sample theta demand_mean = H_theta[t-1, :, :] # second step, optimize a linear function model = pyscipopt.Model("Optimization in Rount {:d}".format(t)) # generate decision variable x = {} for xindex in range(1, K+1): x[xindex] = model.addVar(vtype="C", lb = 0, ub = 1, name="x{:d}".format(xindex)) # second step, generate object function obj_coefficient = np.sum(demand_mean * P_list, axis = 1)# obj_coefficient[k] = $\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1}$ model.setObjective(quicksum(x[xindex]*obj_coefficient[xindex-1] for xindex in range(1, K+1)), "maximize") # objective = $\sum_{k=1}^K(\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1})x_{k}$ # # second step, add constraint x_1+...+x_k<=1 # model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j # c[t - 1, :] = H_I[t - 1, :] / (T - t + 1) # for jj in range(1, M+1): # # size(A) = [N, M], size(demand_mean) = [K, N] # con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ # model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[t - 1, jj - 1]) # # second step, optimize the problem # model.optimize() # bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero # for xindex in range(1,K+1): # bestx[xindex - 1] = model.getVal(x[xindex]) # bestx[K] = 1 - np.sum(bestx[0:K]) # eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution # bestx = np.array([eliminate_error(x) for x in bestx]) # bestx = bestx / np.sum(bestx) # # third step, offer price # price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # second step, add constraint x_1+...+x_k<=1 constraint_index = {} constraint_index[0] = model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j c[t - 1, :] = H_I[t - 1, :] / (T - t + 1) for jj in range(1, M+1): # size(A) = [N, M], size(demand_mean) = [K, N] con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ constraint_index[jj] = model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[t - 1, jj - 1]) # second step, optimize the problem model.optimize() bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero for xindex in range(1,K+1): bestx[xindex - 1] = model.getVal(x[xindex]) bestx[K] = 1 - np.sum(bestx[0:K]) eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution bestx = np.array([eliminate_error(x) for x in bestx]) bestx = bestx / np.sum(bestx) # third step, offer price price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the constraint value in optimization H_constraint_value[t - 1, 0] = np.sum(bestx[0:K]) for jj in range(1, M+1): con_coefficient = np.array(list(model.getValsLinear(constraint_index[jj]).values())) H_constraint_value[t - 1, jj] = np.sum(bestx[0:K] * con_coefficient) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the optimal solution in this round H_bestX[t - 1, :] = bestx # fourth step, record the realization of demand if price_offered_index < K + 1: H_D[t - 1, :] = mybinomial(np.ones(N), theta[price_offered_index - 1, :]) # record the realization of demand else: # the demand must be zero H_D[t - 1, :] = np.zeros(N) # fourth step, record the reward in this period if price_offered_index < K + 1: H_reward[t - 1] = P_list[price_offered_index - 1, :].dot(H_D[t - 1, :]) # record the realization of demand else: # the demand must be zero H_reward[t - 1] = 0 # fourth step, record the remain inventory, size(A) = [N, M] H_I[t] = H_I[t - 1] - np.transpose(A).dot(H_D[t - 1, :]) if not all(H_I[t] >= 0): break # fourth step, record the new estimate of alpha and beta if price_offered_index < K + 1: # if demand = 1, then alpha plus 1; if demand = 0, then alpha remain unchanged H_alpha[t, :, :] = H_alpha[t - 1, :, :] H_alpha[t, price_offered_index - 1, :] = H_alpha[t, price_offered_index - 1, :] + H_D[t - 1, :] # if demand = 1, then beta remained unchanged; if demand = 0, then beta plus 1 H_beta[t, :, :] = H_beta[t - 1, :, :] H_beta[t, price_offered_index - 1, :] = H_beta[t - 1, price_offered_index - 1, :] + np.ones(N) - H_D[t - 1, :] else: # the demand must be zero, then all the estimate remain unchanged H_alpha[t, :, :] = H_alpha[t - 1, :, :] H_beta[t, :, :] = H_beta[t - 1, :, :] print("Total reward of algorithm = {:f}".format(np.sum(H_reward))) ``` Total reward of algorithm = 4259.000000 ```python # generate the csv data file and restore it into csv file from datetime import datetime moment = str(datetime.now()).replace(':', '-').replace(' ', '_')[:-7] # the value of moment: '2021-10-21_11-39-24', we used this varibale to name our files # we firstly input the parameter into txt file prameter_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_ParameterList.txt".format(K, N, M, T, random_seed) with open(".\\Result_Ferreira et.al. 2018 Algorithm 2\\" + prameter_filename, 'w') as f: f.write("K = {:d}\n".format(K)) f.write("N = {:d}\n".format(N)) f.write("M = {:d}\n".format(M)) f.write("randomseed = {:d}\n".format(random_seed)) f.write("-----Admissible Prive Vector------\n") for kindex in range(K): f.write("Price vector {:d} : {:s}\n".format(kindex, str(P_list[kindex, :]))) f.write("-----Initial Inventory------\n") f.write("Initial Inventory: {:s}\n".format(str(I_0))) f.write("-----Resource Consumption------\n") for nindex in range(N): f.write("Cost of resource of product {:d}: {:s}\n".format(nindex + 1, str(A[nindex, :]))) f.write("-----Real theta------\n") for kindex in range(K): f.write("Given price vector {:d}, the real theta is {:s}\n".format(kindex + 1, str(theta[kindex, :]))) # then we input the experiment into csc file, we use period as index data = pd.DataFrame({"Pricing_index": H_P, "Reward": H_reward}) data['Period_index'] = range(1, T+1) # add the demand of each product data = pd.concat([data, pd.DataFrame(H_D, columns = ["product_{:d}_demand".format(nindex) for nindex in range(1,N+1)])], axis = 1) # add the remain invetory of each resource data = pd.concat([data, pd.DataFrame(H_I[0:T, :], columns = ["resouce_{:d}".format(mindex) for mindex in range(1,M+1)])], axis = 1) # add the constraint value data = pd.concat([data, pd.DataFrame(H_constraint_value[0:T, :], columns = ["constraint_{:d}".format(conindex) for conindex in range(0,M+1)])], axis = 1) # add the resource limits data = pd.concat([data, pd.DataFrame(c[0:T, :], columns = ["c_{:d}".format(conindex) for conindex in range(1,M+1)])], axis = 1) # add the best solution in each round data = pd.concat([data, pd.DataFrame(H_bestX,\ columns = ["use_price_index_{:d}".format(kindex) for kindex in range(1,K+1)] + ["use_infinite_price"])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_alpha[0:T, :, :], newshape =(T, K * N)), columns = ["alpha_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_beta[0:T, :, :], newshape =(T, K * N)), columns = ["beta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of theta data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_theta[0:T, :, :], newshape =(T, K * N)), columns = ["theta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) exp_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_Experiment.csv".format(K, N, M, T, random_seed) data.to_csv(".\\Result_Ferreira et.al. 2018 Algorithm 2\\" + exp_filename, index = False) ``` # clear the memory H_reward = np.zeros(T) # the reward in each period H_bestX = np.zeros(shape = (T, K + 1)) # the best solution in each optimization H_P = np.zeros(shape = T) # the index of pricing vector we used in each period H_D = np.zeros(shape = (T, N)) # the demand of products in each period H_I = np.zeros(shape = (T + 1, M)) # avaliable inventory in each period H_I[0, :] = np.float64(I_0) c = np.zeros(shape = (T, M))# if we replace step 1 with true theta for t in range(1, T+1): # first step, sample from posterior distribution # H_alpha[t-1, :, :], H_beta[t-1, :, :] is the history data from 0 to t # H_theta[t-1, :, :] is the sample theta we used in round t # H_theta[t-1, :, :] = mybeta(H_alpha[t-1, :, :], H_beta[t-1, :, :]) # first step, calculate the mean demand given sample theta demand_mean = theta # second step, optimize a linear function model = pyscipopt.Model("Optimization in Rount {:d}".format(t)) # generate decision variable x = {} for xindex in range(1, K+1): x[xindex] = model.addVar(vtype="C", lb = 0, ub = 1, name="x{:d}".format(xindex)) # second step, generate object function obj_coefficient = np.sum(demand_mean * P_list, axis = 1)# obj_coefficient[k] = $\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1}$ model.setObjective(quicksum(x[xindex]*obj_coefficient[xindex-1] for xindex in range(1, K+1)), "maximize") # objective = $\sum_{k=1}^K(\sum_{i=1}^N d_{i,k+1}(t)p_{i,k+1})x_{k}$ # second step, add constraint x_1+...+x_k<=1 model.addCons(quicksum(x[xindex] for xindex in range(1, K+1)) <= 1) # second step, for each resources, we require \sum_{k=1}^K\sum_{i=1}^N d_{i,k}a_{i,j}x_l<=c_j c[t-1, :] = H_I[t-1, :] / (T - t + 1) for jj in range(1, M+1): # size(A) = [N, M], size(demand_mean) = [K, N] con_coefficient = A[:, jj - 1].dot(np.transpose(demand_mean))# con_coefficient[k] = $\sum_{i=1}^N a_{i,j}d_{i,k+1}$ model.addCons(quicksum(x[xindex] * con_coefficient[xindex - 1] for xindex in range(1, K+1)) <= c[t - 1, jj - 1]) # second step, optimize the problem model.optimize() bestx = np.zeros(K+1) # p_{K+1} would force the demand be zero for xindex in range(1,K+1): bestx[xindex - 1] = model.getVal(x[xindex]) bestx[K] = 1 - np.sum(bestx[0:K]) eliminate_error = lambda x: 0 if np.abs(x) < 1e-10 else x #there would be numerical error in the best solution bestx = np.array([eliminate_error(x) for x in bestx]) bestx = bestx / np.sum(bestx) # third step, offer price price_offered_index = np.random.choice(np.arange(1, K + 2), p = bestx) # fourth step, update estimate of parameter H_P[t - 1] = price_offered_index # record the index of offered price # fourth step, record the optimal solution in this round H_bestX[t - 1, :] = bestx # fourth step, record the realization of demand if price_offered_index < K + 1: H_D[t - 1, :] = mybinomial(np.ones(N), theta[price_offered_index - 1, :]) # record the realization of demand else: # the demand must be zero H_D[t - 1, :] = np.zeros(N) # fourth step, record the reward in this period if price_offered_index < K + 1: H_reward[t - 1] = P_list[price_offered_index - 1, :].dot(H_D[t - 1, :]) # record the realization of demand else: # the demand must be zero H_reward[t - 1] = 0 # fourth step, record the remain inventory, size(A) = [N, M] H_I[t, :] = H_I[t - 1, :] - np.transpose(A).dot(H_D[t - 1, :]) if not all(H_I[t, :] >= 0): break print("Total reward of known distribution: {:f}".format(np.sum(H_reward)))# then input the experiment into csc file, we use period as index data = pd.DataFrame({"Pricing_index": H_P, "Reward": H_reward}) data['Period_index'] = range(1, T+1) # add the demand of each product data = pd.concat([data, pd.DataFrame(H_D, columns = ["product_{:d}_demand".format(nindex) for nindex in range(1,N+1)])], axis = 1) # add the remain invetory of each resource data = pd.concat([data, pd.DataFrame(H_I[0:T, :], columns = ["resouce_{:d}".format(mindex) for mindex in range(1,M+1)])], axis = 1) # add the best solution in each round data = pd.concat([data, pd.DataFrame(H_bestX,\ columns = ["use_price_index_{:d}".format(kindex) for kindex in range(1,K+1)] + ["use_infinite_price"])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_alpha[0:T, :, :], newshape =(T, K * N)), columns = ["alpha_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of alpha data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_beta[0:T, :, :], newshape =(T, K * N)), columns = ["beta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) # add the estimation of theta data = pd.concat([data,\ pd.DataFrame(np.reshape(a = H_theta[0:T, :, :], newshape =(T, K * N)), columns = ["theta_k-{:d}_n-{:d}".format(k, n) for k in range(1, K+1) for n in range(1, N+1) ])], axis = 1) exp_filename = moment + "_K-{:d}_N-{:d}_M-{:d}_T-{:d}_randomseed-{:d}_RealThetaExperiment.csv".format(K, N, M, T, random_seed) data.to_csv(".\\Result_Ferreira et.al. 2018 Algorithm 2\\" + exp_filename, index = False)c ## 3rd algotithm ## 4 th alogrithm We implement the 4th algorithm of Ferreira et.al. 2018 Following is its notation and description | Parameter | description | | :------------------: | :----------------------------------------------------------- | | $K$ | Total number of available price vectors | | $N$ | Total number of products | | $M$ | Total number of kinds of resource | | $T$ | Total number of periods | | $[x]$ | We define $[x]$ as a set, $[x]=\{1,2,\cdots, x\}$ | | $i$ | Index of products | | $j$ | Index of resources | | $t$ | Index of period | | $I_j,I_j(t)$ | $I_j$ is the initial inventory for each resource $j\in [M]$, $I_j(t)$ is the inventory at the end of period $t$. $I_j(0)=I_j$ | | $a_{ij}$ | When we produced one unit item $i$, it would consume $a_{ij}$ unit $j$ | | $c_j$ | we define $c_j=\frac{I_j}{t}$ | | $p_k$ | We define $\{p_1,p_2,\cdots,p_K\}$ as the admissible price vectors, each $p_k$ is a $N\times 1$ vector, specifying the price of each product, $p_k=(p_{1k},\cdots,p_{Nk})$, where $p_{ik}$ is the price of product $i$, for $i\in [N]$. We define $p_{\infty}$ as a "shut-off" price, such that the demand for any product under this price is zero. | | $P(t)$ | We denote by $P(t)=(P_1(t),\cdots,P_N(t))$ the prices chosen by the retailer in this period, and require that $P(t)\in \{p_1,p_2,\cdots,p_K,p_{\infty}\}$ | | $D(t)$ | We denote by $D(t) = (D_1(t),\cdots,D_N(t))$ the demand of each product at period $t$. We assume that given $P(t)=p_k$, the demand $D(t)$ is sampled from a probability distribution on $\mathbb{R}^{N}_+$ with joint cumulative distribution function (CDF) $F (x_1,\cdots,x_N, pk, \theta )$. $D(t)$ is independent of the history $\mathcal{H}_{t-1}$, given $P(t)$ | | $\theta$ | $\theta$ is the parameter of demand distribution, takes values in the parameter space $\Theta\subset\mathbb{R}^l$. The nature would sample $\theta$ from a prior distribution at the beginning form the process. The distribution is assumed to be subexponential; | | $\mathcal{H}_{t }$ | $\mathcal{H}_{t}=(P(1),D(1),\cdots,P(t),D(t))$ | | $\xi(t)$ | At the beginning of each period $t\in[T]$, the retailer observes some context $\xi(t)$, $\xi(t)$ belongs to some discrete set $\mathcal{X}$. We assume $\xi(t)$ is sampled i.i.d from a known distribution. | | $d_{ik}(\xi|\theta)$ | The mean demand of product $i\in [N]$ under price vector $p_k$, $\forall k\in[K]$, given context $\xi$ and parameter $\theta$ | We assume the distribution of demand is calculated as follows: \begin{equation} (D_1,D_2,\cdots,D_{N}) \sim F(d_1, d_2,\cdots,d_N|P,\xi,\theta) \end{equation} $P$ is the price vector we offer, $\xi$ is the observed context variable, $\theta$ is the parameter that we need to estimate, it is sampled from the nature at the beginning of our study. We assume $\theta \sim f_{\Theta}(\theta)$ We furtherly assume the density function of this distribution is $f(d_1, d_2,\cdots,d_N|P,\xi,\theta)$. Then we will derive the posterior distribution of $ \theta$ $$ \begin{align} &f(\theta \ | \ (P_1,\xi_1,D^{(1)}), \ (P_2,\xi_2,D^{(2)}),\cdots, \ (P_t,\xi_t,D^{(t)}))\\ =&\frac{f(\theta, \ (P_1,\xi_1,D^{(1)}), \ (P_2,\xi_2,D^{(2)}),\cdots, \ (P_t,\xi_t,D^{(t)}))}{\int_{-\infty}^{\infty}f_{\Theta}(\theta)\prod_{i=1}^tf(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N|P_i,\xi_i,\theta)d\theta}\\ =&\frac{f(\ (P_1,\xi_1,D^{(1)}), \ (P_2,\xi_2,D^{(2)}),\cdots, \ (P_t,\xi_t,D^{(t)})\ | \ \theta) f_{\Theta}(\theta)}{\int_{-\infty}^{\infty}f_{\Theta}(\theta)\prod_{i=1}^tf(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N|P_i,\xi_i,\theta)d\theta}\\ =&\frac{ f_{\Theta}(\theta)\prod_{i=1}^t f(P_t,\xi_t,D^{(t)}| \ \theta)}{\int_{-\infty}^{\infty}f_{\Theta}(\theta)\prod_{i=1}^tf(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N|P_i,\xi_i,\theta)d\theta}\\ =&\frac{ f_{\Theta}(\theta)\prod_{i=1}^t f(D^{(i)}| \ \theta, P_t,\xi_t,)}{\int_{-\infty}^{\infty}f_{\Theta}(\theta)\prod_{i=1}^tf(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N|P_i,\xi_i,\theta)d\theta}\\ =&\frac{ f_{\Theta}(\theta)\prod_{i=1}^t f(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N| \ \theta, P_t,\xi_t,)}{\int_{-\infty}^{\infty}f_{\Theta}(\theta)\prod_{i=1}^tf(d^{(i)}_1, d^{(i)}_2,\cdots,d^{(i)}_N|P_i,\xi_i,\theta)d\theta}\\ \end{align} $$ $P_i$ is the pricing vector we choose in the $i^{th}$ period $\xi_i$ is the context we observed in the $i^{th}$ period $D^{(i)}$ is the demand vector in $i^{th}$ period $d^{(i)}_j$ is the demand of $j^{th}$ product in $i^{th}$ period To implement this procedure, we need to solve 3 problems 1. Given the real demand generator, we need to calculate its density function. 2. sample random number from a customized density function 3. calculate the integral, numerically We assume the demand follows discrete distribution, that is $d_i$ ```python # Generate parameters np.random.seed(12345) K = np.random.randint(low = 1, high = 5) # Total number of available price vectors N = np.random.randint(low = 1, high = 5) # Total number of products M = np.random.randint(low = 1, high = 5) # Total number of kinds of resource T = 1000 # Total number of periods # generate the demand # each row represent an admissible pricing strategy P_list = np.float64(np.random.randint(low = 1, high = 10, size = (K, M))) # type of context xi_type_num = np.random.randint(low = 3, high = 5 ) # maximum number of context type xi_list = np.float64(np.arange(1, xi_type_num, 1)) # initialize inventory I_0 = np.random.randint(low = 9000, high = 11000, size = M) # initialize a_ij A = np.float64(np.random.randint(low = 5, high = 15, size = (N,M))) # real distribution of theta, we adopt beta distribution here, # here theta is the parameter of beta dirstribution # we assume the alpha and beta is independent of pricing vector , observed vector, and product alpha_real_scalar = np.random.randint(low = 1, high = 3) beta_real_scalar = np.random.randint(low = 2, high = 5) alpha_real = alpha_real_scalar * np.ones(shape = (K, xi_type, N)) beta_real = beta_real_scalar * np.ones(shape = (K, xi_type, N)) # alpha_real = np.random.randint(low = 1, high = 3, size = (K, xi_type, N)) # beta_real = np.random.randint(low = 2, high = 5, size = (K, xi_type, N)) # initialize history H_P = np.zeros(shape = T) # the index of pricing vector we used in each period H_xi = np.zeros(shape = T)# the index of observed context in each period H_D = np.zeros(shape = (T, N)) # the demand of products in each period H_I = np.zeros(shape = (T, M)) # avaliable inventory in each period H_I[0, :] = np.float64(I_0) # each realization of price vector, observed context, index of period, # corresponds to a estimate H_alpha = np.zeros(shape = (T,K,xi_type_num,N)) H_beta = np.zeros(shape = (T,K,xi_type_num,N)) for kk in range(0, K): for xi_index in range(0, xi_type_num): H_alpha[0, kk, xi_index, :] = 1*np.ones(N) H_beta[0, kk, xi_index, :] = 1*np.ones(N) ``` ```python # Given the pricing vector and parameter, we use this function to generate demand def GetDemand(P, xi, theta, num = 1): # P is the pricing vector, N*1 # xi is the context observed by the merchant # theta is the parameter of beta distribution, a N*2 vector # num is the size of return demand, we would return M*num array, each column denote a sample demand # return value is a M*num array, each column denote a sample demand demand_sample = np.zeros(N, num) for ii in range(N): demand_sample[ii, :] = np.random.beta(alpha = alpha[ii], beta = beta[ii], size = num) + xi*5 - P[ii]*2 return demand_sample ``` We derive the update formular here ```python def UpdatePosteriorDistribution(t, H_P, H_xi, H_D, H_alpha, H_beta): # t is the index of period, the history is available from 0-t # H_P is the index of pricing vector in each period # H_xi is the index of obeserved context in each period # alpha_real and beta_real is the estimation of alpha and beta, given alpha_real = alpha_real_scalar * np.ones(shape = (K, xi_type, N)) beta_real = beta_real_scalar * np.ones(shape = (K, xi_type, N)) ``` ```python # implementation of algorithm for tt in range(0, T): # step 1, sample a randome parameter theta alpha_tt = H_alpha[tt] beta_tt = H_beta[tt] # step 1, calculate the mean demand d_mean_tt = np.zeros(N, K) for kk in range(0, K): # traverse all the admissable pricing vector ``` ```python ``` ```python np.float64(12) ``` <ipython-input-23-92a6b828a7ec>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.float(12) 12.0 ```python np.ones(5) ``` array([1., 1., 1., 1., 1.]) ```python theta_real ``` array([0.25 , 0.33333333]) ```python xi_list ``` array([1, 2, 3]) ```python P_list ``` array([[2, 5], [6, 3], [2, 7]]) ```python P_list[:,0] + 2 ``` array([4, 8, 4]) ```python I_0 ``` array([10339, 9654]) ```python I ``` array([[10339., 0., 0., ..., 0., 0., 0.], [ 9654., 0., 0., ..., 0., 0., 0.]]) ```python help(np.zeros) ``` Help on built-in function zeros in module numpy: zeros(...) zeros(shape, dtype=float, order='C', *, like=None) Return a new array of given shape and type, filled with zeros. Parameters ---------- shape : int or tuple of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional, default: 'C' Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. like : array_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as ``like`` supports the ``__array_function__`` protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. .. note:: The ``like`` keyword is an experimental feature pending on acceptance of :ref:`NEP 35 <NEP35>`. .. versionadded:: 1.20.0 Returns ------- out : ndarray Array of zeros with the given shape, dtype, and order. See Also -------- zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. ones : Return a new array setting values to one. full : Return a new array of given shape filled with value. Examples -------- >>> np.zeros(5) array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1)) array([[ 0.], [ 0.]]) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')]) # Neural Contextual Bandits with UCB-based Exploration Notation: | Notation | Description | | :----------------------- | :----------------------------------------------------------- | | $K$ | number of arms | | $T$ | number of total rounds | | $t$ | index of round | | $x_{t,a}$ | $x_{t,a}\in\mathbb{R}^d$, $a\in [K]$, it is the context, the context consists of $K$ feature vectors $\{x_{t,a}\in\mathbb{R}^d|a\in[K]\}$ | | $a_t$ | after observes the context, the agent select an action $a_t$ in round t | | $r_{t,a_t}$ | the reward after the agent select action $a_t$ | | $h$ | we assume that $r_{t,a_t}=h(x_{t,a_t})+\xi_t$, h is an unknown function satisfying $0\le h(x)\le 1$ for any x | | $\xi_t$ | $\xi_t$ is v-sub-Gaussian noise conditioned on $x_{1,a_1},\cdots,x_{t-1,a_{t-1}}$, satisfying $\mathbb{E}\xi_t=0$ | | $L$ | the depth of neural network | | $m$ | number of neural in each layer of network | | $\sigma(x)$ | we define $\sigma(x)=\max\{x,0\}$ | | $W_1,\cdots,W_{L-1},W_L$ | the weight in neural network. $W_1\in\mathbb{R}^{m\times d}$, $W_i\in\mathbb{R}^{m\times m}$, $2\le i\le L-1$, $W_L\in\mathbb{R}^{m\times 1}$ | | $\theta$ | $\theta=[vec(W_1)^T,\cdots,vec(W_l)^T]\in\mathbb{R}^p$, $p=m+md+m^2(L-1)$ | | $f(x;\theta)$ | we define $f(x;\theta)=\sqrt{m}W_L\sigma(W_{l-1}\sigma(\cdots\sigma(W_1x)))$ | Initialization of parameters: UCB algorithm: we set $\mathcal{L}(\theta) = \sum_{i=1}^t\frac{(f(x_{i,a_i};\theta)-r_{i,a_i})^2}{2}+\frac{m\lambda||\theta-\theta^{(0)}||^2_2}{2}$ Then the gradient would be $$ \nabla\mathcal{L}(\theta) = \sum_{i=1}^t(f(x_{i,a_i};\theta)-r_{i,a_i})\nabla f(x_{i,a_i};\theta) + m\lambda(\theta-\theta^{(0)}) $$ Forawar Algorithm of Neural Network $$ \begin{align} X_0 &= X\\ X_1 &=\sigma(W_1X_0)\\ X_2 &=\sigma(W_2X_1)\\ \cdots\\ X_{L-1}&=\sigma(W_{L-1}X_{L-2})\\ X_{L} &=W_L X_{L-1} \end{align} $$ $f(X) = X_L$ Backward Propagation $$ \begin{align} \nabla_{X_L}f &= 1\\ \nabla_{W_L}f &= X_{L-1}\\ \nabla_{X_{L-1}}f &= W_{L}\\ \\ \nabla_{W_{L-1}}f &= \nabla_{W_{L-1}}f(X_{L-1}(W_{L-1}, X_{L-2}), W_L)=\nabla_{X_{L-1}}f \cdot \nabla_{W_{L-1}}X_{L-1}(W_{L-1}, X_{L-2})\\ \nabla_{X_{L-2}}f &= \nabla_{X_{L-2}}f(X_{L-1}(W_{L-1}, X_{L-2}), W_L)=\nabla_{X_{L-1}}f \cdot \nabla_{X_{L-2}}X_{L-1}(W_{L-1}, X_{L-2})\\ \\ \nabla_{W_{L-2}}f &= \nabla_{W_{L-2}}f(X_{L-2}(W_{L-2}, X_{L-3}), W_L,W_{L-1})=\nabla_{X_{L-2}}f \cdot \nabla_{W_{L-2}}X_{L-2}(W_{L-2}, X_{L-3})\\ \nabla_{X_{L-3}}f &= \nabla_{X_{L-3}}f(X_{L-2}(W_{L-2}, X_{L-3}), W_L,W_{L-1})=\nabla_{X_{L-2}}f \cdot \nabla_{X_{L-3}}X_{L-2}(W_{L-2}, X_{L-3})\\ \cdots\\ \nabla_{W_{l}}f &= \nabla_{W_{l}}f(X_{l}(W_{l}, X_{l-1}), W_L,W_{L-1},\cdots,W_{l+1})=\nabla_{X_{l}}f \cdot \nabla_{W_{l}}X_{l}(W_{l}, X_{l-1})\\ \nabla_{X_{l-1}}f &= \nabla_{X_{l-1}}f(X_{l}(W_{l}, X_{l-1}), W_L,W_{L-1},\cdots,W_{l+1})=\nabla_{X_{l}}f \cdot \nabla_{X_{l-1}}X_{l}(W_{l}, X_{l-1})\\ \cdots\\ \nabla_{W_{1}}f &= \nabla_{W_{1}}f(X_{1}(W_{1}, X_{0}), W_L,W_{L-1},\cdots,W_{2})=\nabla_{X_{1}}f \cdot \nabla_{W_{1}}X_{1}(W_{1}, X_{0})\\ \nabla_{X_{0}}f &= \nabla_{X_{0}}f(X_{1}(W_{1}, X_{0}), W_L,W_{L-1},\cdots,W_{2})=\nabla_{X_{1}}f \cdot \nabla_{X_{0}}X_{1}(W_{1}, X_{0})\\ \end{align} $$ $\nabla_{W_{l}}f$ is a matrix, to be specific, $\nabla_{W_{l}}f=\left[\begin{matrix}\frac{\partial f}{\partial w^{(l)}_{11}}&\cdots &\frac{\partial f}{\partial w^{(l)}_{1m}}\\ \vdots&& \vdots\\ \frac{\partial f}{\partial w^{(l)}_{m1}}&\cdots &\frac{\partial f}{\partial w^{(l)}_{mm}}\end{matrix}\right]$ $$ \begin{align} \left[\begin{matrix}\frac{\partial f}{\partial w^{(l)}_{11}}&\cdots &\frac{\partial f}{\partial w^{(l)}_{1m}}\\ \vdots&& \vdots\\ \frac{\partial f}{\partial w^{(l)}_{m1}}&\cdots &\frac{\partial f}{\partial w^{(l)}_{mm}}\end{matrix}\right]=& \left[\begin{matrix}\frac{\partial f}{\partial x^{(l)}_{1}} \frac{\partial x^{(l)}_{1}}{\partial w^{(l)}_{11}}&\cdots &\frac{\partial f}{\partial x^{(l)}_{1}}\frac{\partial x^{(l)}_{1}}{\partial w^{(l)}_{1m}}\\ \vdots&& \vdots\\ \frac{\partial f}{\partial x^{(l)}_{m}}\frac{\partial x^{(l)}_{m}}{\partial w^{(l)}_{m1}}&\cdots &\frac{\partial f}{\partial x^{(l)}_{m}}\frac{\partial x^{(l)}_{m}}{\partial w^{(l)}_{mm}}\end{matrix}\right]\\ =& \left[\begin{matrix}\frac{\partial f}{\partial x^{(l)}_{1}} \mathbb{1}_{\sigma(w^{(l)}_{11}x^{(l-1)}_1+w^{(l)}_{12}x^{(l-1)}_2+\cdots+w^{(l)}_{1m}x^{(l-1)}_m)>0} x^{(l-1)}_{1}&\cdots &\frac{\partial f}{\partial x^{(l)}_{1}}\mathbb{1}_{\sigma(w^{(l)}_{11}x^{(l-1)}_1+w^{(l)}_{12}x^{(l-1)}_2+\cdots+w^{(l)}_{1m}x^{(l-1)}_m)>0} x^{(l-1)}_{m}\\ \vdots&& \vdots\\ \frac{\partial f}{\partial x^{(l)}_{m}}\mathbb{1}_{\sigma(w^{(l)}_{m1}x^{(l-1)}_1+w^{(l)}_{m2}x^{(l-1)}_2+\cdots+w^{(l)}_{mm}x^{(l-1)}_m)>0} x^{(l-1)}_{1}&\cdots &\frac{\partial f}{\partial x^{(l)}_{m}}\mathbb{1}_{\sigma(w^{(l)}_{m1}x^{(l-1)}_1+w^{(l)}_{m2}x^{(l-1)}_2+\cdots+w^{(l)}_{mm}x^{(l-1)}_m)>0} x^{(l-1)}_{m}\end{matrix}\right]\\ \end{align} $$ $\nabla_{X_{l-1}}f$ is a vector, to be specific, $\nabla_{X_{l-1}}f=\left[\begin{matrix}\frac{\partial f}{\partial x^{(l-1)}_{1}}\\ \vdots\\ \frac{\partial f}{\partial x^{(l-1)}_{m}}\end{matrix}\right]$ $$ \begin{align} \left[\begin{matrix}\frac{\partial f}{\partial x^{(l-1)}_{1}}\\ \vdots\\ \frac{\partial f}{\partial x^{(l-1)}_{m}}\end{matrix}\right]=& \left[\begin{matrix}\frac{\partial f}{\partial x^{(l)}_{1}}\frac{\partial x^{(l)}_1}{\partial x^{(l-1)}_1}+\frac{\partial f}{\partial x^{(l)}_{2}}\frac{\partial x^{(l)}_{2}}{\partial x^{(l-1)}_{1}}+\cdots+\frac{\partial f}{\partial x^{(l)}_{m}}\frac{\partial x^{(l)}_{m}}{\partial x^{(l-1)}_{1}}\\ \vdots\\ \frac{\partial f}{\partial x^{(l)}_{1}}\frac{\partial x^{(l)}_{1}}{\partial x^{(l-1)}_{m}}+\frac{\partial f}{\partial x^{(l)}_{2}}\frac{\partial x^{(l)}_{2}}{\partial x^{(l-1)}_{m}}+\cdots+\frac{\partial f}{\partial x^{(l)}_{m}}\frac{\partial x^{(l)}_{m}}{\partial x^{(l-1)}_{m}}\end{matrix}\right]\\ =& \left[\begin{matrix}\frac{\partial f}{\partial x^{(l)}_{1}}\mathbb{1}_{\sigma(w^{(l)}_{11}x^{(l-1)}_1+w^{(l)}_{12}x^{(l-1)}_2+\cdots+w^{(l)}_{1m}x^{(l-1)}_m)>0}w^{(l)}_{11}+\frac{\partial f}{\partial x^{(l)}_{2}}\mathbb{1}_{\sigma(w^{(l)}_{21}x^{(l-1)}_1+w^{(l)}_{22}x^{(l-1)}_2+\cdots+w^{(l)}_{2m}x^{(l-1)}_m)>0}w^{(l)}_{21}+\cdots+\frac{\partial f}{\partial x^{(l)}_{m}}\mathbb{1}_{\sigma(w^{(l)}_{m1}x^{(l-1)}_1+w^{(l)}_{m2}x^{(l-1)}_2+\cdots+w^{(l)}_{mm}x^{(l-1)}_m)>0}w^{(l)}_{m1}\\ \vdots\\ \frac{\partial f}{\partial x^{(l)}_{1}}\mathbb{1}_{\sigma(w^{(l)}_{11}x^{(l-1)}_1+w^{(l)}_{12}x^{(l-1)}_2+\cdots+w^{(l)}_{1m}x^{(l-1)}_m)>0}w^{(l)}_{1m}+\frac{\partial f}{\partial x^{(l)}_{2}}\mathbb{1}_{\sigma(w^{(l)}_{21}x^{(l-1)}_1+w^{(l)}_{22}x^{(l-1)}_2+\cdots+w^{(l)}_{2m}x^{(l-1)}_m)>0}w^{(l)}_{2m}+\cdots+\frac{\partial f}{\partial x^{(l)}_{m}}\mathbb{1}_{\sigma(w^{(l)}_{m1}x^{(l-1)}_1+w^{(l)}_{m2}x^{(l-1)}_2+\cdots+w^{(l)}_{mm}x^{(l-1)}_m)>0}w^{(l)}_{mm}\end{matrix}\right ]\\ =&\left[\begin{matrix}w^{(l)}_{11}&\cdots& w^{(l)}_{1m}\\ \vdots&&\vdots\\ w^{(l)}_{m1}&\cdots& w^{(l)}_{mm}\end{matrix}\right]^T \left[\begin{matrix}\frac{\partial f}{\partial x^{(l)}_{1}}\mathbb{1}_{\sigma(w^{(l)}_{11}x^{(l-1)}_1+w^{(l)}_{12}x^{(l-1)}_2+\cdots+w^{(l)}_{1m}x^{(l-1)}_m)>0}\\ \vdots\\ \frac{\partial f}{\partial x^{(l)}_{m}}\mathbb{1}_{\sigma(w^{(l)}_{m1}x^{(l-1)}_1+w^{(l)}_{m2}x^{(l-1)}_2+\cdots+w^{(l)}_{mm}x^{(l-1)}_m)>0}\end{matrix}\right]\\ \end{align} $$ ```python %reset -f import numpy as np ``` ```python # the setting is based on the description of section 7.1 of the papaer # Set the parameter of the network L = 2 m = 20 # Set the parameter of the game K = 2# Total number of actions, T = 100 # Total number of periods d = 2 # the dimension of context # Total number of parameters in the nerual network # the paper claims that p = m+md+m^2(L-1) # let L = 2, # it also claim that f(x,\theta)=\sqrt{m}W_2\sigma(W_1x) # then the total number of neurals should be m + m * d + m * m * (L - 2) p = m + m * d + m * m * (L - 2) ``` We assume the reward follows reward = context^T * A^T * A * context + \xi $\xi$ is a random variable following standard normal distribution N(0, 1) A is d\*d matrix, randomly generated from N(0, 1) We assume the context is independent from the action and round index. Given action a and round index t, the context is randomly sample from a unit ball in dimension d ```python A = np.random.normal(loc=0, scale=1, size=(d, d)) ``` ```python # Initialize the hyper parameter of neural network here # we fix gamma in each round, according to the description of section 3.1 gamma_t = 0.01 #{0.01, 0.1, 1, 10} v = 0.1 #{0.01, 0.1, 1} lambda_ = 0.01 #{0.01, 0.1, 1} delta = 0.01 #{0.01, 0.1, 1} S = 0.01 #{0.01, 0.1, 1, 10} eta = 1e-3 #{0.001, 0.01, 0.1} # we set J equal to round index t ``` ```python # following are functions that are used to play the game def SampleContext(d, K): # according to the description, the context is uniformly distributed on a d-dimension sphere # d is the dimension of context, a scalar # K is the total number of arts, a scalar # this function return context, as an d*K matrix, each column corresponds a context of action context = np.random.normal(loc=0, scale=1, size=(d, K)) length = np.sqrt( np.sum(context * context, axis = 0) ) length = np.tile(length, (d, 1)) context = context / length # each column represent a context return context def GetRealReward(context, A): # context is the context of arm, a d*1 vector # A is the d*d matrix, # this function return the reward return context.transpose().dot(A.transpose().dot(A)).dot(context) + np.random.normal(loc=0, scale=1) ``` ```python # following are functions that are related to the neural network def Relu(x): # Relu function # if x is a scalar, the return value would be a scalar # if x is a matrix, the return value would be a matrix return np.maximum(x,0) def ReluDerivative(x): # the derivative of Relu function # if x is a scalar, the return value would be a scalar # if x is a matrix, the return value would be a matrix # return np.array([(lambda x: 1 if x > 0 else 0)(xi) for xi in x]) if x > 0: return 1 else: return 0 def NeuralNetwork(X, params, L, m): # X is the input, each column correspont to a context # params is a dictionay, each key corresponds to the weight in each layer # its keys are "w1" , "w2", ..., "w{:d}".format(L). # L is the number of layers # m is the number of neurals in each layer # the return value would be a dictionary, its key would be like "l0", "l1", "l2", ..., "l{:d}".format(L), # each key represent the value of a layer, "l0" is X, the last layer is output X_layer = {} X_layer["x0"] = X for l in range(1, L): X_layer["x" + str(l)] = Relu(params["w" + str(l)].dot(X_layer["x" + str(l-1)])) X_layer["x" + str(L)] = np.sqrt(m) * params["w" + str(L)].dot(X_layer["x" + str(L-1)]) return X_layer def GradientNeuralNetwork(X, params, L, m): # this function calculate the gradient of each parameter in the neural network # X is the context, a 1 dimension vecotr in R^d # params is a dictionary that stores the paraemeters of neural network # its keys are "w1" , "w2", ..., "w{:d}".format(L). # L is the number of layers # m is the number of neurals in each layer # vectorize the function we used myRelu = np.vectorize(Relu) myReluDerivative = np.vectorize(ReluDerivative) # we firstly calculate the value of each layer X_layer = NeuralNetwork(X, params, L, m) # then we calculate the gradient of "X_layer" and gradient of parameter grad_X_layer = {} grad_parameter = {} grad_X_layer["x" + str(L)] = 1 grad_parameter["w" + str(L)] = np.sqrt(m) * X_layer["x" + str(L - 1)] grad_X_layer["x" + str(L - 1)] = np.sqrt(m) * params["w" + str(L)][0, :] for l in range(L - 1, 0, -1): grad_parameter["w" + str(l) ] = grad_X_layer["x" + str(l)] * myReluDerivative(X_layer["x" + str(l)]) grad_parameter["w" + str(l) ] = np.matmul(np.expand_dims(grad_parameter["w" + str(l) ], axis=1),\ np.expand_dims(X_layer["x" + str(l - 1)], axis = 0)) grad_X_layer["x" + str(l - 1)] = grad_X_layer["x" + str(l)] * myReluDerivative(X_layer["x" + str(l)]) grad_X_layer["x" + str(l - 1)] = np.matmul(params["w" + str(l)].transpose(),\ np.expand_dims(grad_X_layer["x" + str(l - 1)] , axis = 1)) return grad_parameter def FlattenGradient(grad_parameter, L): # accroding to the paper, the function f should be a vector in R^p # but what we got in GradientNeuralNetwork is a dictionary, # we would use this function to convert the dictinary into a vector # grad_parameter is the gradient stored in a dictionary # L is the total number of layers # the return value is the flattern vector = [vec(w1)^T, vec(w2)^T, ..., vec(w_L)^T]^T # we firstly generate the order of all the parameter para_order = ["w" + str(l) for l in range(1, L + 1)] #e.g. para_order = ["w1", "w2", "w3"] # then we can combine all the 1 d arrays together gradient = np.concatenate([grad_parameter[para_name].flatten() for para_name in para_order]) return gradient def GradientLossFunction(X, params, L, m, r, theta_0, lambda_): # this function calculate the gradient of lossfunction # X is the matrix of observed contexts, each column represent a context # X is required to be a 2-D matrix here, even sometimes it may only contain one column # params is a dictionary that stores the paraemeters of neural network # its keys are "w1" , "w2", ..., "w{:d}".format(L). # L is the number of layers # m is the number of neurals in each layer # r is the reward in each round # r is required to be a vector here, even sometimes it may only contain one column # theta_0 is the initalized value of parameters, restored as a disctionary #we would repeatedly call GradientNeuralNetwork() to calculate the gradients here # firstly, we calculate the shape of X and r context_num = len(r) # secondly, we calculate the value of each layer X_layer = NeuralNetwork(X, params, L, m) # each value in X_layer would be a # secondly, we repeatedly call GradientNeuralNetwork() to calculate the gradient of regression part grad_loss = {}# apply for space for key in params.keys(): grad_loss[key] = np.zeros(params[key].shape) for ii in range(1, context_num + 1): new_term = GradientNeuralNetwork(X[:, ii - 1], params, L, m) for key in grad_loss.keys(): grad_loss[key] = grad_loss[key] + new_term[key] * (X_layer["x" + str(L)][0, ii - 1] - r[ii - 1]) # grad_loss[key] = grad_loss[key] + new_term[key] * (X_layer["x" + str(L)][0, ii - 1] - r[ii - 1]) / context_num # thirdly, we calculate the gradient of regularization for key in grad_loss.keys(): grad_loss[key] = grad_loss[key] + m * lambda_ * (params[key] - theta_0[key]) return grad_loss # X = np.array([[1, 1], [2, 3]]) # lambda_ = 0 # theta_0 = {"w1": np.zeros((4, 2)), # "w2": np.zeros((1,4))} # r = np.array([0, 0]) # L = 2 # m = 4 # params = {"w1": np.array([[1, 2], [-3, 2], [0, -1], [3, 3]]), # "w2": np.array([[1, 2, 3, -1]])} # grad_loss = GradientLossFunction(X, params, L, m, r, theta_0, lambda_) # X_layer = NeuralNetwork(X, params, L, m) # print(X_layer) # print(grad_loss) # grad_parameter = GradientNeuralNetwork(X[:, 0], params, L, m) # print(grad_parameter) # grad_parameter = GradientNeuralNetwork(X[:, 1], params, L, m) # print(grad_parameter) ``` ```python # we implement the algorithm here from copy import deepcopy #set the random seed np.random.seed(12345) # initialize the value of parameter theta_0 = {} W = np.random.normal(loc = 0, scale = 4 / m, size=(int(m/2), int(m/2))) w = np.random.normal(loc = 0, scale = 4 / m, size=(1, int(m/2))) for key in range(1, L + 1): if key == 1: # this paper doesn't present the initialization of w1 # in its setting, d = m, then he let theta_0["w1"]=[W,0;0,W] # but in fact d might not equal to m tempW = np.random.normal(loc = 0, scale = 4 / m, size=(int(m/2), int(d/2))) theta_0["w1"] = np.zeros((m, d)) theta_0["w1"][0:int(m/2), 0:int(d/2)] = tempW theta_0["w1"][int(m/2):, int(d/2):] = tempW elif 2 <= key and key <= L - 1: theta_0["w" + str(key)] = np.zeros((m, m)) theta_0["w" + str(key)][0:int(m/2), 0:int(m/2)] = W theta_0["w" + str(key)][int(m/2):, 0:int(m/2):] = W else: theta_0["w" + str(key)] = np.concatenate([w, -w], axis = 1) params = deepcopy(theta_0) Z_t_minus1 = lambda_ * np.eye(p) np.random.seed(12345) # implement NeuralUCB reward = np.zeros(T) X_history = np.zeros((d, T)) params_history = {} grad_history = {} for tt in range(1, T + 1): # observe \{x_{t,a}\}_{a=1}^{k=1} context_list = SampleContext(d, K) # compute the upper bound of reward U_t_a = np.zeros(K) # the upper bound of K actions predict_reward = np.zeros(K) for a in range(1, K + 1): predict_reward[a - 1] = NeuralNetwork(context_list[:, a - 1], params, L, m)['x' + str(L)][0] grad_parameter = GradientNeuralNetwork(context_list[:, a - 1], params, L, m) grad_parameter = FlattenGradient(grad_parameter, L) Z_t_minus1_inverse = np.linalg.inv(Z_t_minus1) U_t_a[a - 1] = predict_reward[a - 1] + gamma_t * np.sqrt(grad_parameter.dot(Z_t_minus1_inverse).dot(grad_parameter)/m) ind = np.argmax(U_t_a, axis=None) # ind is the index of action we would play # play ind and observe reward X_history[:, tt - 1] = context_list[:, ind] reward[tt - 1] = GetRealReward(context_list[:, ind], A) print("round {:d}, predicted reward {:4f},\ predicted upper bound {:4f},\ actual reward{:4f}".format(tt, predict_reward[ind], U_t_a[ind], reward[tt - 1])) assert(np.abs(predict_reward[ind]) <= 50) # compute Z_t_minus1 grad_parameter = GradientNeuralNetwork(context_list[:, ind], params, L, m) grad_parameter = FlattenGradient(grad_parameter, L) grad_parameter = np.expand_dims(grad_parameter, axis = 1) Z_t_minus1 = Z_t_minus1 + grad_parameter.dot(grad_parameter.transpose()) / m # train neural network J = tt for j in range(J): grad_loss = GradientLossFunction(X_history[:, 0:tt], params, L, m, reward[0:tt], theta_0, lambda_) for key in params.keys(): params[key] = params[key] - eta * grad_loss[key] params_history[tt] = params grad_history[tt] = grad_loss ``` round 1, predicted reward -0.000424, predicted upper bound 0.090640, actual reward2.272125 round 2, predicted reward 0.068763, predicted upper bound 0.114806, actual reward1.644206 round 3, predicted reward 0.035864, predicted upper bound 0.112615, actual reward2.374053 round 4, predicted reward 0.133829, predicted upper bound 0.159915, actual reward0.621021 round 5, predicted reward 0.125655, predicted upper bound 0.175896, actual reward0.225242 round 6, predicted reward 0.160420, predicted upper bound 0.172339, actual reward1.690004 round 7, predicted reward 0.777125, predicted upper bound 0.800167, actual reward-0.560492 round 8, predicted reward 0.983655, predicted upper bound 1.010498, actual reward0.744462 round 9, predicted reward 1.065241, predicted upper bound 1.076667, actual reward-0.820915 round 10, predicted reward 0.283184, predicted upper bound 0.310808, actual reward1.749863 round 11, predicted reward 0.703293, predicted upper bound 0.738148, actual reward1.670348 round 12, predicted reward 1.105121, predicted upper bound 1.141263, actual reward0.433601 round 13, predicted reward 1.212571, predicted upper bound 1.232599, actual reward1.332337 round 14, predicted reward 0.474813, predicted upper bound 0.492311, actual reward-0.914758 round 15, predicted reward 1.054616, predicted upper bound 1.076929, actual reward2.096148 round 16, predicted reward 0.316751, predicted upper bound 0.331554, actual reward0.559662 round 17, predicted reward 1.622827, predicted upper bound 1.635132, actual reward1.440866 round 18, predicted reward 0.930713, predicted upper bound 0.973603, actual reward1.502516 round 19, predicted reward 1.353896, predicted upper bound 1.373078, actual reward0.416201 round 20, predicted reward 1.559543, predicted upper bound 1.568139, actual reward0.512476 round 21, predicted reward 0.834536, predicted upper bound 0.867873, actual reward0.425917 round 22, predicted reward 1.317566, predicted upper bound 1.328963, actual reward2.076005 round 23, predicted reward 1.364796, predicted upper bound 1.393930, actual reward-0.160265 round 24, predicted reward 1.417134, predicted upper bound 1.426571, actual reward-1.330353 round 25, predicted reward 1.056596, predicted upper bound 1.067803, actual reward0.817492 round 26, predicted reward 0.295162, predicted upper bound 0.315495, actual reward0.331979 round 27, predicted reward 1.039549, predicted upper bound 1.048849, actual reward1.552421 round 28, predicted reward 1.288948, predicted upper bound 1.322777, actual reward1.542083 round 29, predicted reward 1.139483, predicted upper bound 1.150642, actual reward1.281281 round 30, predicted reward 0.928884, predicted upper bound 0.943935, actual reward1.528348 round 31, predicted reward 0.526687, predicted upper bound 0.542968, actual reward1.059209 round 32, predicted reward 1.145122, predicted upper bound 1.155893, actual reward0.838127 round 33, predicted reward 1.031941, predicted upper bound 1.057640, actual reward-0.269146 round 34, predicted reward 0.979327, predicted upper bound 0.996686, actual reward1.154079 round 35, predicted reward 1.324289, predicted upper bound 1.338024, actual reward-0.529172 round 36, predicted reward 1.217855, predicted upper bound 1.227487, actual reward0.535593 round 37, predicted reward 0.759149, predicted upper bound 0.770074, actual reward1.832194 round 38, predicted reward 1.029710, predicted upper bound 1.040862, actual reward0.805005 round 39, predicted reward 1.251582, predicted upper bound 1.260370, actual reward1.802072 round 40, predicted reward 0.688033, predicted upper bound 0.701778, actual reward1.214210 round 41, predicted reward 1.014587, predicted upper bound 1.024450, actual reward-0.445522 round 42, predicted reward 0.791284, predicted upper bound 0.803736, actual reward0.657000 round 43, predicted reward 1.055941, predicted upper bound 1.065663, actual reward0.939589 round 44, predicted reward 0.729106, predicted upper bound 0.742272, actual reward0.658019 round 45, predicted reward 0.383343, predicted upper bound 0.403322, actual reward0.924442 round 46, predicted reward 1.073350, predicted upper bound 1.082610, actual reward1.287910 round 47, predicted reward 1.051787, predicted upper bound 1.060078, actual reward0.485091 round 48, predicted reward 1.265421, predicted upper bound 1.279897, actual reward1.047104 round 49, predicted reward 1.084986, predicted upper bound 1.091933, actual reward2.123704 round 50, predicted reward 0.876523, predicted upper bound 0.886180, actual reward-0.025674 round 51, predicted reward 1.229329, predicted upper bound 1.243771, actual reward1.423720 round 52, predicted reward 0.492564, predicted upper bound 0.508513, actual reward0.822949 round 53, predicted reward 0.924992, predicted upper bound 0.933414, actual reward-0.581617 round 54, predicted reward 1.301908, predicted upper bound 1.311082, actual reward1.544164 round 55, predicted reward 0.890817, predicted upper bound 0.899964, actual reward1.086808 round 56, predicted reward 0.752403, predicted upper bound 0.764056, actual reward0.326341 round 57, predicted reward 1.402462, predicted upper bound 1.411922, actual reward1.975315 round 58, predicted reward 0.964382, predicted upper bound 0.974079, actual reward1.409764 round 59, predicted reward 0.690136, predicted upper bound 0.698323, actual reward0.360301 round 60, predicted reward 1.255878, predicted upper bound 1.270911, actual reward1.927858 round 61, predicted reward 1.412268, predicted upper bound 1.421108, actual reward1.417952 round 62, predicted reward 0.931399, predicted upper bound 0.941860, actual reward0.604083 round 63, predicted reward 1.266366, predicted upper bound 1.276277, actual reward1.276250 round 64, predicted reward 0.919050, predicted upper bound 0.948325, actual reward1.783952 round 65, predicted reward 1.418305, predicted upper bound 1.425967, actual reward0.098886 round 66, predicted reward 1.158272, predicted upper bound 1.166320, actual reward0.272244 round 67, predicted reward 0.690655, predicted upper bound 0.711684, actual reward-0.158905 round 68, predicted reward 0.483797, predicted upper bound 0.494244, actual reward1.397000 round 69, predicted reward 0.603170, predicted upper bound 0.633071, actual reward0.938655 round 70, predicted reward 1.001356, predicted upper bound 1.009557, actual reward-0.160535 round 71, predicted reward 1.402945, predicted upper bound 1.426201, actual reward2.354198 round 72, predicted reward 0.474606, predicted upper bound 0.485840, actual reward2.270110 round 73, predicted reward 0.624751, predicted upper bound 0.635042, actual reward0.276979 round 74, predicted reward 1.284081, predicted upper bound 1.294900, actual reward0.914317 round 75, predicted reward 1.527126, predicted upper bound 1.536955, actual reward1.243799 round 76, predicted reward 1.427915, predicted upper bound 1.441402, actual reward3.202854 round 77, predicted reward 0.665389, predicted upper bound 0.685482, actual reward2.574900 round 78, predicted reward 1.112521, predicted upper bound 1.121283, actual reward1.642484 round 79, predicted reward 0.397173, predicted upper bound 0.406823, actual reward0.404134 round 80, predicted reward 1.215799, predicted upper bound 1.239467, actual reward0.852867 round 81, predicted reward 0.714865, predicted upper bound 0.724042, actual reward2.350419 round 82, predicted reward 0.387147, predicted upper bound 0.403358, actual reward0.107181 round 83, predicted reward 1.337601, predicted upper bound 1.345103, actual reward-0.036781 round 84, predicted reward 1.699848, predicted upper bound 1.710142, actual reward0.361713 round 85, predicted reward 1.638043, predicted upper bound 1.645842, actual reward1.355636 round 86, predicted reward 0.531219, predicted upper bound 0.542413, actual reward-0.570691 round 87, predicted reward 0.526051, predicted upper bound 0.543833, actual reward0.040482 round 88, predicted reward 2.052348, predicted upper bound 2.060005, actual reward3.109648 round 89, predicted reward 1.538383, predicted upper bound 1.544247, actual reward0.032526 round 90, predicted reward 1.647936, predicted upper bound 1.653114, actual reward1.561023 round 91, predicted reward 1.463811, predicted upper bound 1.468371, actual reward0.730551 round 92, predicted reward 0.569166, predicted upper bound 0.585575, actual reward-0.606856 round 93, predicted reward 0.404037, predicted upper bound 0.415614, actual reward-0.218457 round 94, predicted reward 0.937470, predicted upper bound 0.949118, actual reward1.422678 round 95, predicted reward 1.599067, predicted upper bound 1.605454, actual reward0.572199 round 96, predicted reward 1.302039, predicted upper bound 1.314894, actual reward2.442352 round 97, predicted reward 1.315582, predicted upper bound 1.325291, actual reward1.104891 round 98, predicted reward 1.823110, predicted upper bound 1.831120, actual reward0.521556 round 99, predicted reward 0.701061, predicted upper bound 0.721147, actual reward1.124101 round 100, predicted reward 0.889067, predicted upper bound 0.901706, actual reward1.802893 ```python print(np.sum(reward)) ``` 93.85659335284052 ```python # benchmark np.random.seed(12345) reward = np.zeros(T) X_history = np.zeros((d, T)) params_history = {} grad_history = {} for tt in range(1, T + 1): # observe \{x_{t,a}\}_{a=1}^{k=1} context_list = SampleContext(d, K) # compute the upper bound of reward predict_reward = np.zeros(K) for a in range(1, K + 1): predict_reward[a - 1] = context_list[:, a - 1].transpose().dot(A.transpose().dot(A)).dot(context_list[:, a - 1]) ind = np.argmax(predict_reward, axis=None) # ind is the index of action we would play # play ind and observe reward X_history[:, tt - 1] = context_list[:, ind] reward[tt - 1] = GetRealReward(context_list[:, ind], A) print("round {:d}, predicted reward {:4f},\ actual reward{:4f}".format(tt, predict_reward[ind], reward[tt - 1])) assert(np.abs(predict_reward[ind]) <= 50) ``` ```python print(np.sum(reward)) ``` ```python # code for reference import h5py import numpy as np import argparse def sigmoid(x): """ define scale function """ return np.exp(x)/(1.0+np.exp(x)) def RELU(x): return np.np.maximum(x,0) def reluDerivative(x): return np.array([reluDerivativeSingleElement(xi) for xi in x]) def reluDerivativeSingleElement(xi): if xi > 0: return 1 elif xi <= 0: return 0 def compute_loss(Y,V): L_sum = np.sum(np.multiply(Y, np.log(V))) m = Y.shape[1] L = -(1./m) * L_sum return L def feed_forward(X, params): tempt={} tempt["Z"]=np.matmul(params["W"], X) + params["b1"] tempt["H"]=sigmoid(tempt["Z"]) #tempt["H"]=RELU(tempt["Z"]) tempt["U"]=np.matmul(params["C"], tempt["H"]) + params["b2"] tempt["V"]=np.exp(tempt["U"]) / np.sum(np.exp(tempt["U"]), axis=0) return tempt def back_propagate(X, Y, params, tempt, m_batch): dU=tempt["V"]-Y dC=(1. / m_batch) * np.matmul(dU, tempt["H"].T) db2=(1. / m_batch) * np.sum(dU, axis=1, keepdims=True) dH=np.matmul(params["C"].T, dU) dZ = dH * sigmoid(tempt["Z"]) * (1 - sigmoid(tempt["Z"])) #dZ=dH*reluDerivative(tempt["Z"]) dW = (1. / m_batch) * np.matmul(dZ, X.T) db1 = (1. / m_batch) * np.sum(dZ, axis=1, keepdims=True) grads={"dW":dW, "db1":db1, "dC":dC, "db2":db2} return grads #hyperparameters epochs=10 batch_size=1 batchs=np.int32(60000/batch_size) LR=0.01 dh=100#number of hidden nodes #getting 60000 samples of training data and 10000 samples of testing data f=h5py.File('MNISTdata.hdf5','r') x_test_set=np.float32(f['x_test'][:]) y_test_set=np.int32(np.array(f['y_test'][:,0])).reshape(-1,1) x_train_set=np.float32(f['x_train'][:]) y_train_set=np.int32(np.array(f['y_train'][:,0])).reshape(-1,1) f.close() X=np.vstack((x_train_set,x_test_set)) Y=np.vstack((y_train_set,y_test_set)) num_samples=Y.shape[0] Y=Y.reshape(1,num_samples) Y_new = np.eye(10)[Y.astype('int32')] Y_new = Y_new.T.reshape(10, num_samples) X_train, X_test=X[:60000].T, X[60000:].T Y_train, Y_test=Y_new[:,:60000], Y_new[:,60000:] #building fully connected neural network with one hidden layer #initialization of parameters params={"b1":np.zeros((dh,1)), "W":np.random.randn(dh,784)*np.sqrt(1. / 784), "b2":np.zeros((10,1)), "C":np.random.randn(10,dh)*np.sqrt(1. / dh)} #training the network for num_epoches in range(epochs): if (num_epoches > 5): LR = 0.001 if (num_epoches > 10): LR = 0.0001 if (num_epoches > 15): LR = 0.00001 #shuffle the training data shuffle_index=np.random.permutation(X_train.shape[1]) X_train= X_train[:, shuffle_index] Y_train=Y_train[:, shuffle_index] for num_batch in range(batchs): left_index=num_batch*batch_size right_index=min(left_index+batch_size,x_train_set.shape[0]-1) m_batch=right_index-left_index X=X_train[:,left_index:right_index] Y=Y_train[:,left_index:right_index] tempt=feed_forward(X, params) grads = back_propagate(X, Y, params, tempt, 1) #gradient descent params["W"] = params["W"] - LR * grads["dW"] params["b1"] = params["b1"] - LR * grads["db1"] params["C"] = params["C"] - LR * grads["dC"] params["b2"] = params["b2"] - LR * grads["db2"] #compute loss on training data tempt = feed_forward(X_train, params) train_loss = compute_loss(Y_train, tempt["V"]) #compute loss on test set tempt=feed_forward(X_test, params) test_loss = compute_loss(Y_test, tempt["V"]) total_correct=0 for n in range(Y_test.shape[1]): p = tempt["V"][:,n] prediction = np.argmax(p) if prediction == np.argmax(Y_test[:,n]): total_correct+=1 accuracy = np.float32(total_correct) / (Y_test.shape[1]) #print(params) print("Epoch {}: training loss = {}, test loss = {}, accuracy={}".format( num_epoches + 1, train_loss, test_loss, accuracy)) ```
```python import numpy as np import ipyvolume as ipv import sympy as sy from sympy.geometry import Plane as syPlane, Point3D as syPoint3D import tqdm ``` ```python xyz = np.array((2 * np.random.random(1000) - 1, 2 * np.random.random(1000) - 1, 2 * np.random.random(1000) - 1)) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') ipv.show() ``` Now, similarly to the [req2.1 notebook](req2.1_filter_plane.ipynb), we will want to filter and plot here a thick cone, i.e. basically two the same cones where their surfaces are separatated by some thickness. The equation for a generically oriented and located regular (non-slanted) cone is given on [Wikipedia](https://en.wikipedia.org/wiki/Cone) as $F(u)=0$ where: $$ F(u) = u \cdot d - |d| |u| \cos \theta $$ where $u=(x,y,z)$, $d=(d,e,f)$ is the vector to which the cone axis is parallel and the aperture is $2\theta$. The vertex of this cone is at the origin, so to displace it to $(a,b,c)$ you need to subtract an additional vector $o = (a,b,c)$ from u: $$ F(u) = (u - o) \cdot d - |d| |u - o| \cos \theta $$ Alternatively, one can apparently use the equation $$ F(u) = ((u - o) \cdot d)^2 - (d \cdot d) ((u - o) \cdot (u - o)) (\cos \theta)^2 $$ This is actually easier, because you can skip the square roots necessary for the norms. ```python x, y, z, d, e, f, a, b, c, theta = sy.symbols('x, y, z, d, e, f, a, b, c, theta') ``` ```python cone_eqn = ((x-a)*d + (y-b)*e + (z-c)*f)**2 \ - sy.cos(theta)**2 * (d * d + e * e + f * f) \ * ((x-a) * (x-a) + (y-b) * (y-b) + (z-c) * (z-c)) ``` To solve, we need to fill out the parameters we want. Let's try some simple things first. ```python res = sy.solve(cone_eqn.subs(theta, sy.pi/4).subs(a, 0).subs(b, 0).subs(c, 0).subs(d, 0).subs(e, 1).subs(f, 0), y) ``` ```python value = res[0].subs(x, 0.1).subs(z, 0.1) ``` ```python float(value) ``` ```python res0 = res[0] ``` ```python cone_eqn.subs ``` Ok, that seems reasonable actually! ```python def plot_cone(res, x_sy, z_sy): """ Draw a cone. """ # get box limits in two dimensions x_lim = ipv.pylab.gcf().xlim z_lim = ipv.pylab.gcf().zlim x_steps = np.linspace(*x_lim, 10) z_steps = np.linspace(*z_lim, 10) x, z = np.meshgrid(x_steps, z_steps) # find corresponding y coordinates y1, y2 = [], [] for xi, zi in zip(x.flatten(), z.flatten()): y1.append(float(res[0].evalf(subs={x_sy: xi, z_sy: zi}))) y2.append(float(res[1].evalf(subs={x_sy: xi, z_sy: zi}))) # plot ipv.plot_surface(x, np.array(y1), z) ipv.plot_surface(x, np.array(y2), z) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone(res, x, z) ipv.show() ``` Nice! Could be better though. - The origin point must be included. - It looks a bit odd that the edges are cut off. It makes sense if you want to fill the whole box, but probably most people will prefer a circular ending. This we could add as an option. - Just pick one of the two solutions, probably the one that is actually in the same direction as the $d$ vector. Let's also try to make it a bit more general and try out some different examples to test other corner cases. ```python def plot_cone_2(axis, origin, half_aperture): """ Draw a cone. axis: three-component vector along which the cone axis lies origin: location of the apex of the cone half_aperture: the aperture of the cone is 2*half_aperture """ x, y, z, d, e, f, a, b, c, theta = sy.symbols('x, y, z, d, e, f, a, b, c, theta') cone_eqn = ((x-a)*d + (y-b)*e + (z-c)*f)**2 \ - sy.cos(theta)**2 * (d * d + e * e + f * f) \ * ((x-a) * (x-a) + (y-b) * (y-b) + (z-c) * (z-c)) res = sy.solve(cone_eqn.subs({d: axis[0], e: axis[1], f: axis[2], a: origin[0], b: origin[1], c: origin[2], theta: half_aperture}), y) # print(res) # get box limits in two dimensions x_lim = ipv.pylab.gcf().xlim z_lim = ipv.pylab.gcf().zlim x_steps = np.linspace(*x_lim, 20) z_steps = np.linspace(*z_lim, 20) x_array, z_array = np.meshgrid(x_steps, z_steps) y_lim = ipv.pylab.gcf().ylim # find corresponding y coordinates y1, y2 = [], [] for xi, zi in zip(x_array.flatten(), z_array.flatten()): y1.append(float(res[0].evalf(subs={x: xi, z: zi}))) y2.append(float(res[1].evalf(subs={x: xi, z: zi}))) # plot ipv.plot_surface(x_array, np.array(y1), z_array) ipv.plot_surface(x_array, np.array(y2), z_array) ipv.ylim(*y_lim) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_2((0, 1, 0), (0, 0, 0), sy.pi/4) ipv.show() ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_2((0.25, 0.5, 0), (0, 0.5, 0), sy.pi/8) ipv.show() ``` Arrgh, what's going on here? Oh, wait, this must be what happens when the x and z parameters are, in fact, outside of where the cone is going to be. Is there a more reliable way to find points x, y, z that are actually on the cone surface instead of just randomly (or rather grid-wise) probing x and z and hoping there's a y point there? The trick is to find a parametric form, I think. Wikipedia has this form for a cone along the z-axis, so we could use that, but then we'd still have to displace it and rotate it. Maybe we can find our own parametric form though. One dimension that we would probably want is the same as the $u$ one of the Wikipedia parameterization, i.e. a coordinate that runs along the length of the axis up to its height $h$, i.e. $u \in [0,h]$. I think this means it should be that $$ u^2 = x^2 + y^2 + z^2 $$ so that $u$ is the square-root of the sum of the three components. This indeed makes sense, because it has two solutions, a positive and a negative one, which technically the cone equations indeed must have. However, we only use the positive range. The remaining two parameters $s$ and $t$ must describe the remaining two ```python ... ``` Ok... this is going to be too much work, and won't generalize nicely to other surfaces anyway. Let's try the easier approach of just rotating the simple parametric form. This will also automatically fix all three "niceness" issues mentioned above. Wikipedia's parametric description for a cone along the z-axis: $$ F(s,t,u) = \left(u \tan s \cos t, u \tan s \sin t, u \right) $$ where $s,t,u$ range over $[0,\theta)$, $[0,2\pi)$, and $[0,h]$, respectively. Actually, Wolfram Mathworld has a simpler parameterization with only two parameters: $$ x = \frac{h-u}{h} r \cos\theta \\ y = \frac{h-u}{h} r \sin\theta \\ z = u $$ for $u$ in $[0,h]$ and $\theta$ in $[0,2\pi)$. ```python def plot_cone_3(height, radius, N_steps=20): """ Draw a cone. height: height along the z-axis radius: radius of the circle """ h, r, u, theta = sy.symbols('h, r, u, theta') x_eqn = (h - u) / h * r * sy.cos(theta) y_eqn = (h - u) / h * r * sy.sin(theta) z_eqn = u # get box limits in two dimensions # x_lim = ipv.pylab.gcf().xlim # z_lim = ipv.pylab.gcf().zlim # x_steps = np.linspace(*x_lim, 20) # z_steps = np.linspace(*z_lim, 20) # x_array, z_array = np.meshgrid(x_steps, z_steps) u_steps = np.linspace(0, height, N_steps) theta_steps = np.linspace(0, 2 * np.pi, N_steps) u_array, theta_array = np.meshgrid(u_steps, theta_steps) y_lim = ipv.pylab.gcf().ylim # find corresponding y coordinates x, y, z = [], [], [] for ui, thetai in zip(u_array.flatten(), theta_array.flatten()): x.append(float(x_eqn.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) y.append(float(y_eqn.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) z.append(float(z_eqn.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) # plot ipv.plot_surface(np.array(x).reshape(u_array.shape), np.array(y).reshape(u_array.shape), np.array(z).reshape(u_array.shape)) # ipv.ylim(*y_lim) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_3(0.5, 0.5) ipv.show() ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_3(1, 0.5) ipv.show() ``` ```python def plot_cone_4(height, radius, rot_x=2*np.pi, rot_y=2*np.pi, N_steps=20): """ Draw a cone. height: height along the z-axis radius: radius of the circle rot_y: rotation angle about the y axis (radians) rot_z: rotation angle about the z axis (radians) N_steps: number of steps in the parametric range used for drawing """ h, r, u, theta = sy.symbols('h, r, u, theta') x_eqn = (h - u) / h * r * sy.cos(theta) y_eqn = (h - u) / h * r * sy.sin(theta) z_eqn = u x_rot_x = x_eqn y_rot_x = y_eqn * sy.cos(rot_x) + z_eqn * sy.sin(rot_x) z_rot_x = - y_eqn * sy.sin(rot_x) + z_eqn * sy.cos(rot_x) x_rot_y = x_rot_x * sy.cos(rot_y) + z_rot_x * sy.sin(rot_y) y_rot_y = y_rot_x z_rot_y = - x_rot_x * sy.sin(rot_y) + z_rot_x * sy.cos(rot_y) # get box limits in two dimensions # x_lim = ipv.pylab.gcf().xlim # z_lim = ipv.pylab.gcf().zlim # x_steps = np.linspace(*x_lim, 20) # z_steps = np.linspace(*z_lim, 20) # x_array, z_array = np.meshgrid(x_steps, z_steps) u_steps = np.linspace(0, height, N_steps) theta_steps = np.linspace(0, 2 * np.pi, N_steps) u_array, theta_array = np.meshgrid(u_steps, theta_steps) y_lim = ipv.pylab.gcf().ylim # find corresponding y coordinates x, y, z = [], [], [] for ui, thetai in zip(u_array.flatten(), theta_array.flatten()): x.append(float(x_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) y.append(float(y_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) z.append(float(z_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) # plot ipv.plot_surface(np.array(x).reshape(u_array.shape), np.array(y).reshape(u_array.shape), np.array(z).reshape(u_array.shape)) # ipv.ylim(*y_lim) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_4(1, 0.5, rot_y=np.pi/4)#, rot_z=np.pi/2) ipv.show() ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_4(1, 0.5, rot_x=np.pi/9)#, rot_z=np.pi/2) ipv.show() ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_4(1, 0.5, rot_x=np.pi/9, rot_y=np.pi/4)#, rot_z=np.pi/2) ipv.show() ``` Ok, this we can work with, it rotates as expected. Probably, we should also add a version with a direction vector, but this will do for now. And we need a version in which you specify two positions: the base center and the apex position. Now just add a translation vector. ```python def plot_cone_5(height, radius, rot_x=2*np.pi, rot_y=2*np.pi, base_pos=(0, 0, 0), N_steps=20, **kwargs): """ Draw a cone. height: height along the z-axis radius: radius of the circle rot_y: rotation angle about the y axis (radians) rot_z: rotation angle about the z axis (radians) base_pos: translation of base of cone to this position, iterable of three numbers N_steps: number of steps in the parametric range used for drawing """ h, r, u, theta = sy.symbols('h, r, u, theta') x_eqn = (h - u) / h * r * sy.cos(theta) y_eqn = (h - u) / h * r * sy.sin(theta) z_eqn = u x_rot_x = x_eqn y_rot_x = y_eqn * sy.cos(rot_x) - z_eqn * sy.sin(rot_x) z_rot_x = y_eqn * sy.sin(rot_x) + z_eqn * sy.cos(rot_x) x_rot_y = x_rot_x * sy.cos(rot_y) - z_rot_x * sy.sin(rot_y) + base_pos[0] y_rot_y = y_rot_x + base_pos[1] z_rot_y = x_rot_x * sy.sin(rot_y) + z_rot_x * sy.cos(rot_y) + base_pos[2] # get box limits in two dimensions u_steps = np.linspace(0, height, N_steps) theta_steps = np.linspace(0, 2 * np.pi, N_steps) u_array, theta_array = np.meshgrid(u_steps, theta_steps) y_lim = ipv.pylab.gcf().ylim # find corresponding y coordinates x, y, z = [], [], [] for ui, thetai in zip(u_array.flatten(), theta_array.flatten()): x.append(float(x_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) y.append(float(y_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) z.append(float(z_rot_y.evalf(subs={h: height, r: radius, u: ui, theta: thetai}))) # plot ipv.plot_surface(np.array(x).reshape(u_array.shape), np.array(y).reshape(u_array.shape), np.array(z).reshape(u_array.shape), **kwargs) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_cone_5(0.5, 0.5, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0))#, rot_z=np.pi/2) ipv.show() ``` Ok, that's it, now a thick cone... ```python plot_cone = plot_cone_5 ``` ```python def cone_axis_from_rotation(rot_x, rot_y): # z-unit vector (0, 0, 1) rotated twice cone_axis = (0, -np.sin(rot_x), np.cos(rot_x)) # rotation around x-axis cone_axis = np.array((-np.sin(rot_y) * cone_axis[2], cone_axis[1], np.cos(rot_y) * cone_axis[2])) # around y return cone_axis ``` ```python def thick_cone_base_positions(height, radius, thickness, rot_x, rot_y, base_pos): thickness = abs(thickness) base_distance = thickness / radius * height * np.sqrt(1 + radius**2 / height**2) # trigonometry cone_axis = cone_axis_from_rotation(rot_x, rot_y) base_pos_1 = np.array(base_pos) - cone_axis * 0.5 * base_distance base_pos_2 = np.array(base_pos) + cone_axis * 0.5 * base_distance return base_pos_1, base_pos_2 ``` ```python def plot_thick_cone(height, radius, thickness, rot_x=2*np.pi, rot_y=2*np.pi, base_pos=(0, 0, 0), **kwargs): """ Plot two cones separated by a distance `thickness`. Parameters: same as plot_cone, plus `thickness`. """ base_pos_1, base_pos_2 = thick_cone_base_positions(height, radius, thickness, rot_x, rot_y, base_pos) plot_cone(height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_1, **kwargs) kwargs.pop('color', None) plot_cone(height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_2, color='blue', **kwargs) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_thick_cone(0.5, 0.5, 0.2, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0)) ipv.show() ``` Nice! # Filtering This is going to be a bit more difficult. We need a closest distance of each point to both surfaces. How to do this? Maybe we can try using Sympy to solve the system of equations describing the minimum distance of a point $P=(p_1, p_2, p_3)$ to a cone surface, like e.g. here: https://math.stackexchange.com/a/880971/258876 ```python h, r, u, theta, p1, p2, p3 = sy.symbols('h, r, u, theta, p1, p2, p3') x_eqn = (h - u) / h * r * sy.cos(theta) y_eqn = (h - u) / h * r * sy.sin(theta) z_eqn = u distance_eqn = (x_eqn - p1)**2 + (y_eqn - p2)**2 + (z_eqn - p3)**2 system = [sy.Derivative(distance_eqn, u), sy.Derivative(distance_eqn, theta)] res = sy.solve(system, distance_eqn, subs={h: 0.5, r: 0.5, p1: 0, p2: 0, p3: 0}) ``` ```python res ``` Not sure how to fix this. Another possibility may be to first filter by looking whether the angle of the vector from apex to $P$ with the vector along the cone axis is larger than $90^\circ + \theta/2$ where $\theta$ is the opening angle. ```python def cone_apex_position(height, rot_x=2*np.pi, rot_y=2*np.pi, base_pos=(0, 0, 0)): cone_axis = cone_axis_from_rotation(rot_x, rot_y) return np.array(base_pos) + cone_axis * height ``` ```python def cone_opening_angle(height, radius): """ Twice the opening angle is the maximum angle between directrices """ return np.arctan(radius / height) ``` ```python def angle_between_two_vectors(a, b): return np.arccos(np.sum(a * b) / np.sqrt(np.sum(a**2)) / np.sqrt(np.sum(b**2))) ``` ```python def point_distance_to_cone(P, height, radius, rot_x=2*np.pi, rot_y=2*np.pi, base_pos=(0, 0, 0), return_extra=False): """ Check whether for a point P, the shortest path to the cone is perpendicular to the cone surface (and if so, return it). If not, it is either "above" the apex and the shortest path is simply the line straight to the apex, or it is "below" the base, and the shortest path is the shortest path to the directrix (the base circle). This function returns a second value depending on which of the three above cases is true for point P. If we're using the perpendicular, it is True, if we're above the apex it is False and if it is below the base, it is None. Extra values can be returned to be reused outside the function by setting return_extra to True. """ cone_axis = cone_axis_from_rotation(rot_x, rot_y) apex_pos = cone_apex_position(height, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos) point_apex_vec = np.array(P) - apex_pos point_apex_angle = np.pi - angle_between_two_vectors(cone_axis, point_apex_vec) opening_angle = cone_opening_angle(height, radius) # for the second conditional, we need the length of the component of the # difference vector between P and apex along the closest generatrix point_apex_generatrix_angle = point_apex_angle - opening_angle point_apex_distance = np.sqrt(np.sum(point_apex_vec**2)) point_apex_generatrix_component = point_apex_distance * np.cos(point_apex_generatrix_angle) generatrix_length = np.sqrt(radius**2 + height**2) returnees = {} if return_extra: returnees['opening_angle'] = opening_angle returnees['point_apex_angle'] = point_apex_angle if point_apex_angle > opening_angle + np.pi / 2: # "above" the apex return point_apex_distance, False, returnees elif point_apex_generatrix_component > generatrix_length: # "below" the directrix # use cosine rule to find length of third side return np.sqrt(point_apex_distance**2 + generatrix_length**2 - 2 * point_apex_distance * generatrix_length * np.cos(point_apex_generatrix_angle)), None, returnees else: # "perpendicular" to a generatrix return point_apex_distance * np.sin(point_apex_generatrix_angle), True, returnees ``` Ok, that should do as well, an all-in-one distance function, a bit complicated, but I see no way around that. ```python def filter_points_cone(points_xyz, height, radius, thickness, rot_x=2*np.pi, rot_y=2*np.pi, base_pos=(0, 0, 0), verbose=False): base_pos_1, base_pos_2 = thick_cone_base_positions(height, radius, thickness, rot_x, rot_y, base_pos) p_filtered = [] for ix, p_i in tqdm.tqdm(enumerate(points_xyz.T)): d_cone1, flag_cone1, vals1 = point_distance_to_cone(p_i, height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_1, return_extra=True) d_cone2, flag_cone2, _ = point_distance_to_cone(p_i, height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_2, return_extra=True) if flag_cone2 is False or flag_cone1 is None: # it is definitely outside of the cones' range pass if verbose: print(f"case 1: {p_i} was ignored") elif flag_cone1 is False: # the first condition is logically enclosed in the second, but the # first is faster and already covers a large part of the cases/volume: if d_cone1 <= thickness or \ d_cone1 <= thickness / np.cos(vals1['point_apex_angle'] - vals1['opening_angle'] - np.pi/2): p_filtered.append(p_i) if verbose: print(f"case 2: {p_i} was added") else: pass if verbose: print(f"case 3: {p_i} was ignored") elif d_cone1 <= thickness and d_cone2 <= thickness: p_filtered.append(p_i) if verbose: print(f"case 4: {p_i} was added") return p_filtered ``` ```python p_filtered = filter_points_cone(xyz, 0.5, 0.5, 0.2, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0)) ``` ```python len(p_filtered) ``` ```python ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_thick_cone(0.5, 0.5, 0.2, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0)) ipv.scatter(*np.array(p_filtered).T, marker='circle_2d', color='blue') ipv.show() ``` First try: That makes no sense... Second try (modified code, added `np.pi - ` in `point_distance_to_cone`): ok, better, at least the points are now in one of the cones, but there are still some weird things; false negatives (between the cones) and false positives (in the red cone). Third try (modified code, was using opening angle as if it was twice what it is, so now without divisions by 2): awesome! ## Debugging For debugging, I used some simple points like these: ```python _xyz = np.array([[0, 0, 0.5], # inside blue, above red [0, 0, 0.7], # above blue (i.e. above both), within "thickness" from blue [0, 0, 1], # far above both [0, 0, 0.3], # inside red [0, 0, 0.1], # inside red, "below" blue [0, 0, -0.1], # below both ]).T ipv.clear() ipv.scatter(*_xyz, color="black") p_filtered = filter_points_cone(_xyz, 0.5, 0.5, 0.2, verbose=True) plot_thick_cone(0.5, 0.5, 0.2) ipv.scatter(*np.array(p_filtered).T, color='green') ipv.show() ``` ~~Ok, so the ones above are correct and the one inside is correct, but the ones inside the red cone are wrong. Let's go through the wrong cases one by one.~~ ~~Why is `[0, 0, 0.3]` added? It's in case 4, so `d_cone1 <= thickness and d_cone2 <= thickness` is True. What are the values?~~ Before, the ones in the red cone were also added, which is what I'm debugging below (but makes no sense anymore now, i.e. now it makes sense, because it's no longer wrong). ```python import ectopylasm.geometry ``` ```python ectopylasm.geometry.filter_points_cone(_xyz, 0.5, 0.5, 0.2) ``` ```python filter_points_cone(_xyz, 0.5, 0.5, 0.2) ``` Arrgh ```python p_filtered = ectopylasm.geometry.filter_points_cone(xyz, 0.5, 0.5, 0.2, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0)) ipv.clear() ipv.scatter(*xyz, marker='circle_2d') plot_thick_cone(0.5, 0.5, 0.2, rot_x=np.pi/9, rot_y=np.pi/4, base_pos=(0, 0.5, 0)) ipv.scatter(*np.array(p_filtered).T, marker='circle_2d', color='blue') ipv.show() ``` ```python height = 0.5 radius = 0.5 thickness = 0.2 rot_x = 0 rot_y = 0 base_pos = (0, 0, 0) p_i = [0, 0, 0.3] base_pos_1, base_pos_2 = thick_cone_base_positions(height, radius, thickness, rot_x, rot_y, base_pos) d_cone1, flag_cone1, vals1 = point_distance_to_cone(p_i, height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_1, return_extra=True) d_cone2, flag_cone2, _ = point_distance_to_cone(p_i, height, radius, rot_x=rot_x, rot_y=rot_y, base_pos=base_pos_2, return_extra=True) ``` ```python d_cone1, d_cone2 ``` ```python ```
#include <boost/concept_check/general.hpp>
module Fibonacci fibpair: Nat -> (Nat, Nat) fibpair Z = (1, 1) fibpair (S k) = case (fibpair k) of (a, b) => (b, a + b) append : List a -> a -> List a append [] x = x :: [] append (y :: xs) x = y :: (append xs x) fiblist: Nat -> List (Nat) fiblist Z = [] fiblist (S k) = case (fibpair k) of (a, b) => append (fiblist k) a tuple: Nat -> Type tuple Z = Unit tuple (S k) = (Nat, tuple k) fibtup: (n: Nat) -> tuple n fibtup Z = () fibtup (S k) = case (fibpair k) of (a, b) => (a, fibtup k) apptup: (n: Nat) -> tuple n -> Nat -> tuple (succ n) apptup Z () k = (k, ()) apptup (S j) (a, b) k = (a, tail) where tail = apptup j b k rev: (n: Nat) -> tuple n -> tuple n rev Z () = () rev (S k) (a, b) = apptup k (rev k b) a revv: {n: Nat} -> tuple n -> tuple n revv {n = Z} () = () revv {n = (S k)} (a, b) = apptup k (revv b) a total ack : Nat -> Nat -> Nat ack Z n = n + 1 ack (S k) Z = ack k 1 ack (S k) (S j) = ack k (ack (S k) j) rec : (a : Type) -> a -> (Nat -> a -> a) -> (Nat -> a) rec a x f Z = x rec a x f (S k) = f k (rec a x f k) base : Nat -> Nat base k = k + 1 s : (m : Nat) -> (ackm : Nat -> Nat) -> Nat -> Nat -> Nat s m ackm k j = ackm j step : Nat -> (Nat -> Nat) -> Nat -> Nat step m ackm = rec Nat (ackm 1)(s m ackm) ackrec : Nat -> Nat -> Nat ackrec = rec (Nat -> Nat) base step
If $S$ is contractible and homeomorphic to $T$, then $T$ is contractible.
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field.basic import algebra.ring.opposite import algebra.big_operators.basic /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations * ``infix ` ≃+* `:25 := ring_equiv`` The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ open_locale big_operators variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) (λ _, R → S) := ⟨ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := e.map_mul' x y /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := e.map_add' x y /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) : ⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl @[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) : (⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl protected lemma congr_arg {f : R ≃+* S} : Π {x x' : R}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := h ▸ rfl lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[simp] lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl @[simp] lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl @[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl @[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl /-- The `ring_equiv` between two semirings with a unique element. -/ def ring_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N := { ..add_equiv.add_equiv_of_unique_of_unique, ..mul_equiv.mul_equiv_of_unique_of_unique} instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : unique (M ≃+* N) := { default := ring_equiv_of_unique_of_unique, uniq := λ _, ext $ λ x, subsingleton.elim _ _ } variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- See Note [custom simps projection] -/ def simps.symm_apply (e : R ≃+* S) : S → R := e.symm initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) := equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) : (ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) : (mk f g h₁ h₂ h₃ h₄).symm = { to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply (e₁ : R ≃+* S) (e₂ : S ≃+* S') (a : R) : e₁.trans e₂ a = e₂ (e₁ a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section opposite open mul_opposite /-- A ring iso `α ≃+* β` can equivalently be viewed as a ring iso `αᵐᵒᵖ ≃+* βᵐᵒᵖ`. -/ @[simps] protected def op {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] : (α ≃+* β) ≃ (αᵐᵒᵖ ≃+* βᵐᵒᵖ) := { to_fun := λ f, { ..f.to_add_equiv.op, ..f.to_mul_equiv.op}, inv_fun := λ f, { ..(add_equiv.op.symm f.to_add_equiv), ..(mul_equiv.op.symm f.to_mul_equiv) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of a ring iso `αᵐᵒᵖ ≃+* βᵐᵒᵖ`. Inverse to `ring_equiv.op`. -/ @[simp] protected def unop {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] : (αᵐᵒᵖ ≃+* βᵐᵒᵖ) ≃ (α ≃+* β) := ring_equiv.op.symm section comm_semiring variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵐᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), .. mul_opposite.op_equiv } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵐᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring end opposite section non_unital_semiring variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff end non_unital_semiring section semiring variables [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } @[simp] lemma coe_of_bijective (f : R →+* S) (hf : function.bijective f) : (of_bijective f hf : R → S) = f := rfl lemma of_bijective_apply (f : R →+* S) (hf : function.bijective f) (x : R) : of_bijective f hf x = f x := rfl end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [non_assoc_semiring R] [non_assoc_semiring S] [non_assoc_semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) := λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h) instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [non_assoc_semiring R] [non_assoc_semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes (f : R ≃+* S) : (f : R →+* S).to_add_monoid_hom = (f : R ≃+ S).to_add_monoid_hom := rfl /-- The two paths coercion can take to an `monoid_hom` are equivalent -/ lemma to_monoid_hom_commutes (f : R ≃+* S) : (f : R →+* S).to_monoid_hom = (f : R ≃* S).to_monoid_hom := rfl /-- The two paths coercion can take to an `equiv` are equivalent -/ lemma to_equiv_commutes (f : R ≃+* S) : (f : R ≃+ S).to_equiv = (f : R ≃* S).to_equiv := rfl @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl @[simp] lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) : e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ := by { ext, simp } @[simp] lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) : e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ := by { ext, simp } /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom section big_operators lemma map_list_prod [semiring R] [semiring S] (f : R ≃+* S) (l : list R) : f l.prod = (l.map f).prod := f.to_ring_hom.map_list_prod l lemma map_list_sum [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (l : list R) : f l.sum = (l.map f).sum := f.to_ring_hom.map_list_sum l /-- An isomorphism into the opposite ring acts on the product by acting on the reversed elements -/ lemma unop_map_list_prod [semiring R] [semiring S] (f : R ≃+* Sᵐᵒᵖ) (l : list R) : mul_opposite.unop (f l.prod) = (l.map (mul_opposite.unop ∘ f)).reverse.prod := f.to_ring_hom.unop_map_list_prod l lemma map_multiset_prod [comm_semiring R] [comm_semiring S] (f : R ≃+* S) (s : multiset R) : f s.prod = (s.map f).prod := f.to_ring_hom.map_multiset_prod s lemma map_multiset_sum [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (s : multiset R) : f s.sum = (s.map f).sum := f.to_ring_hom.map_multiset_sum s lemma map_prod {α : Type*} [comm_semiring R] [comm_semiring S] (g : R ≃+* S) (f : α → R) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_ring_hom.map_prod f s lemma map_sum {α : Type*} [non_assoc_semiring R] [non_assoc_semiring S] (g : R ≃+* S) (f : α → R) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_ring_hom.map_sum f s end big_operators section division_ring variables {K K' : Type*} [division_ring K] [division_ring K'] (g : K ≃+* K') (x y : K) lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_ring_hom.map_inv x lemma map_div : g (x / y) = g x / g y := g.to_ring_hom.map_div x y end division_ring section group_power variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R ≃+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_ring_hom.map_pow a end group_power end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem self_trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans_self (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is a domain, then so is the first. -/ protected lemma is_domain {A : Type*} (B : Type*) [ring A] [ring B] [is_domain B] (e : A ≃+* B) : is_domain A := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], by simpa using eq_zero_or_eq_zero_of_mul_eq_zero this, exists_pair_ne := ⟨e.symm 0, e.symm 1, e.symm.injective.ne zero_ne_one⟩ } end ring_equiv
[STATEMENT] lemma iD_addpreRT [simp]: fixes rt dip npre assumes "dip \<in> kD rt" shows "iD (the (addpreRT rt dip npre)) = iD rt" [PROOF STATE] proof (prove) goal (1 subgoal): 1. iD (the (addpreRT rt dip npre)) = iD rt [PROOF STEP] unfolding iD_def addpreRT_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. {dipa. flag (the (map_option (\<lambda>s. rt(dip \<mapsto> addpre s npre)) (rt dip))) dipa = Some Aodv_Basic.inv} = {dip. flag rt dip = Some Aodv_Basic.inv} [PROOF STEP] using assms [THEN kD_Some] [PROOF STATE] proof (prove) using this: \<exists>dsn dsk flag hops nhip pre. rt dip = Some (dsn, dsk, flag, hops, nhip, pre) goal (1 subgoal): 1. {dipa. flag (the (map_option (\<lambda>s. rt(dip \<mapsto> addpre s npre)) (rt dip))) dipa = Some Aodv_Basic.inv} = {dip. flag rt dip = Some Aodv_Basic.inv} [PROOF STEP] by clarsimp auto