text
stringlengths 0
3.34M
|
---|
theory Interpretation_in_nested_targets
imports Main
begin
locale injection =
fixes f :: \<open>'a \<Rightarrow> 'b\<close>
assumes eqI: \<open>f x = f y \<Longrightarrow> x = y\<close>
begin
lemma eq_iff:
\<open>x = y \<longleftrightarrow> f x = f y\<close>
by (auto intro: eqI)
lemma inv_apply:
\<open>inv f (f x) = x\<close>
by (rule inv_f_f) (simp add: eqI injI)
end
context
fixes f :: \<open>'a::linorder \<Rightarrow> 'b::linorder\<close>
assumes \<open>strict_mono f\<close>
begin
global_interpretation strict_mono: injection f
by standard (simp add: \<open>strict_mono f\<close> strict_mono_eq)
thm strict_mono.eq_iff
thm strict_mono.inv_apply
end
thm strict_mono.eq_iff
thm strict_mono.inv_apply
end
|
Require Export P02.
Lemma power_series_correct: forall (m: nat),
{{ True }}
X := 0;
Y := 1;
Z := 1;
while ~(X = m) do
Z := 2 * Z;
Y := Y + Z;
X := X + 1
end
{{ Y = power_series 2 m }}.
Proof.
exact FILL_IN_HERE.
Qed.
|
-- Andreas, 2013-06-15 reported by Guillaume Brunerie
-- {-# OPTIONS -v malonzo.definition:100 #-}
module Issue867 where
{- The program below gives the following error when trying to compile it (using MAlonzo)
$ agda -c Test.agda
Checking Test (/tmp/Test.agda).
Finished Test.
Compiling Test in /tmp/Test.agdai to /tmp/MAlonzo/Code/Test.hs
Calling: ghc -O -o /tmp/Test -Werror -i/tmp -main-is MAlonzo.Code.Test /tmp/MAlonzo/Code/Test.hs --make -fwarn-incomplete-patterns -fno-warn-overlapping-patterns
[1 of 2] Compiling MAlonzo.RTE ( MAlonzo/RTE.hs, MAlonzo/RTE.o )
[2 of 2] Compiling MAlonzo.Code.Test ( /tmp/MAlonzo/Code/Test.hs, /tmp/MAlonzo/Code/Test.o )
Compilation error:
/tmp/MAlonzo/Code/Test.hs:21:35:
Not in scope: `d5'
Perhaps you meant one of these:
`d1' (line 11), `d4' (line 26), `d9' (line 29)
-}
-- Here is the program
module Test where
data β : Set where
O : β
S : β β β
{-# BUILTIN NATURAL β #-}
postulate
IO : β {i} β Set i β Set i
return : β {i} {A : Set i} β A β IO A
{-# BUILTIN IO IO #-}
main : IO β
main = return (S 1)
{- Itβs the first time I try to compile an Agda program, so presumably Iβm doing something wrong. But even if Iβm doing something wrong, Agda should be the one giving the error, not ghc. -}
-- Should work now.
|
lemma complex_cnj_one [simp]: "cnj 1 = 1" |
------------------------------------------------------------------------
-- One form of induction for natural numbers
------------------------------------------------------------------------
-- I want universe polymorphism.
module Induction1.Nat where
open import Data.Nat
import Induction1.WellFounded as WF
------------------------------------------------------------------------
-- Complete induction based on <β²
open WF _<β²_ using (Acc; acc)
allAcc : β n β Acc n
allAcc n = acc (helper n)
where
helper : β n m β m <β² n β Acc m
helper zero _ ()
helper (suc n) .n β€β²-refl = acc (helper n)
helper (suc n) m (β€β²-step m<β²n) = helper n m m<β²n
open WF _<β²_ public using () renaming (WfRec to <-Rec)
open WF.All _<β²_ allAcc public
renaming ( wfRec-builder to <-rec-builder
; wfRec to <-rec
)
|
theory prop_09
imports Main
"$HIPSTER_HOME/IsaHipster"
begin
datatype Nat = Z | S "Nat"
fun plus :: "Nat => Nat => Nat" where
"plus (Z) y = y"
| "plus (S z) y = S (plus z y)"
fun minus :: "Nat => Nat => Nat" where
"minus (Z) y = Z"
| "minus (S z) (Z) = S z"
| "minus (S z) (S x2) = minus z x2"
(*hipster plus minus *)
theorem x0 :
"(minus (minus i j) k) = (minus i (plus j k))"
by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)
end
|
/*
* File: Random.h
* Author: nguyentran
*
* Created on May 27, 2013, 10:46 AM
*/
#ifndef RANDOM_H
#define RANDOM_H
#include <gsl/gsl_rng.h>
#include "PropertyMacro.h"
#include "Strategies/AdaptiveCyclingStrategy.h"
class Model;
class Random {
DISALLOW_COPY_AND_ASSIGN(Random)
DISALLOW_MOVE(Random)
VIRTUAL_PROPERTY(unsigned long, seed)
public:
gsl_rng *G_RNG;
explicit Random(gsl_rng *g_rng = nullptr);
virtual ~Random();
void initialize(const unsigned long &seed = 0);
void release() const;
virtual int random_poisson(const double &poisson_mean);
virtual unsigned long random_uniform(unsigned long range);
virtual unsigned long random_uniform_int(const unsigned long &from, const unsigned long &to);
virtual double random_uniform_double(const double &from, const double &to);
/*
* This function will return a random number in [0,1)
*/
virtual double random_uniform();
virtual double random_normal(const double &mean, const double &sd);
virtual double random_normal_truncated(const double &mean, const double &sd);
virtual int random_normal(const int &mean, const int &sd);
virtual int random_normal_truncated(const int &mean, const int &sd);
virtual double random_beta(const double &alpha, const double &beta);
virtual double random_gamma(const double &shape, const double &scale);
virtual double cdf_gamma_distribution(const double &x, const double &alpha, const double &beta);
virtual double cdf_gamma_distribution_inverse(const double &p, const double &alpha, const double &beta);
virtual double random_flat(const double &from, const double &to);
virtual void random_multinomial(const size_t &K, const unsigned &N, double p[], unsigned n[]);
virtual void random_shuffle(void *base, size_t base_length, size_t size_of_type);
virtual double cdf_standard_normal_distribution(const double &p);
virtual int random_binomial(const double &p, const unsigned int &n);
void shuffle(void *base, const size_t &n, const size_t &size);
};
#endif /* RANDOM_H */
|
= = Songs = =
|
!==========================================================================
elemental function gsw_enthalpy_t_exact (sa, t, p)
!==========================================================================
!
! Calculates the specific enthalpy of seawater
!
! sa : Absolute Salinity [g/kg]
! t : in-situ temperature [deg C]
! p : sea pressure [dbar]
!
! gsw_enthalpy_t_exact : specific enthalpy [J/kg]
!--------------------------------------------------------------------------
use gsw_mod_toolbox, only : gsw_gibbs
use gsw_mod_teos10_constants, only : gsw_t0
use gsw_mod_kinds
implicit none
real (r8), intent(in) :: sa, t, p
real (r8) :: gsw_enthalpy_t_exact
integer, parameter :: n0=0, n1=1
gsw_enthalpy_t_exact = gsw_gibbs(n0,n0,n0,sa,t,p) - &
(t+gsw_t0)*gsw_gibbs(n0,n1,n0,sa,t,p)
return
end function
!--------------------------------------------------------------------------
|
Northeastern International Airways suspended service on all but one of its routes after an unsuccessful attempt to attract passengers with new cut-rate fares. The airline, which filed for bankruptcy Tuesday, suspended ''until further notice'' flights to Chicago, Philadelphia and Orlando, St. Petersburg and West Palm Beach, Fla., a spokesman said. It is continuing flights between Islip, N.Y., and Ft. Lauderdale. A Northeastern flight from Chicago to Florida was canceled Wednesday because of mechanical problems. The privately held Ft. Lauderdale-based airline owes some $15 million to creditors. Under mounting pressure from creditors, Northeastern terminated flights to a number of cities earlier this week. The operation was undercapitalized and ran into problems after a quick expansion. |
[STATEMENT]
lemma set_insort [simp]:
"set (insort cmp x xs) = insert x (set xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set (Sorting_Algorithms.insort cmp x xs) = insert x (set xs)
[PROOF STEP]
by (induction xs) auto |
RequirePackage("grape");
V := GF(3)^7;
P := Filtered(List(Elements(Subspaces(V, 1)), v -> Elements(v)[2]), u -> u*u = Z(3));;
G := Graph(Group(()), P, function(x,y) return x; end, function(x,y) return x*y = 0*Z(3); end, true);;
GlobalParameters(G);
|
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
! This file was ported from Lean 3 source module algebra.quaternion
! leanprover-community/mathlib commit da3fc4a33ff6bc75f077f691dc94c217b8d41559
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Algebra.Algebra.Equiv
import Mathbin.LinearAlgebra.Finrank
import Mathbin.LinearAlgebra.FreeModule.Basic
import Mathbin.LinearAlgebra.FreeModule.Finite.Basic
import Mathbin.SetTheory.Cardinal.Ordinal
import Mathbin.Tactic.RingExp
/-!
# Quaternions
In this file we define quaternions `β[R]` over a commutative ring `R`, and define some
algebraic structures on `β[R]`.
## Main definitions
* `quaternion_algebra R a b`, `β[R, a, b]` :
[quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b`
* `quaternion R`, `β[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`;
* `quaternion.norm_sq` : square of the norm of a quaternion;
* `quaternion.conj` : conjugate of a quaternion;
We also define the following algebraic structures on `β[R]`:
* `ring β[R, a, b]` and `algebra R β[R, a, b]` : for any commutative ring `R`;
* `ring β[R]` and `algebra R β[R]` : for any commutative ring `R`;
* `domain β[R]` : for a linear ordered commutative ring `R`;
* `division_algebra β[R]` : for a linear ordered field `R`.
## Notation
The following notation is available with `open_locale quaternion`.
* `β[R, cβ, cβ]` : `quaternion_algebra R cβ cβ`
* `β[R]` : quaternions over `R`.
## Implementation notes
We define quaternions over any ring `R`, not just `β` to be able to deal with, e.g., integer
or rational quaternions without using real numbers. In particular, all definitions in this file
are computable.
## Tags
quaternion
-/
/- ./././Mathport/Syntax/Translate/Command.lean:424:34: infer kinds are unsupported in Lean 4: mk {} -/
/-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$.
Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/
@[nolint unused_arguments, ext]
structure QuaternionAlgebra (R : Type _) (a b : R) where mk ::
re : R
imI : R
imJ : R
imK : R
#align quaternion_algebra QuaternionAlgebra
-- mathport name: quaternion_algebra
scoped[Quaternion] notation "β[" R "," a "," b "]" => QuaternionAlgebra R a b
namespace QuaternionAlgebra
/-- The equivalence between a quaternion algebra over R and R Γ R Γ R Γ R. -/
@[simps]
def equivProd {R : Type _} (cβ cβ : R) : β[R,cβ,cβ] β R Γ R Γ R Γ R
where
toFun a := β¨a.1, a.2, a.3, a.4β©
invFun a := β¨a.1, a.2.1, a.2.2.1, a.2.2.2β©
left_inv := fun β¨aβ, aβ, aβ, aββ© => rfl
right_inv := fun β¨aβ, aβ, aβ, aββ© => rfl
#align quaternion_algebra.equiv_prod QuaternionAlgebra.equivProd
/-- The equivalence between a quaternion algebra over `R` and `fin 4 β R`. -/
@[simps symm_apply]
def equivTuple {R : Type _} (cβ cβ : R) : β[R,cβ,cβ] β (Fin 4 β R)
where
toFun a := ![a.1, a.2, a.3, a.4]
invFun a := β¨a 0, a 1, a 2, a 3β©
left_inv := fun β¨aβ, aβ, aβ, aββ© => rfl
right_inv f := by ext β¨_, _ | _ | _ | _ | _ | β¨β©β© <;> rfl
#align quaternion_algebra.equiv_tuple QuaternionAlgebra.equivTuple
@[simp]
theorem equivTuple_apply {R : Type _} (cβ cβ : R) (x : β[R,cβ,cβ]) :
equivTuple cβ cβ x = ![x.re, x.imI, x.imJ, x.imK] :=
rfl
#align quaternion_algebra.equiv_tuple_apply QuaternionAlgebra.equivTuple_apply
@[simp]
theorem mk.eta {R : Type _} {cβ cβ} : β a : β[R,cβ,cβ], mk a.1 a.2 a.3 a.4 = a
| β¨aβ, aβ, aβ, aββ© => rfl
#align quaternion_algebra.mk.eta QuaternionAlgebra.mk.eta
variable {S T R : Type _} [CommRing R] {cβ cβ : R} (r x y z : R) (a b c : β[R,cβ,cβ])
/-- The imaginary part of a quaternion. -/
def im (x : β[R,cβ,cβ]) : β[R,cβ,cβ] :=
β¨0, x.imI, x.imJ, x.imKβ©
#align quaternion_algebra.im QuaternionAlgebra.im
@[simp]
theorem im_re : a.im.re = 0 :=
rfl
#align quaternion_algebra.im_re QuaternionAlgebra.im_re
@[simp]
theorem im_imI : a.im.imI = a.imI :=
rfl
#align quaternion_algebra.im_im_i QuaternionAlgebra.im_imI
@[simp]
theorem im_imJ : a.im.imJ = a.imJ :=
rfl
#align quaternion_algebra.im_im_j QuaternionAlgebra.im_imJ
@[simp]
theorem im_imK : a.im.imK = a.imK :=
rfl
#align quaternion_algebra.im_im_k QuaternionAlgebra.im_imK
@[simp]
theorem im_idem : a.im.im = a.im :=
rfl
#align quaternion_algebra.im_idem QuaternionAlgebra.im_idem
instance : CoeTC R β[R,cβ,cβ] :=
β¨fun x => β¨x, 0, 0, 0β©β©
@[simp, norm_cast]
theorem coe_re : (x : β[R,cβ,cβ]).re = x :=
rfl
#align quaternion_algebra.coe_re QuaternionAlgebra.coe_re
@[simp, norm_cast]
theorem coe_imI : (x : β[R,cβ,cβ]).imI = 0 :=
rfl
#align quaternion_algebra.coe_im_i QuaternionAlgebra.coe_imI
@[simp, norm_cast]
theorem coe_imJ : (x : β[R,cβ,cβ]).imJ = 0 :=
rfl
#align quaternion_algebra.coe_im_j QuaternionAlgebra.coe_imJ
@[simp, norm_cast]
theorem coe_imK : (x : β[R,cβ,cβ]).imK = 0 :=
rfl
#align quaternion_algebra.coe_im_k QuaternionAlgebra.coe_imK
theorem coe_injective : Function.Injective (coe : R β β[R,cβ,cβ]) := fun x y h => congr_arg re h
#align quaternion_algebra.coe_injective QuaternionAlgebra.coe_injective
@[simp]
theorem coe_inj {x y : R} : (x : β[R,cβ,cβ]) = y β x = y :=
coe_injective.eq_iff
#align quaternion_algebra.coe_inj QuaternionAlgebra.coe_inj
@[simps]
instance : Zero β[R,cβ,cβ] :=
β¨β¨0, 0, 0, 0β©β©
@[simp, norm_cast]
theorem coe_zero : ((0 : R) : β[R,cβ,cβ]) = 0 :=
rfl
#align quaternion_algebra.coe_zero QuaternionAlgebra.coe_zero
instance : Inhabited β[R,cβ,cβ] :=
β¨0β©
@[simps]
instance : One β[R,cβ,cβ] :=
β¨β¨1, 0, 0, 0β©β©
@[simp, norm_cast]
theorem coe_one : ((1 : R) : β[R,cβ,cβ]) = 1 :=
rfl
#align quaternion_algebra.coe_one QuaternionAlgebra.coe_one
@[simps]
instance : Add β[R,cβ,cβ] :=
β¨fun a b => β¨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4β©β©
@[simp]
theorem mk_add_mk (aβ aβ aβ aβ bβ bβ bβ bβ : R) :
(mk aβ aβ aβ aβ : β[R,cβ,cβ]) + mk bβ bβ bβ bβ = mk (aβ + bβ) (aβ + bβ) (aβ + bβ) (aβ + bβ) :=
rfl
#align quaternion_algebra.mk_add_mk QuaternionAlgebra.mk_add_mk
@[norm_cast, simp]
theorem coe_add : ((x + y : R) : β[R,cβ,cβ]) = x + y := by ext <;> simp
#align quaternion_algebra.coe_add QuaternionAlgebra.coe_add
@[simps]
instance : Neg β[R,cβ,cβ] :=
β¨fun a => β¨-a.1, -a.2, -a.3, -a.4β©β©
@[simp]
theorem neg_mk (aβ aβ aβ aβ : R) : -(mk aβ aβ aβ aβ : β[R,cβ,cβ]) = β¨-aβ, -aβ, -aβ, -aββ© :=
rfl
#align quaternion_algebra.neg_mk QuaternionAlgebra.neg_mk
@[norm_cast, simp]
theorem coe_neg : ((-x : R) : β[R,cβ,cβ]) = -x := by ext <;> simp
#align quaternion_algebra.coe_neg QuaternionAlgebra.coe_neg
@[simps]
instance : Sub β[R,cβ,cβ] :=
β¨fun a b => β¨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4β©β©
@[simp]
theorem mk_sub_mk (aβ aβ aβ aβ bβ bβ bβ bβ : R) :
(mk aβ aβ aβ aβ : β[R,cβ,cβ]) - mk bβ bβ bβ bβ = mk (aβ - bβ) (aβ - bβ) (aβ - bβ) (aβ - bβ) :=
rfl
#align quaternion_algebra.mk_sub_mk QuaternionAlgebra.mk_sub_mk
@[simp, norm_cast]
theorem coe_im : (x : β[R,cβ,cβ]).im = 0 :=
rfl
#align quaternion_algebra.coe_im QuaternionAlgebra.coe_im
@[simp]
theorem re_add_im : βa.re + a.im = a :=
ext _ _ (add_zero _) (zero_add _) (zero_add _) (zero_add _)
#align quaternion_algebra.re_add_im QuaternionAlgebra.re_add_im
@[simp]
theorem sub_self_im : a - a.im = a.re :=
ext _ _ (sub_zero _) (sub_self _) (sub_self _) (sub_self _)
#align quaternion_algebra.sub_self_im QuaternionAlgebra.sub_self_im
@[simp]
theorem sub_self_re : a - a.re = a.im :=
ext _ _ (sub_self _) (sub_zero _) (sub_zero _) (sub_zero _)
#align quaternion_algebra.sub_self_re QuaternionAlgebra.sub_self_re
/-- Multiplication is given by
* `1 * x = x * 1 = x`;
* `i * i = cβ`;
* `j * j = cβ`;
* `i * j = k`, `j * i = -k`;
* `k * k = -cβ * cβ`;
* `i * k = cβ * j`, `k * i = `-cβ * j`;
* `j * k = -cβ * i`, `k * j = cβ * i`. -/
@[simps]
instance : Mul β[R,cβ,cβ] :=
β¨fun a b =>
β¨a.1 * b.1 + cβ * a.2 * b.2 + cβ * a.3 * b.3 - cβ * cβ * a.4 * b.4,
a.1 * b.2 + a.2 * b.1 - cβ * a.3 * b.4 + cβ * a.4 * b.3,
a.1 * b.3 + cβ * a.2 * b.4 + a.3 * b.1 - cβ * a.4 * b.2,
a.1 * b.4 + a.2 * b.3 - a.3 * b.2 + a.4 * b.1β©β©
@[simp]
theorem mk_mul_mk (aβ aβ aβ aβ bβ bβ bβ bβ : R) :
(mk aβ aβ aβ aβ : β[R,cβ,cβ]) * mk bβ bβ bβ bβ =
β¨aβ * bβ + cβ * aβ * bβ + cβ * aβ * bβ - cβ * cβ * aβ * bβ,
aβ * bβ + aβ * bβ - cβ * aβ * bβ + cβ * aβ * bβ,
aβ * bβ + cβ * aβ * bβ + aβ * bβ - cβ * aβ * bβ, aβ * bβ + aβ * bβ - aβ * bβ + aβ * bββ© :=
rfl
#align quaternion_algebra.mk_mul_mk QuaternionAlgebra.mk_mul_mk
section
variable [SMul S R] [SMul T R] (s : S)
/-
The `ring R` argument is not used, but it's also much stronger than the other definitions in this
file need; for instance `quaternion_algebra.has_zero` only really needs `has_zero R`. For
simplicity we just keep things consistent.
-/
@[nolint unused_arguments]
instance : SMul S β[R,cβ,cβ] where smul s a := β¨s β’ a.1, s β’ a.2, s β’ a.3, s β’ a.4β©
instance [SMul S T] [IsScalarTower S T R] : IsScalarTower S T β[R,cβ,cβ]
where smul_assoc s t x := by ext <;> exact smul_assoc _ _ _
instance [SMulCommClass S T R] : SMulCommClass S T β[R,cβ,cβ]
where smul_comm s t x := by ext <;> exact smul_comm _ _ _
@[simp]
theorem smul_re : (s β’ a).re = s β’ a.re :=
rfl
#align quaternion_algebra.smul_re QuaternionAlgebra.smul_re
@[simp]
theorem smul_imI : (s β’ a).imI = s β’ a.imI :=
rfl
#align quaternion_algebra.smul_im_i QuaternionAlgebra.smul_imI
@[simp]
theorem smul_imJ : (s β’ a).imJ = s β’ a.imJ :=
rfl
#align quaternion_algebra.smul_im_j QuaternionAlgebra.smul_imJ
@[simp]
theorem smul_imK : (s β’ a).imK = s β’ a.imK :=
rfl
#align quaternion_algebra.smul_im_k QuaternionAlgebra.smul_imK
@[simp]
theorem smul_mk (re im_i im_j im_k : R) :
s β’ (β¨re, im_i, im_j, im_kβ© : β[R,cβ,cβ]) = β¨s β’ re, s β’ im_i, s β’ im_j, s β’ im_kβ© :=
rfl
#align quaternion_algebra.smul_mk QuaternionAlgebra.smul_mk
end
@[simp, norm_cast]
theorem coe_smul [SMulZeroClass S R] (s : S) (r : R) : (β(s β’ r) : β[R,cβ,cβ]) = s β’ βr :=
ext _ _ rfl (smul_zero s).symm (smul_zero s).symm (smul_zero s).symm
#align quaternion_algebra.coe_smul QuaternionAlgebra.coe_smul
instance : AddCommGroup β[R,cβ,cβ] := by
refine_struct {
add := (Β· + Β·)
neg := Neg.neg
sub := Sub.sub
zero := (0 : β[R,cβ,cβ])
nsmul := (Β· β’ Β·)
zsmul := (Β· β’ Β·) } <;>
intros <;>
try rfl <;>
ext <;>
simp <;>
ring
instance : AddGroupWithOne β[R,cβ,cβ] :=
{
QuaternionAlgebra.addCommGroup with
natCast := fun n => ((n : R) : β[R,cβ,cβ])
natCast_zero := by simp
natCast_succ := by simp
intCast := fun n => ((n : R) : β[R,cβ,cβ])
intCast_ofNat := fun _ => congr_arg coe (Int.cast_ofNat _)
intCast_negSucc := fun n => show ββ_ = -ββ_ by rw [Int.cast_neg, Int.cast_ofNat, coe_neg]
one := 1 }
@[simp, norm_cast]
theorem nat_cast_re (n : β) : (n : β[R,cβ,cβ]).re = n :=
rfl
#align quaternion_algebra.nat_cast_re QuaternionAlgebra.nat_cast_re
@[simp, norm_cast]
theorem nat_cast_imI (n : β) : (n : β[R,cβ,cβ]).imI = 0 :=
rfl
#align quaternion_algebra.nat_cast_im_i QuaternionAlgebra.nat_cast_imI
@[simp, norm_cast]
theorem nat_cast_imJ (n : β) : (n : β[R,cβ,cβ]).imJ = 0 :=
rfl
#align quaternion_algebra.nat_cast_im_j QuaternionAlgebra.nat_cast_imJ
@[simp, norm_cast]
theorem nat_cast_imK (n : β) : (n : β[R,cβ,cβ]).imK = 0 :=
rfl
#align quaternion_algebra.nat_cast_im_k QuaternionAlgebra.nat_cast_imK
@[simp, norm_cast]
theorem nat_cast_im (n : β) : (n : β[R,cβ,cβ]).im = 0 :=
rfl
#align quaternion_algebra.nat_cast_im QuaternionAlgebra.nat_cast_im
@[norm_cast]
theorem coe_nat_cast (n : β) : β(n : R) = (n : β[R,cβ,cβ]) :=
rfl
#align quaternion_algebra.coe_nat_cast QuaternionAlgebra.coe_nat_cast
@[simp, norm_cast]
theorem int_cast_re (z : β€) : (z : β[R,cβ,cβ]).re = z :=
rfl
#align quaternion_algebra.int_cast_re QuaternionAlgebra.int_cast_re
@[simp, norm_cast]
theorem int_cast_imI (z : β€) : (z : β[R,cβ,cβ]).imI = 0 :=
rfl
#align quaternion_algebra.int_cast_im_i QuaternionAlgebra.int_cast_imI
@[simp, norm_cast]
theorem int_cast_imJ (z : β€) : (z : β[R,cβ,cβ]).imJ = 0 :=
rfl
#align quaternion_algebra.int_cast_im_j QuaternionAlgebra.int_cast_imJ
@[simp, norm_cast]
theorem int_cast_imK (z : β€) : (z : β[R,cβ,cβ]).imK = 0 :=
rfl
#align quaternion_algebra.int_cast_im_k QuaternionAlgebra.int_cast_imK
@[simp, norm_cast]
theorem int_cast_im (z : β€) : (z : β[R,cβ,cβ]).im = 0 :=
rfl
#align quaternion_algebra.int_cast_im QuaternionAlgebra.int_cast_im
@[norm_cast]
theorem coe_int_cast (z : β€) : β(z : R) = (z : β[R,cβ,cβ]) :=
rfl
#align quaternion_algebra.coe_int_cast QuaternionAlgebra.coe_int_cast
instance : Ring β[R,cβ,cβ] := by
refine_struct
{ QuaternionAlgebra.addGroupWithOne,
QuaternionAlgebra.addCommGroup with
add := (Β· + Β·)
mul := (Β· * Β·)
one := 1
npow := @npowRec _ β¨(1 : β[R,cβ,cβ])β© β¨(Β· * Β·)β© } <;>
intros <;>
try rfl <;>
ext <;>
simp <;>
ring
@[norm_cast, simp]
theorem coe_mul : ((x * y : R) : β[R,cβ,cβ]) = x * y := by ext <;> simp
#align quaternion_algebra.coe_mul QuaternionAlgebra.coe_mul
-- TODO: add weaker `mul_action`, `distrib_mul_action`, and `module` instances (and repeat them
-- for `β[R]`)
instance [CommSemiring S] [Algebra S R] : Algebra S β[R,cβ,cβ]
where
smul := (Β· β’ Β·)
toFun s := coe (algebraMap S R s)
map_one' := by simpa only [map_one]
map_zero' := by simpa only [map_zero]
map_mul' x y := by rw [map_mul, coe_mul]
map_add' x y := by rw [map_add, coe_add]
smul_def' s x := by ext <;> simp [Algebra.smul_def]
commutes' s x := by ext <;> simp [Algebra.commutes]
theorem algebraMap_eq (r : R) : algebraMap R β[R,cβ,cβ] r = β¨r, 0, 0, 0β© :=
rfl
#align quaternion_algebra.algebra_map_eq QuaternionAlgebra.algebraMap_eq
section
variable (cβ cβ)
/-- `quaternion_algebra.re` as a `linear_map`-/
@[simps]
def reLm : β[R,cβ,cβ] ββ[R] R where
toFun := re
map_add' x y := rfl
map_smul' r x := rfl
#align quaternion_algebra.re_lm QuaternionAlgebra.reLm
/-- `quaternion_algebra.im_i` as a `linear_map`-/
@[simps]
def imILm : β[R,cβ,cβ] ββ[R] R where
toFun := imI
map_add' x y := rfl
map_smul' r x := rfl
#align quaternion_algebra.im_i_lm QuaternionAlgebra.imILm
/-- `quaternion_algebra.im_j` as a `linear_map`-/
@[simps]
def imJLm : β[R,cβ,cβ] ββ[R] R where
toFun := imJ
map_add' x y := rfl
map_smul' r x := rfl
#align quaternion_algebra.im_j_lm QuaternionAlgebra.imJLm
/-- `quaternion_algebra.im_k` as a `linear_map`-/
@[simps]
def imKLm : β[R,cβ,cβ] ββ[R] R where
toFun := imK
map_add' x y := rfl
map_smul' r x := rfl
#align quaternion_algebra.im_k_lm QuaternionAlgebra.imKLm
/-- `quaternion_algebra.equiv_tuple` as a linear equivalence. -/
def linearEquivTuple : β[R,cβ,cβ] ββ[R] Fin 4 β R :=
LinearEquiv.symm-- proofs are not `rfl` in the forward direction
{ (equivTuple cβ cβ).symm with
toFun := (equivTuple cβ cβ).symm
invFun := equivTuple cβ cβ
map_add' := fun vβ vβ => rfl
map_smul' := fun vβ vβ => rfl }
#align quaternion_algebra.linear_equiv_tuple QuaternionAlgebra.linearEquivTuple
@[simp]
theorem coe_linearEquivTuple : β(linearEquivTuple cβ cβ) = equivTuple cβ cβ :=
rfl
#align quaternion_algebra.coe_linear_equiv_tuple QuaternionAlgebra.coe_linearEquivTuple
@[simp]
theorem coe_linearEquivTuple_symm : β(linearEquivTuple cβ cβ).symm = (equivTuple cβ cβ).symm :=
rfl
#align quaternion_algebra.coe_linear_equiv_tuple_symm QuaternionAlgebra.coe_linearEquivTuple_symm
/-- `β[R, cβ, cβ]` has a basis over `R` given by `1`, `i`, `j`, and `k`. -/
noncomputable def basisOneIJK : Basis (Fin 4) R β[R,cβ,cβ] :=
Basis.ofEquivFun <| linearEquivTuple cβ cβ
#align quaternion_algebra.basis_one_i_j_k QuaternionAlgebra.basisOneIJK
@[simp]
theorem coe_basisOneIJK_repr (q : β[R,cβ,cβ]) :
β((basisOneIJK cβ cβ).repr q) = ![q.re, q.imI, q.imJ, q.imK] :=
rfl
#align quaternion_algebra.coe_basis_one_i_j_k_repr QuaternionAlgebra.coe_basisOneIJK_repr
instance : Module.Finite R β[R,cβ,cβ] :=
Module.Finite.of_basis (basisOneIJK cβ cβ)
instance : Module.Free R β[R,cβ,cβ] :=
Module.Free.of_basis (basisOneIJK cβ cβ)
theorem dim_eq_four [StrongRankCondition R] : Module.rank R β[R,cβ,cβ] = 4 :=
by
rw [dim_eq_card_basis (basis_one_i_j_k cβ cβ), Fintype.card_fin]
norm_num
#align quaternion_algebra.dim_eq_four QuaternionAlgebra.dim_eq_four
theorem finrank_eq_four [StrongRankCondition R] : FiniteDimensional.finrank R β[R,cβ,cβ] = 4 :=
by
have : Cardinal.toNat 4 = 4 := by
rw [β Cardinal.toNat_cast 4, Nat.cast_bit0, Nat.cast_bit0, Nat.cast_one]
rw [FiniteDimensional.finrank, dim_eq_four, this]
#align quaternion_algebra.finrank_eq_four QuaternionAlgebra.finrank_eq_four
end
@[norm_cast, simp]
theorem coe_sub : ((x - y : R) : β[R,cβ,cβ]) = x - y :=
(algebraMap R β[R,cβ,cβ]).map_sub x y
#align quaternion_algebra.coe_sub QuaternionAlgebra.coe_sub
@[norm_cast, simp]
theorem coe_pow (n : β) : (β(x ^ n) : β[R,cβ,cβ]) = βx ^ n :=
(algebraMap R β[R,cβ,cβ]).map_pow x n
#align quaternion_algebra.coe_pow QuaternionAlgebra.coe_pow
theorem coe_commutes : βr * a = a * r :=
Algebra.commutes r a
#align quaternion_algebra.coe_commutes QuaternionAlgebra.coe_commutes
theorem coe_commute : Commute (βr) a :=
coe_commutes r a
#align quaternion_algebra.coe_commute QuaternionAlgebra.coe_commute
theorem coe_mul_eq_smul : βr * a = r β’ a :=
(Algebra.smul_def r a).symm
#align quaternion_algebra.coe_mul_eq_smul QuaternionAlgebra.coe_mul_eq_smul
theorem mul_coe_eq_smul : a * r = r β’ a := by rw [β coe_commutes, coe_mul_eq_smul]
#align quaternion_algebra.mul_coe_eq_smul QuaternionAlgebra.mul_coe_eq_smul
@[norm_cast, simp]
theorem coe_algebraMap : β(algebraMap R β[R,cβ,cβ]) = coe :=
rfl
#align quaternion_algebra.coe_algebra_map QuaternionAlgebra.coe_algebraMap
theorem smul_coe : x β’ (y : β[R,cβ,cβ]) = β(x * y) := by rw [coe_mul, coe_mul_eq_smul]
#align quaternion_algebra.smul_coe QuaternionAlgebra.smul_coe
/-- Quaternion conjugate. -/
def conj : β[R,cβ,cβ] ββ[R] β[R,cβ,cβ] :=
LinearEquiv.ofInvolutive
{ toFun := fun a => β¨a.1, -a.2, -a.3, -a.4β©
map_add' := fun a b => by ext <;> simp [neg_add]
map_smul' := fun r a => by ext <;> simp } fun a => by simp
#align quaternion_algebra.conj QuaternionAlgebra.conj
@[simp]
theorem re_conj : (conj a).re = a.re :=
rfl
#align quaternion_algebra.re_conj QuaternionAlgebra.re_conj
@[simp]
theorem imI_conj : (conj a).imI = -a.imI :=
rfl
#align quaternion_algebra.im_i_conj QuaternionAlgebra.imI_conj
@[simp]
theorem imJ_conj : (conj a).imJ = -a.imJ :=
rfl
#align quaternion_algebra.im_j_conj QuaternionAlgebra.imJ_conj
@[simp]
theorem imK_conj : (conj a).imK = -a.imK :=
rfl
#align quaternion_algebra.im_k_conj QuaternionAlgebra.imK_conj
@[simp]
theorem im_conj : (conj a).im = -a.im :=
ext _ _ neg_zero.symm rfl rfl rfl
#align quaternion_algebra.im_conj QuaternionAlgebra.im_conj
@[simp]
theorem conj_mk (aβ aβ aβ aβ : R) : conj (mk aβ aβ aβ aβ : β[R,cβ,cβ]) = β¨aβ, -aβ, -aβ, -aββ© :=
rfl
#align quaternion_algebra.conj_mk QuaternionAlgebra.conj_mk
@[simp]
theorem conj_conj : a.conj.conj = a :=
ext _ _ rfl (neg_neg _) (neg_neg _) (neg_neg _)
#align quaternion_algebra.conj_conj QuaternionAlgebra.conj_conj
theorem conj_add : (a + b).conj = a.conj + b.conj :=
conj.map_add a b
#align quaternion_algebra.conj_add QuaternionAlgebra.conj_add
@[simp]
theorem conj_mul : (a * b).conj = b.conj * a.conj := by ext <;> simp <;> ring
#align quaternion_algebra.conj_mul QuaternionAlgebra.conj_mul
theorem conj_conj_mul : (a.conj * b).conj = b.conj * a := by rw [conj_mul, conj_conj]
#align quaternion_algebra.conj_conj_mul QuaternionAlgebra.conj_conj_mul
theorem conj_mul_conj : (a * b.conj).conj = b * a.conj := by rw [conj_mul, conj_conj]
#align quaternion_algebra.conj_mul_conj QuaternionAlgebra.conj_mul_conj
theorem self_add_conj' : a + a.conj = β(2 * a.re) := by ext <;> simp [two_mul]
#align quaternion_algebra.self_add_conj' QuaternionAlgebra.self_add_conj'
theorem self_add_conj : a + a.conj = 2 * a.re := by simp only [self_add_conj', two_mul, coe_add]
#align quaternion_algebra.self_add_conj QuaternionAlgebra.self_add_conj
theorem conj_add_self' : a.conj + a = β(2 * a.re) := by rw [add_comm, self_add_conj']
#align quaternion_algebra.conj_add_self' QuaternionAlgebra.conj_add_self'
theorem conj_add_self : a.conj + a = 2 * a.re := by rw [add_comm, self_add_conj]
#align quaternion_algebra.conj_add_self QuaternionAlgebra.conj_add_self
theorem conj_eq_two_re_sub : a.conj = β(2 * a.re) - a :=
eq_sub_iff_add_eq.2 a.conj_add_self'
#align quaternion_algebra.conj_eq_two_re_sub QuaternionAlgebra.conj_eq_two_re_sub
theorem commute_conj_self : Commute a.conj a :=
by
rw [a.conj_eq_two_re_sub]
exact (coe_commute (2 * a.re) a).sub_left (Commute.refl a)
#align quaternion_algebra.commute_conj_self QuaternionAlgebra.commute_conj_self
theorem commute_self_conj : Commute a a.conj :=
a.commute_conj_self.symm
#align quaternion_algebra.commute_self_conj QuaternionAlgebra.commute_self_conj
theorem commute_conj_conj {a b : β[R,cβ,cβ]} (h : Commute a b) : Commute a.conj b.conj :=
calc
a.conj * b.conj = (b * a).conj := (conj_mul b a).symm
_ = (a * b).conj := by rw [h.eq]
_ = b.conj * a.conj := conj_mul a b
#align quaternion_algebra.commute_conj_conj QuaternionAlgebra.commute_conj_conj
@[simp, norm_cast]
theorem conj_coe : conj (x : β[R,cβ,cβ]) = x := by ext <;> simp
#align quaternion_algebra.conj_coe QuaternionAlgebra.conj_coe
@[simp]
theorem conj_im : conj a.im = -a.im :=
im_conj _
#align quaternion_algebra.conj_im QuaternionAlgebra.conj_im
@[simp, norm_cast]
theorem conj_nat_cast (n : β) : conj (n : β[R,cβ,cβ]) = n := by rw [β coe_nat_cast, conj_coe]
#align quaternion_algebra.conj_nat_cast QuaternionAlgebra.conj_nat_cast
@[simp, norm_cast]
theorem conj_int_cast (z : β€) : conj (z : β[R,cβ,cβ]) = z := by rw [β coe_int_cast, conj_coe]
#align quaternion_algebra.conj_int_cast QuaternionAlgebra.conj_int_cast
@[simp]
theorem conj_smul [Monoid S] [DistribMulAction S R] (s : S) (a : β[R,cβ,cβ]) :
conj (s β’ a) = s β’ conj a :=
ext _ _ rfl (smul_neg _ _).symm (smul_neg _ _).symm (smul_neg _ _).symm
#align quaternion_algebra.conj_smul QuaternionAlgebra.conj_smul
@[simp]
theorem conj_one : conj (1 : β[R,cβ,cβ]) = 1 :=
conj_coe 1
#align quaternion_algebra.conj_one QuaternionAlgebra.conj_one
theorem eq_re_of_eq_coe {a : β[R,cβ,cβ]} {x : R} (h : a = x) : a = a.re := by rw [h, coe_re]
#align quaternion_algebra.eq_re_of_eq_coe QuaternionAlgebra.eq_re_of_eq_coe
theorem eq_re_iff_mem_range_coe {a : β[R,cβ,cβ]} :
a = a.re β a β Set.range (coe : R β β[R,cβ,cβ]) :=
β¨fun h => β¨a.re, h.symmβ©, fun β¨x, hβ© => eq_re_of_eq_coe h.symmβ©
#align quaternion_algebra.eq_re_iff_mem_range_coe QuaternionAlgebra.eq_re_iff_mem_range_coe
section CharZero
variable [NoZeroDivisors R] [CharZero R]
@[simp]
theorem conj_eq_self {cβ cβ : R} {a : β[R,cβ,cβ]} : conj a = a β a = a.re := by
simp [ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero]
#align quaternion_algebra.conj_eq_self QuaternionAlgebra.conj_eq_self
theorem conj_eq_neg {cβ cβ : R} {a : β[R,cβ,cβ]} : conj a = -a β a.re = 0 := by
simp [ext_iff, eq_neg_iff_add_eq_zero]
#align quaternion_algebra.conj_eq_neg QuaternionAlgebra.conj_eq_neg
end CharZero
-- Can't use `rw β conj_eq_self` in the proof without additional assumptions
theorem conj_mul_eq_coe : conj a * a = (conj a * a).re := by ext <;> simp <;> ring
#align quaternion_algebra.conj_mul_eq_coe QuaternionAlgebra.conj_mul_eq_coe
theorem mul_conj_eq_coe : a * conj a = (a * conj a).re :=
by
rw [a.commute_self_conj.eq]
exact a.conj_mul_eq_coe
#align quaternion_algebra.mul_conj_eq_coe QuaternionAlgebra.mul_conj_eq_coe
theorem conj_zero : conj (0 : β[R,cβ,cβ]) = 0 :=
conj.map_zero
#align quaternion_algebra.conj_zero QuaternionAlgebra.conj_zero
theorem conj_neg : (-a).conj = -a.conj :=
(conj : β[R,cβ,cβ] ββ[R] _).map_neg a
#align quaternion_algebra.conj_neg QuaternionAlgebra.conj_neg
theorem conj_sub : (a - b).conj = a.conj - b.conj :=
(conj : β[R,cβ,cβ] ββ[R] _).map_sub a b
#align quaternion_algebra.conj_sub QuaternionAlgebra.conj_sub
instance : StarRing β[R,cβ,cβ] where
unit := conj
star_involutive := conj_conj
star_add := conj_add
star_mul := conj_mul
@[simp]
theorem star_def (a : β[R,cβ,cβ]) : star a = conj a :=
rfl
#align quaternion_algebra.star_def QuaternionAlgebra.star_def
@[simp]
theorem conj_pow (n : β) : (a ^ n).conj = a.conj ^ n :=
star_pow _ _
#align quaternion_algebra.conj_pow QuaternionAlgebra.conj_pow
open MulOpposite
/-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/
def conjAe : β[R,cβ,cβ] ββ[R] β[R,cβ,cβ]α΅α΅α΅ :=
{ conj.toAddEquiv.trans opAddEquiv with
toFun := op β conj
invFun := conj β unop
map_mul' := fun x y => by simp
commutes' := fun r => by simp }
#align quaternion_algebra.conj_ae QuaternionAlgebra.conjAe
@[simp]
theorem coe_conjAe : β(conjAe : β[R,cβ,cβ] ββ[R] _) = op β conj :=
rfl
#align quaternion_algebra.coe_conj_ae QuaternionAlgebra.coe_conjAe
end QuaternionAlgebra
/-- Space of quaternions over a type. Implemented as a structure with four fields:
`re`, `im_i`, `im_j`, and `im_k`. -/
def Quaternion (R : Type _) [One R] [Neg R] :=
QuaternionAlgebra R (-1) (-1)
#align quaternion Quaternion
-- mathport name: quaternion
scoped[Quaternion] notation "β[" R "]" => Quaternion R
/-- The equivalence between the quaternions over `R` and `R Γ R Γ R Γ R`. -/
@[simps]
def Quaternion.equivProd (R : Type _) [One R] [Neg R] : β[R] β R Γ R Γ R Γ R :=
QuaternionAlgebra.equivProd _ _
#align quaternion.equiv_prod Quaternion.equivProd
/-- The equivalence between the quaternions over `R` and `fin 4 β R`. -/
@[simps symm_apply]
def Quaternion.equivTuple (R : Type _) [One R] [Neg R] : β[R] β (Fin 4 β R) :=
QuaternionAlgebra.equivTuple _ _
#align quaternion.equiv_tuple Quaternion.equivTuple
@[simp]
theorem Quaternion.equivTuple_apply (R : Type _) [One R] [Neg R] (x : β[R]) :
Quaternion.equivTuple R x = ![x.re, x.imI, x.imJ, x.imK] :=
rfl
#align quaternion.equiv_tuple_apply Quaternion.equivTuple_apply
namespace Quaternion
variable {S T R : Type _} [CommRing R] (r x y z : R) (a b c : β[R])
export QuaternionAlgebra (re imI imJ imK)
instance : CoeTC R β[R] :=
QuaternionAlgebra.hasCoeT
instance : Ring β[R] :=
QuaternionAlgebra.ring
instance : Inhabited β[R] :=
QuaternionAlgebra.inhabited
instance [SMul S R] : SMul S β[R] :=
QuaternionAlgebra.hasSmul
instance [SMul S T] [SMul S R] [SMul T R] [IsScalarTower S T R] : IsScalarTower S T β[R] :=
QuaternionAlgebra.isScalarTower
instance [SMul S R] [SMul T R] [SMulCommClass S T R] : SMulCommClass S T β[R] :=
QuaternionAlgebra.sMulCommClass
instance [CommSemiring S] [Algebra S R] : Algebra S β[R] :=
QuaternionAlgebra.algebra
instance : StarRing β[R] :=
QuaternionAlgebra.starRing
@[ext]
theorem ext : a.re = b.re β a.imI = b.imI β a.imJ = b.imJ β a.imK = b.imK β a = b :=
QuaternionAlgebra.ext a b
#align quaternion.ext Quaternion.ext
theorem ext_iff {a b : β[R]} :
a = b β a.re = b.re β§ a.imI = b.imI β§ a.imJ = b.imJ β§ a.imK = b.imK :=
QuaternionAlgebra.ext_iff a b
#align quaternion.ext_iff Quaternion.ext_iff
/-- The imaginary part of a quaternion. -/
def im (x : β[R]) : β[R] :=
x.im
#align quaternion.im Quaternion.im
@[simp]
theorem im_re : a.im.re = 0 :=
rfl
#align quaternion.im_re Quaternion.im_re
@[simp]
theorem im_imI : a.im.imI = a.imI :=
rfl
#align quaternion.im_im_i Quaternion.im_imI
@[simp]
theorem im_imJ : a.im.imJ = a.imJ :=
rfl
#align quaternion.im_im_j Quaternion.im_imJ
@[simp]
theorem im_imK : a.im.imK = a.imK :=
rfl
#align quaternion.im_im_k Quaternion.im_imK
@[simp]
theorem im_idem : a.im.im = a.im :=
rfl
#align quaternion.im_idem Quaternion.im_idem
@[simp]
theorem re_add_im : βa.re + a.im = a :=
a.re_add_im
#align quaternion.re_add_im Quaternion.re_add_im
@[simp]
theorem sub_self_im : a - a.im = a.re :=
a.sub_self_im
#align quaternion.sub_self_im Quaternion.sub_self_im
@[simp]
theorem sub_self_re : a - a.re = a.im :=
a.sub_self_re
#align quaternion.sub_self_re Quaternion.sub_self_re
@[simp, norm_cast]
theorem coe_re : (x : β[R]).re = x :=
rfl
#align quaternion.coe_re Quaternion.coe_re
@[simp, norm_cast]
theorem coe_imI : (x : β[R]).imI = 0 :=
rfl
#align quaternion.coe_im_i Quaternion.coe_imI
@[simp, norm_cast]
theorem coe_imJ : (x : β[R]).imJ = 0 :=
rfl
#align quaternion.coe_im_j Quaternion.coe_imJ
@[simp, norm_cast]
theorem coe_imK : (x : β[R]).imK = 0 :=
rfl
#align quaternion.coe_im_k Quaternion.coe_imK
@[simp, norm_cast]
theorem coe_im : (x : β[R]).im = 0 :=
rfl
#align quaternion.coe_im Quaternion.coe_im
@[simp]
theorem zero_re : (0 : β[R]).re = 0 :=
rfl
#align quaternion.zero_re Quaternion.zero_re
@[simp]
theorem zero_imI : (0 : β[R]).imI = 0 :=
rfl
#align quaternion.zero_im_i Quaternion.zero_imI
@[simp]
theorem zero_imJ : (0 : β[R]).imJ = 0 :=
rfl
#align quaternion.zero_im_j Quaternion.zero_imJ
@[simp]
theorem zero_imK : (0 : β[R]).imK = 0 :=
rfl
#align quaternion.zero_im_k Quaternion.zero_imK
@[simp]
theorem zero_im : (0 : β[R]).im = 0 :=
rfl
#align quaternion.zero_im Quaternion.zero_im
@[simp, norm_cast]
theorem coe_zero : ((0 : R) : β[R]) = 0 :=
rfl
#align quaternion.coe_zero Quaternion.coe_zero
@[simp]
theorem one_re : (1 : β[R]).re = 1 :=
rfl
#align quaternion.one_re Quaternion.one_re
@[simp]
theorem one_imI : (1 : β[R]).imI = 0 :=
rfl
#align quaternion.one_im_i Quaternion.one_imI
@[simp]
theorem one_imJ : (1 : β[R]).imJ = 0 :=
rfl
#align quaternion.one_im_j Quaternion.one_imJ
@[simp]
theorem one_imK : (1 : β[R]).imK = 0 :=
rfl
#align quaternion.one_im_k Quaternion.one_imK
@[simp]
theorem one_im : (1 : β[R]).im = 0 :=
rfl
#align quaternion.one_im Quaternion.one_im
@[simp, norm_cast]
theorem coe_one : ((1 : R) : β[R]) = 1 :=
rfl
#align quaternion.coe_one Quaternion.coe_one
@[simp]
theorem add_re : (a + b).re = a.re + b.re :=
rfl
#align quaternion.add_re Quaternion.add_re
@[simp]
theorem add_imI : (a + b).imI = a.imI + b.imI :=
rfl
#align quaternion.add_im_i Quaternion.add_imI
@[simp]
theorem add_imJ : (a + b).imJ = a.imJ + b.imJ :=
rfl
#align quaternion.add_im_j Quaternion.add_imJ
@[simp]
theorem add_imK : (a + b).imK = a.imK + b.imK :=
rfl
#align quaternion.add_im_k Quaternion.add_imK
@[simp]
theorem add_im : (a + b).im = a.im + b.im :=
ext _ _ (add_zero _).symm rfl rfl rfl
#align quaternion.add_im Quaternion.add_im
@[simp, norm_cast]
theorem coe_add : ((x + y : R) : β[R]) = x + y :=
QuaternionAlgebra.coe_add x y
#align quaternion.coe_add Quaternion.coe_add
@[simp]
theorem neg_re : (-a).re = -a.re :=
rfl
#align quaternion.neg_re Quaternion.neg_re
@[simp]
theorem neg_imI : (-a).imI = -a.imI :=
rfl
#align quaternion.neg_im_i Quaternion.neg_imI
@[simp]
theorem neg_imJ : (-a).imJ = -a.imJ :=
rfl
#align quaternion.neg_im_j Quaternion.neg_imJ
@[simp]
theorem neg_imK : (-a).imK = -a.imK :=
rfl
#align quaternion.neg_im_k Quaternion.neg_imK
@[simp]
theorem neg_im : (-a).im = -a.im :=
ext _ _ neg_zero.symm rfl rfl rfl
#align quaternion.neg_im Quaternion.neg_im
@[simp, norm_cast]
theorem coe_neg : ((-x : R) : β[R]) = -x :=
QuaternionAlgebra.coe_neg x
#align quaternion.coe_neg Quaternion.coe_neg
@[simp]
theorem sub_re : (a - b).re = a.re - b.re :=
rfl
#align quaternion.sub_re Quaternion.sub_re
@[simp]
theorem sub_imI : (a - b).imI = a.imI - b.imI :=
rfl
#align quaternion.sub_im_i Quaternion.sub_imI
@[simp]
theorem sub_imJ : (a - b).imJ = a.imJ - b.imJ :=
rfl
#align quaternion.sub_im_j Quaternion.sub_imJ
@[simp]
theorem sub_imK : (a - b).imK = a.imK - b.imK :=
rfl
#align quaternion.sub_im_k Quaternion.sub_imK
@[simp]
theorem sub_im : (a - b).im = a.im - b.im :=
ext _ _ (sub_zero _).symm rfl rfl rfl
#align quaternion.sub_im Quaternion.sub_im
@[simp, norm_cast]
theorem coe_sub : ((x - y : R) : β[R]) = x - y :=
QuaternionAlgebra.coe_sub x y
#align quaternion.coe_sub Quaternion.coe_sub
@[simp]
theorem mul_re : (a * b).re = a.re * b.re - a.imI * b.imI - a.imJ * b.imJ - a.imK * b.imK :=
(QuaternionAlgebra.hasMul_mul_re a b).trans <| by
simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg]
#align quaternion.mul_re Quaternion.mul_re
@[simp]
theorem mul_imI : (a * b).imI = a.re * b.imI + a.imI * b.re + a.imJ * b.imK - a.imK * b.imJ :=
(QuaternionAlgebra.hasMul_mul_imI a b).trans <| by
simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg]
#align quaternion.mul_im_i Quaternion.mul_imI
@[simp]
theorem mul_imJ : (a * b).imJ = a.re * b.imJ - a.imI * b.imK + a.imJ * b.re + a.imK * b.imI :=
(QuaternionAlgebra.hasMul_mul_imJ a b).trans <| by
simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg]
#align quaternion.mul_im_j Quaternion.mul_imJ
@[simp]
theorem mul_imK : (a * b).imK = a.re * b.imK + a.imI * b.imJ - a.imJ * b.imI + a.imK * b.re :=
(QuaternionAlgebra.hasMul_mul_imK a b).trans <| by
simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg]
#align quaternion.mul_im_k Quaternion.mul_imK
@[simp, norm_cast]
theorem coe_mul : ((x * y : R) : β[R]) = x * y :=
QuaternionAlgebra.coe_mul x y
#align quaternion.coe_mul Quaternion.coe_mul
@[norm_cast, simp]
theorem coe_pow (n : β) : (β(x ^ n) : β[R]) = βx ^ n :=
QuaternionAlgebra.coe_pow x n
#align quaternion.coe_pow Quaternion.coe_pow
@[simp, norm_cast]
theorem nat_cast_re (n : β) : (n : β[R]).re = n :=
rfl
#align quaternion.nat_cast_re Quaternion.nat_cast_re
@[simp, norm_cast]
theorem nat_cast_imI (n : β) : (n : β[R]).imI = 0 :=
rfl
#align quaternion.nat_cast_im_i Quaternion.nat_cast_imI
@[simp, norm_cast]
theorem nat_cast_imJ (n : β) : (n : β[R]).imJ = 0 :=
rfl
#align quaternion.nat_cast_im_j Quaternion.nat_cast_imJ
@[simp, norm_cast]
theorem nat_cast_imK (n : β) : (n : β[R]).imK = 0 :=
rfl
#align quaternion.nat_cast_im_k Quaternion.nat_cast_imK
@[simp, norm_cast]
theorem nat_cast_im (n : β) : (n : β[R]).im = 0 :=
rfl
#align quaternion.nat_cast_im Quaternion.nat_cast_im
@[norm_cast]
theorem coe_nat_cast (n : β) : β(n : R) = (n : β[R]) :=
rfl
#align quaternion.coe_nat_cast Quaternion.coe_nat_cast
@[simp, norm_cast]
theorem int_cast_re (z : β€) : (z : β[R]).re = z :=
rfl
#align quaternion.int_cast_re Quaternion.int_cast_re
@[simp, norm_cast]
theorem int_cast_imI (z : β€) : (z : β[R]).imI = 0 :=
rfl
#align quaternion.int_cast_im_i Quaternion.int_cast_imI
@[simp, norm_cast]
theorem int_cast_imJ (z : β€) : (z : β[R]).imJ = 0 :=
rfl
#align quaternion.int_cast_im_j Quaternion.int_cast_imJ
@[simp, norm_cast]
theorem int_cast_imK (z : β€) : (z : β[R]).imK = 0 :=
rfl
#align quaternion.int_cast_im_k Quaternion.int_cast_imK
@[simp, norm_cast]
theorem int_cast_im (z : β€) : (z : β[R]).im = 0 :=
rfl
#align quaternion.int_cast_im Quaternion.int_cast_im
@[norm_cast]
theorem coe_int_cast (z : β€) : β(z : R) = (z : β[R]) :=
rfl
#align quaternion.coe_int_cast Quaternion.coe_int_cast
theorem coe_injective : Function.Injective (coe : R β β[R]) :=
QuaternionAlgebra.coe_injective
#align quaternion.coe_injective Quaternion.coe_injective
@[simp]
theorem coe_inj {x y : R} : (x : β[R]) = y β x = y :=
coe_injective.eq_iff
#align quaternion.coe_inj Quaternion.coe_inj
@[simp]
theorem smul_re [SMul S R] (s : S) : (s β’ a).re = s β’ a.re :=
rfl
#align quaternion.smul_re Quaternion.smul_re
@[simp]
theorem smul_imI [SMul S R] (s : S) : (s β’ a).imI = s β’ a.imI :=
rfl
#align quaternion.smul_im_i Quaternion.smul_imI
@[simp]
theorem smul_imJ [SMul S R] (s : S) : (s β’ a).imJ = s β’ a.imJ :=
rfl
#align quaternion.smul_im_j Quaternion.smul_imJ
@[simp]
theorem smul_imK [SMul S R] (s : S) : (s β’ a).imK = s β’ a.imK :=
rfl
#align quaternion.smul_im_k Quaternion.smul_imK
@[simp]
theorem smul_im [SMulZeroClass S R] (s : S) : (s β’ a).im = s β’ a.im :=
ext _ _ (smul_zero _).symm rfl rfl rfl
#align quaternion.smul_im Quaternion.smul_im
@[simp, norm_cast]
theorem coe_smul [SMulZeroClass S R] (s : S) (r : R) : (β(s β’ r) : β[R]) = s β’ βr :=
QuaternionAlgebra.coe_smul _ _
#align quaternion.coe_smul Quaternion.coe_smul
theorem coe_commutes : βr * a = a * r :=
QuaternionAlgebra.coe_commutes r a
#align quaternion.coe_commutes Quaternion.coe_commutes
theorem coe_commute : Commute (βr) a :=
QuaternionAlgebra.coe_commute r a
#align quaternion.coe_commute Quaternion.coe_commute
theorem coe_mul_eq_smul : βr * a = r β’ a :=
QuaternionAlgebra.coe_mul_eq_smul r a
#align quaternion.coe_mul_eq_smul Quaternion.coe_mul_eq_smul
theorem mul_coe_eq_smul : a * r = r β’ a :=
QuaternionAlgebra.mul_coe_eq_smul r a
#align quaternion.mul_coe_eq_smul Quaternion.mul_coe_eq_smul
@[simp]
theorem algebraMap_def : β(algebraMap R β[R]) = coe :=
rfl
#align quaternion.algebra_map_def Quaternion.algebraMap_def
theorem smul_coe : x β’ (y : β[R]) = β(x * y) :=
QuaternionAlgebra.smul_coe x y
#align quaternion.smul_coe Quaternion.smul_coe
instance : Module.Finite R β[R] :=
QuaternionAlgebra.Module.finite _ _
instance : Module.Free R β[R] :=
QuaternionAlgebra.Module.free _ _
theorem dim_eq_four [StrongRankCondition R] : Module.rank R β[R] = 4 :=
QuaternionAlgebra.dim_eq_four _ _
#align quaternion.dim_eq_four Quaternion.dim_eq_four
theorem finrank_eq_four [StrongRankCondition R] : FiniteDimensional.finrank R β[R] = 4 :=
QuaternionAlgebra.finrank_eq_four _ _
#align quaternion.finrank_eq_four Quaternion.finrank_eq_four
/-- Quaternion conjugate. -/
def conj : β[R] ββ[R] β[R] :=
QuaternionAlgebra.conj
#align quaternion.conj Quaternion.conj
@[simp]
theorem conj_re : a.conj.re = a.re :=
rfl
#align quaternion.conj_re Quaternion.conj_re
@[simp]
theorem conj_imI : a.conj.imI = -a.imI :=
rfl
#align quaternion.conj_im_i Quaternion.conj_imI
@[simp]
theorem conj_imJ : a.conj.imJ = -a.imJ :=
rfl
#align quaternion.conj_im_j Quaternion.conj_imJ
@[simp]
theorem conj_imK : a.conj.imK = -a.imK :=
rfl
#align quaternion.conj_im_k Quaternion.conj_imK
@[simp]
theorem conj_im : a.conj.im = -a.im :=
a.im_conj
#align quaternion.conj_im Quaternion.conj_im
@[simp]
theorem conj_conj : a.conj.conj = a :=
a.conj_conj
#align quaternion.conj_conj Quaternion.conj_conj
@[simp]
theorem conj_add : (a + b).conj = a.conj + b.conj :=
a.conj_add b
#align quaternion.conj_add Quaternion.conj_add
@[simp]
theorem conj_mul : (a * b).conj = b.conj * a.conj :=
a.conj_mul b
#align quaternion.conj_mul Quaternion.conj_mul
theorem conj_conj_mul : (a.conj * b).conj = b.conj * a :=
a.conj_conj_mul b
#align quaternion.conj_conj_mul Quaternion.conj_conj_mul
theorem conj_mul_conj : (a * b.conj).conj = b * a.conj :=
a.conj_mul_conj b
#align quaternion.conj_mul_conj Quaternion.conj_mul_conj
theorem self_add_conj' : a + a.conj = β(2 * a.re) :=
a.self_add_conj'
#align quaternion.self_add_conj' Quaternion.self_add_conj'
theorem self_add_conj : a + a.conj = 2 * a.re :=
a.self_add_conj
#align quaternion.self_add_conj Quaternion.self_add_conj
theorem conj_add_self' : a.conj + a = β(2 * a.re) :=
a.conj_add_self'
#align quaternion.conj_add_self' Quaternion.conj_add_self'
theorem conj_add_self : a.conj + a = 2 * a.re :=
a.conj_add_self
#align quaternion.conj_add_self Quaternion.conj_add_self
theorem conj_eq_two_re_sub : a.conj = β(2 * a.re) - a :=
a.conj_eq_two_re_sub
#align quaternion.conj_eq_two_re_sub Quaternion.conj_eq_two_re_sub
theorem commute_conj_self : Commute a.conj a :=
a.commute_conj_self
#align quaternion.commute_conj_self Quaternion.commute_conj_self
theorem commute_self_conj : Commute a a.conj :=
a.commute_self_conj
#align quaternion.commute_self_conj Quaternion.commute_self_conj
theorem commute_conj_conj {a b : β[R]} (h : Commute a b) : Commute a.conj b.conj :=
QuaternionAlgebra.commute_conj_conj h
#align quaternion.commute_conj_conj Quaternion.commute_conj_conj
alias commute_conj_conj β commute.quaternion_conj
#align quaternion.commute.quaternion_conj Quaternion.Commute.quaternion_conj
@[simp, norm_cast]
theorem conj_coe : conj (x : β[R]) = x :=
QuaternionAlgebra.conj_coe x
#align quaternion.conj_coe Quaternion.conj_coe
@[simp]
theorem im_conj : a.im.conj = -a.im :=
QuaternionAlgebra.im_conj _
#align quaternion.im_conj Quaternion.im_conj
@[simp, norm_cast]
theorem conj_nat_cast (n : β) : conj (n : β[R]) = n :=
QuaternionAlgebra.conj_nat_cast _
#align quaternion.conj_nat_cast Quaternion.conj_nat_cast
@[simp, norm_cast]
theorem conj_int_cast (z : β€) : conj (z : β[R]) = z :=
QuaternionAlgebra.conj_int_cast _
#align quaternion.conj_int_cast Quaternion.conj_int_cast
@[simp]
theorem conj_smul [Monoid S] [DistribMulAction S R] (s : S) (a : β[R]) :
conj (s β’ a) = s β’ conj a :=
QuaternionAlgebra.conj_smul _ _
#align quaternion.conj_smul Quaternion.conj_smul
@[simp]
theorem conj_one : conj (1 : β[R]) = 1 :=
conj_coe 1
#align quaternion.conj_one Quaternion.conj_one
theorem eq_re_of_eq_coe {a : β[R]} {x : R} (h : a = x) : a = a.re :=
QuaternionAlgebra.eq_re_of_eq_coe h
#align quaternion.eq_re_of_eq_coe Quaternion.eq_re_of_eq_coe
theorem eq_re_iff_mem_range_coe {a : β[R]} : a = a.re β a β Set.range (coe : R β β[R]) :=
QuaternionAlgebra.eq_re_iff_mem_range_coe
#align quaternion.eq_re_iff_mem_range_coe Quaternion.eq_re_iff_mem_range_coe
section CharZero
variable [NoZeroDivisors R] [CharZero R]
@[simp]
theorem conj_eq_self {a : β[R]} : conj a = a β a = a.re :=
QuaternionAlgebra.conj_eq_self
#align quaternion.conj_eq_self Quaternion.conj_eq_self
@[simp]
theorem conj_eq_neg {a : β[R]} : conj a = -a β a.re = 0 :=
QuaternionAlgebra.conj_eq_neg
#align quaternion.conj_eq_neg Quaternion.conj_eq_neg
end CharZero
theorem conj_mul_eq_coe : conj a * a = (conj a * a).re :=
a.conj_mul_eq_coe
#align quaternion.conj_mul_eq_coe Quaternion.conj_mul_eq_coe
theorem mul_conj_eq_coe : a * conj a = (a * conj a).re :=
a.mul_conj_eq_coe
#align quaternion.mul_conj_eq_coe Quaternion.mul_conj_eq_coe
@[simp]
theorem conj_zero : conj (0 : β[R]) = 0 :=
QuaternionAlgebra.conj_zero
#align quaternion.conj_zero Quaternion.conj_zero
@[simp]
theorem conj_neg : (-a).conj = -a.conj :=
a.conj_neg
#align quaternion.conj_neg Quaternion.conj_neg
@[simp]
theorem conj_sub : (a - b).conj = a.conj - b.conj :=
a.conj_sub b
#align quaternion.conj_sub Quaternion.conj_sub
@[simp]
theorem conj_pow (n : β) : conj (a ^ n) = conj a ^ n :=
a.conj_pow n
#align quaternion.conj_pow Quaternion.conj_pow
open MulOpposite
/-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/
def conjAe : β[R] ββ[R] β[R]α΅α΅α΅ :=
QuaternionAlgebra.conjAe
#align quaternion.conj_ae Quaternion.conjAe
@[simp]
theorem coe_conjAe : β(conjAe : β[R] ββ[R] β[R]α΅α΅α΅) = op β conj :=
rfl
#align quaternion.coe_conj_ae Quaternion.coe_conjAe
/-- Square of the norm. -/
def normSq : β[R] β*β R where
toFun a := (a * a.conj).re
map_zero' := by rw [conj_zero, MulZeroClass.zero_mul, zero_re]
map_one' := by rw [conj_one, one_mul, one_re]
map_mul' x y :=
coe_injective <| by
conv_lhs =>
rw [β mul_conj_eq_coe, conj_mul, mul_assoc, β mul_assoc y, y.mul_conj_eq_coe, coe_commutes,
β mul_assoc, x.mul_conj_eq_coe, β coe_mul]
#align quaternion.norm_sq Quaternion.normSq
theorem normSq_def : normSq a = (a * a.conj).re :=
rfl
#align quaternion.norm_sq_def Quaternion.normSq_def
theorem normSq_def' : normSq a = a.1 ^ 2 + a.2 ^ 2 + a.3 ^ 2 + a.4 ^ 2 := by
simp only [norm_sq_def, sq, mul_neg, sub_neg_eq_add, mul_re, conj_re, conj_im_i, conj_im_j,
conj_im_k]
#align quaternion.norm_sq_def' Quaternion.normSq_def'
theorem normSq_coe : normSq (x : β[R]) = x ^ 2 := by
rw [norm_sq_def, conj_coe, β coe_mul, coe_re, sq]
#align quaternion.norm_sq_coe Quaternion.normSq_coe
@[simp]
theorem normSq_conj : normSq (conj a) = normSq a := by simp [norm_sq_def']
#align quaternion.norm_sq_conj Quaternion.normSq_conj
@[norm_cast]
theorem normSq_nat_cast (n : β) : normSq (n : β[R]) = n ^ 2 := by rw [β coe_nat_cast, norm_sq_coe]
#align quaternion.norm_sq_nat_cast Quaternion.normSq_nat_cast
@[norm_cast]
theorem normSq_int_cast (z : β€) : normSq (z : β[R]) = z ^ 2 := by rw [β coe_int_cast, norm_sq_coe]
#align quaternion.norm_sq_int_cast Quaternion.normSq_int_cast
@[simp]
theorem normSq_neg : normSq (-a) = normSq a := by simp only [norm_sq_def, conj_neg, neg_mul_neg]
#align quaternion.norm_sq_neg Quaternion.normSq_neg
theorem self_mul_conj : a * a.conj = normSq a := by rw [mul_conj_eq_coe, norm_sq_def]
#align quaternion.self_mul_conj Quaternion.self_mul_conj
theorem conj_mul_self : a.conj * a = normSq a := by rw [β a.commute_self_conj.eq, self_mul_conj]
#align quaternion.conj_mul_self Quaternion.conj_mul_self
theorem im_sq : a.im ^ 2 = -normSq a.im := by
simp_rw [sq, β conj_mul_self, im_conj, neg_mul, neg_neg]
#align quaternion.im_sq Quaternion.im_sq
theorem coe_normSq_add : (normSq (a + b) : β[R]) = normSq a + a * b.conj + b * a.conj + normSq b :=
by simp [β self_mul_conj, mul_add, add_mul, add_assoc]
#align quaternion.coe_norm_sq_add Quaternion.coe_normSq_add
theorem normSq_smul (r : R) (q : β[R]) : normSq (r β’ q) = r ^ 2 * normSq q := by
simp_rw [norm_sq_def, conj_smul, smul_mul_smul, smul_re, sq, smul_eq_mul]
#align quaternion.norm_sq_smul Quaternion.normSq_smul
theorem normSq_add (a b : β[R]) : normSq (a + b) = normSq a + normSq b + 2 * (a * conj b).re :=
calc
normSq (a + b) = normSq a + (a * conj b).re + ((b * conj a).re + normSq b) := by
simp_rw [norm_sq_def, conj_add, add_mul, mul_add, add_re]
_ = normSq a + normSq b + ((a * conj b).re + (b * conj a).re) := by abel
_ = normSq a + normSq b + 2 * (a * conj b).re := by
rw [β add_re, β conj_mul_conj a b, self_add_conj', coe_re]
#align quaternion.norm_sq_add Quaternion.normSq_add
end Quaternion
namespace Quaternion
variable {R : Type _}
section LinearOrderedCommRing
variable [LinearOrderedCommRing R] {a : β[R]}
@[simp]
theorem normSq_eq_zero : normSq a = 0 β a = 0 :=
by
refine' β¨fun h => _, fun h => h.symm βΈ norm_sq.map_zeroβ©
rw [norm_sq_def', add_eq_zero_iff', add_eq_zero_iff', add_eq_zero_iff'] at h
exact ext a 0 (pow_eq_zero h.1.1.1) (pow_eq_zero h.1.1.2) (pow_eq_zero h.1.2) (pow_eq_zero h.2)
all_goals apply_rules [sq_nonneg, add_nonneg]
#align quaternion.norm_sq_eq_zero Quaternion.normSq_eq_zero
theorem normSq_ne_zero : normSq a β 0 β a β 0 :=
not_congr normSq_eq_zero
#align quaternion.norm_sq_ne_zero Quaternion.normSq_ne_zero
@[simp]
theorem normSq_nonneg : 0 β€ normSq a := by
rw [norm_sq_def']
apply_rules [sq_nonneg, add_nonneg]
#align quaternion.norm_sq_nonneg Quaternion.normSq_nonneg
@[simp]
theorem normSq_le_zero : normSq a β€ 0 β a = 0 := by
simpa only [le_antisymm_iff, norm_sq_nonneg, and_true_iff] using @norm_sq_eq_zero _ _ a
#align quaternion.norm_sq_le_zero Quaternion.normSq_le_zero
instance : Nontrivial β[R] where exists_pair_ne := β¨0, 1, mt (congr_arg re) zero_ne_oneβ©
instance : NoZeroDivisors β[R] :=
{ Quaternion.nontrivial with
eq_zero_or_eq_zero_of_mul_eq_zero := fun a b hab =>
have : normSq a * normSq b = 0 := by rwa [β norm_sq.map_mul, norm_sq_eq_zero]
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp normSq_eq_zero.1 normSq_eq_zero.1 }
instance : IsDomain β[R] :=
NoZeroDivisors.to_isDomain _
theorem sq_eq_normSq : a ^ 2 = normSq a β a = a.re :=
by
simp_rw [β conj_eq_self]
obtain rfl | hq0 := eq_or_ne a 0
Β· simp
Β· rw [β conj_mul_self, sq, mul_left_inj' hq0, eq_comm]
#align quaternion.sq_eq_norm_sq Quaternion.sq_eq_normSq
theorem sq_eq_neg_normSq : a ^ 2 = -normSq a β a.re = 0 :=
by
simp_rw [β conj_eq_neg]
obtain rfl | hq0 := eq_or_ne a 0
Β· simp
rw [β conj_mul_self, β mul_neg, β neg_sq, sq, mul_left_inj' (neg_ne_zero.mpr hq0), eq_comm]
#align quaternion.sq_eq_neg_norm_sq Quaternion.sq_eq_neg_normSq
end LinearOrderedCommRing
section Field
variable [LinearOrderedField R] (a b : β[R])
@[simps (config := { attrs := [] })]
instance : Inv β[R] :=
β¨fun a => (normSq a)β»ΒΉ β’ a.conjβ©
instance : GroupWithZero β[R] :=
{ Quaternion.nontrivial,
(by infer_instance : MonoidWithZero
β[R]) with
inv := Inv.inv
inv_zero := by rw [has_inv_inv, conj_zero, smul_zero]
mul_inv_cancel := fun a ha => by
rw [has_inv_inv, Algebra.mul_smul_comm, self_mul_conj, smul_coe,
inv_mul_cancel (norm_sq_ne_zero.2 ha), coe_one] }
@[norm_cast, simp]
theorem coe_inv (x : R) : ((xβ»ΒΉ : R) : β[R]) = xβ»ΒΉ :=
map_invβ (algebraMap R β[R]) _
#align quaternion.coe_inv Quaternion.coe_inv
@[norm_cast, simp]
theorem coe_div (x y : R) : ((x / y : R) : β[R]) = x / y :=
map_divβ (algebraMap R β[R]) x y
#align quaternion.coe_div Quaternion.coe_div
@[norm_cast, simp]
theorem coe_zpow (x : R) (z : β€) : ((x ^ z : R) : β[R]) = x ^ z :=
map_zpowβ (algebraMap R β[R]) x z
#align quaternion.coe_zpow Quaternion.coe_zpow
instance : DivisionRing β[R] :=
{ Quaternion.groupWithZero,
Quaternion.ring with
ratCast := fun q => β(q : R)
ratCast_mk := fun n d hd h => by rw [Rat.cast_mk', coe_mul, coe_int_cast, coe_inv, coe_nat_cast]
qsmul := (Β· β’ Β·)
qsmul_eq_mul' := fun q x => by
rw [coe_mul_eq_smul]
ext <;> exact DivisionRing.qsmul_eq_mul' _ _ }
@[simp, norm_cast]
theorem rat_cast_re (q : β) : (q : β[R]).re = q :=
rfl
#align quaternion.rat_cast_re Quaternion.rat_cast_re
@[simp, norm_cast]
theorem rat_cast_imI (q : β) : (q : β[R]).imI = 0 :=
rfl
#align quaternion.rat_cast_im_i Quaternion.rat_cast_imI
@[simp, norm_cast]
theorem rat_cast_imJ (q : β) : (q : β[R]).imJ = 0 :=
rfl
#align quaternion.rat_cast_im_j Quaternion.rat_cast_imJ
@[simp, norm_cast]
theorem rat_cast_imK (q : β) : (q : β[R]).imK = 0 :=
rfl
#align quaternion.rat_cast_im_k Quaternion.rat_cast_imK
@[simp, norm_cast]
theorem rat_cast_im (q : β) : (q : β[R]).im = 0 :=
rfl
#align quaternion.rat_cast_im Quaternion.rat_cast_im
@[norm_cast]
theorem coe_rat_cast (q : β) : β(q : R) = (q : β[R]) :=
rfl
#align quaternion.coe_rat_cast Quaternion.coe_rat_cast
theorem conj_inv : conj aβ»ΒΉ = (conj a)β»ΒΉ :=
star_inv' a
#align quaternion.conj_inv Quaternion.conj_inv
theorem conj_zpow (z : β€) : conj (a ^ z) = conj a ^ z :=
star_zpowβ a z
#align quaternion.conj_zpow Quaternion.conj_zpow
@[simp, norm_cast]
theorem conj_rat_cast (q : β) : conj (q : β[R]) = q :=
@star_ratCast β[R] _ _ q
#align quaternion.conj_rat_cast Quaternion.conj_rat_cast
@[simp]
theorem normSq_inv : normSq aβ»ΒΉ = (normSq a)β»ΒΉ :=
map_invβ normSq _
#align quaternion.norm_sq_inv Quaternion.normSq_inv
@[simp]
theorem normSq_div : normSq (a / b) = normSq a / normSq b :=
map_divβ normSq a b
#align quaternion.norm_sq_div Quaternion.normSq_div
@[simp]
theorem normSq_zpow (z : β€) : normSq (a ^ z) = normSq a ^ z :=
map_zpowβ normSq a z
#align quaternion.norm_sq_zpow Quaternion.normSq_zpow
@[norm_cast]
theorem normSq_rat_cast (q : β) : normSq (q : β[R]) = q ^ 2 := by rw [β coe_rat_cast, norm_sq_coe]
#align quaternion.norm_sq_rat_cast Quaternion.normSq_rat_cast
end Field
end Quaternion
namespace Cardinal
open Cardinal Quaternion
section QuaternionAlgebra
variable {R : Type _} (cβ cβ : R)
private theorem pow_four [Infinite R] : (#R) ^ 4 = (#R) :=
power_nat_eq (aleph0_le_mk R) <| by simp
#align cardinal.pow_four cardinal.pow_four
/-- The cardinality of a quaternion algebra, as a type. -/
theorem mk_quaternionAlgebra : (#β[R,cβ,cβ]) = (#R) ^ 4 :=
by
rw [mk_congr (QuaternionAlgebra.equivProd cβ cβ)]
simp only [mk_prod, lift_id]
ring
#align cardinal.mk_quaternion_algebra Cardinal.mk_quaternionAlgebra
@[simp]
theorem mk_quaternionAlgebra_of_infinite [Infinite R] : (#β[R,cβ,cβ]) = (#R) := by
rw [mk_quaternion_algebra, pow_four]
#align cardinal.mk_quaternion_algebra_of_infinite Cardinal.mk_quaternionAlgebra_of_infinite
/-- The cardinality of a quaternion algebra, as a set. -/
theorem mk_univ_quaternionAlgebra : (#(Set.univ : Set β[R,cβ,cβ])) = (#R) ^ 4 := by
rw [mk_univ, mk_quaternion_algebra]
#align cardinal.mk_univ_quaternion_algebra Cardinal.mk_univ_quaternionAlgebra
@[simp]
theorem mk_univ_quaternionAlgebra_of_infinite [Infinite R] :
(#(Set.univ : Set β[R,cβ,cβ])) = (#R) := by rw [mk_univ_quaternion_algebra, pow_four]
#align cardinal.mk_univ_quaternion_algebra_of_infinite Cardinal.mk_univ_quaternionAlgebra_of_infinite
end QuaternionAlgebra
section Quaternion
variable (R : Type _) [One R] [Neg R]
/-- The cardinality of the quaternions, as a type. -/
@[simp]
theorem mk_quaternion : (#β[R]) = (#R) ^ 4 :=
mk_quaternionAlgebra _ _
#align cardinal.mk_quaternion Cardinal.mk_quaternion
@[simp]
theorem mk_quaternion_of_infinite [Infinite R] : (#β[R]) = (#R) := by rw [mk_quaternion, pow_four]
#align cardinal.mk_quaternion_of_infinite Cardinal.mk_quaternion_of_infinite
/-- The cardinality of the quaternions, as a set. -/
@[simp]
theorem mk_univ_quaternion : (#(Set.univ : Set β[R])) = (#R) ^ 4 :=
mk_univ_quaternionAlgebra _ _
#align cardinal.mk_univ_quaternion Cardinal.mk_univ_quaternion
@[simp]
theorem mk_univ_quaternion_of_infinite [Infinite R] : (#(Set.univ : Set β[R])) = (#R) := by
rw [mk_univ_quaternion, pow_four]
#align cardinal.mk_univ_quaternion_of_infinite Cardinal.mk_univ_quaternion_of_infinite
end Quaternion
end Cardinal
|
module Language.LSP.CodeAction.AddClause
import Core.Context
import Core.Core
import Core.Env
import Core.Metadata
import Core.UnifyState
import Idris.IDEMode.CaseSplit
import Idris.REPL.Opts
import Idris.Syntax
import Language.JSON
import Language.LSP.CodeAction.Utils
import Language.LSP.Message
import Server.Configuration
import Server.Log
import Server.Utils
buildCodeAction : URI -> TextEdit -> CodeAction
buildCodeAction uri edit =
MkCodeAction
{ title = "Add clause"
, kind = Just RefactorRewrite
, diagnostics = Nothing
, isPreferred = Nothing
, disabled = Nothing
, edit = Just $ MkWorkspaceEdit
{ changes = Just (singleton uri [edit])
, documentChanges = Nothing
, changeAnnotations = Nothing
}
, command = Nothing
, data_ = Nothing
}
export
addClause : Ref LSPConf LSPConfiguration
=> Ref Ctxt Defs
=> Ref MD Metadata
=> Ref ROpts REPLOpts
=> Ref Syn SyntaxInfo
=> Ref UST UState
=> CodeActionParams -> Core (Maybe CodeAction)
addClause params = do
logI AddClause "Checking for \{show params.textDocument.uri} at \{show params.range}"
withSingleLine AddClause params (pure Nothing) $ \line => do
Just clause <- getClause (line + 1) (UN "")
| Nothing => do logD AddClause "No clause defined at line \{show line}"
pure Nothing
-- FIXME: check where the declaration ends instead of putting it one line under the cursor
let range = MkRange (MkPosition (line + 1) 0) (MkPosition (line + 1) 0)
let edit = MkTextEdit range (clause ++ "\n")
pure $ Just $ buildCodeAction params.textDocument.uri edit
|
{-# OPTIONS_GHC -Wall #-}
{-|
Module : AutoBench.Internal.Types
Description : Datatypes and associated helper functions\/defaults.
Copyright : (c) 2018 Martin Handley
License : BSD-style
Maintainer : [email protected]
Stability : Experimental
Portability : GHC
Datatypes used internally throughout AutoBench's implementation and any
associated helper functions\/defaults.
-}
{-
----------------------------------------------------------------------------
<TO-DO>:
----------------------------------------------------------------------------
- 'DataOpts' Discover setting;
- Make AnalOpts in TestSuite a maybe type? In case users don't want to
analyse right away;
- 'UserInputs' PP doesn't wrap;
- 'TestSuite's PP isn't alphabetical by test program name;
-}
module AutoBench.Internal.Types
(
-- * Re-exports
module AutoBench.Types
-- * User inputs
-- ** Test data options
, toHRange -- Convert @Gen l s u :: DataOpts@ to a Haskell range.
-- ** Internal representation of user inputs
, UserInputs(..) -- A data structure maintained by the system to classify user inputs.
, initUserInputs -- Initialise a 'UserInputs' data structure.
-- * Benchmarking
, BenchReport(..) -- A report to summarise the benchmarking phase of testing.
, Coord -- (Input Size, Runtime) results as coordinates for unary test programs.
, Coord3 -- (Input Size, Input Size, Runtime) results as coordinates for binary test programs.
, DataSize(..) -- The size of unary and binary test data.
, SimpleReport(..) -- A simplified version of Criterion's 'Report'. See 'Criterion.Types.Report'.
-- * Test results
, TestReport(..) -- A report to summarise the system's testing phase.
-- ** QuickBench
, QuickReport(..) -- A report to summarise the QuickBench phase of testing.
-- * Statistical analysis
, AnalysisReport(..) -- A report to summarise the system's analysis phase.
, CVStats(..) -- Fitting statistics calculated for regression models per each iteration of cross-validation.
, Improvement -- An efficiency improvement is an ordering between two test programs and a rating
-- 0 <= d <= 1 that corresponds to the percentage of test cases that support the ordering.
, Exp -- Expressions with 'Double' literals.
, LinearCandidate(..) -- The details of a regression model necessary to fit it to a given dataset.
, LinearFit(..) -- A regression model's fitting statistics and helper functions: predicting y-coordinates, pretty printing.
, SimpleResults(..) -- Simple statistical analysis results for each test program.
, numPredictors -- Number of predictors for each type of model.
, simpleReportToCoord -- Convert a 'SimpleReport' to a (input size(s), runtime) coordinate, i.e., 'Coord' or 'Coord3'.
, simpleReportsToCoords -- Convert a list of 'SimpleReport' to a (input size(s), runtime) coordinate, i.e., 'Coord' or 'Coord3'.
-- ** QuickBench
, QuickAnalysis(..) -- A report to summarise the system's analysis phase for QuickBenching.
, QuickResults(..) -- Simple statistical analysis results for each test program for QuickBenching.
-- * Errors
-- ** System errors
, SystemError(..) -- System errors.
-- ** Input errors
, InputError(..) -- User input errors.
) where
import Control.Exception.Base (Exception)
import Criterion.Types (OutlierEffect(..))
import Data.Either (partitionEithers)
import Numeric.LinearAlgebra (Vector)
import qualified AutoBench.Internal.Expr as E
import AutoBench.Types -- Re-export.
import AutoBench.Internal.AbstractSyntax
( HsType
, Id
, ModuleElem(..)
, TypeString
)
-- * User inputs
-- ** Test suites
-- | Convert @Gen l s u :: DataOpts@ to a Haskell range.
toHRange :: DataOpts -> [Int]
toHRange Manual{} = []
toHRange (Gen l s u) = [l, (l + s) .. u]
-- ** Internal representation of user inputs
-- | While user inputs are being analysed by the system, a 'UserInputs' data
-- structure is maintained. The purpose of this data structure is to classify
-- user inputs according to the properties they satisfy. For example, when the
-- system first interprets a user input file, all of its definitions are added
-- to the '_allElems' list. This list is then processed to determine which
-- definitions have function types that are syntactically compatible with the
-- requirements of the system (see 'AutoBench.Internal.StaticChecks').
-- Definitions that are compatible are added to the '_validElems' list, and
-- those that aren't are added to the '_invalidElems' list. Elements in the
-- '_validElems' list are then classified according to, for example, whether
-- they are nullary, unary, or binary functions. This check process continues
-- until all user inputs are classified according to the list headers below.
-- Note that both static ('AutoBench.Internal.StaticChecks') and dynamic
-- ('AutoBench.Internal.DynamicChecks') checks are required to classify user
-- inputs.
--
-- Notice that each /invalid/ definitions has one or more input errors
-- associated with it.
--
-- After the system has processed all user inputs, users can review this data
-- structure to see how the system has classified their inputs, and if any
-- input errors have been generated.
data UserInputs =
UserInputs
{
_allElems :: [(ModuleElem, Maybe TypeString)] -- ^ All definitions in a user input file.
, _invalidElems :: [(ModuleElem, Maybe TypeString)] -- ^ Syntactically invalid definitions (see 'AutoBench.Internal.AbstractSyntax').
, _validElems :: [(Id, HsType)] -- ^ Syntactically valid definitions (see 'AutoBench.Internal.AbstractSyntax').
, _nullaryFuns :: [(Id, HsType)] -- ^ Nullary functions.
, _unaryFuns :: [(Id, HsType)] -- ^ Unary functions.
, _binaryFuns :: [(Id, HsType)] -- ^ Binary functions.
, _arbFuns :: [(Id, HsType)] -- ^ Unary/binary functions whose input types are members of the Arbitrary type class.
, _benchFuns :: [(Id, HsType)] -- ^ Unary/binary functions whose input types are members of the NFData type class.
, _nfFuns :: [(Id, HsType)] -- ^ Unary/binary functions whose result types are members of the NFData type class.
, _invalidData :: [(Id, HsType, [InputError])] -- ^ Invalid user-specified test data.
, _unaryData :: [(Id, HsType, [Int])] -- ^ Valid user-specified test data for unary functions /with size information/.
, _binaryData :: [(Id, HsType, [(Int, Int)])] -- ^ Valid user-specified test data for binary functions /with size information/.
, _invalidTestSuites :: [(Id, [InputError])] -- ^ Invalid test suites.
, _testSuites :: [(Id, TestSuite)] -- ^ Valid test suites.
}
-- | Initialise a 'UserInputs' data structure by specifying the '_allElems'
-- list.
initUserInputs :: [(ModuleElem, Maybe TypeString)] -> UserInputs
initUserInputs xs =
UserInputs
{
_allElems = xs
, _invalidElems = []
, _validElems = []
, _nullaryFuns = []
, _unaryFuns = []
, _binaryFuns = []
, _arbFuns = []
, _benchFuns = []
, _nfFuns = []
, _invalidData = []
, _unaryData = []
, _binaryData = []
, _invalidTestSuites = []
, _testSuites = []
}
-- * Benchmarking
-- | (Input Size, Runtime) results as coordinates for unary test programs.
type Coord = (Double, Double)
-- | (Input Size, Input Size, Runtime) results as coordinates for binary test
-- programs.
type Coord3 = (Double, Double, Double)
-- | The size of unary and binary test data.
data DataSize =
SizeUn Int -- ^ The size of unary test data.
| SizeBin Int Int -- ^ The size of binary test data.
deriving (Ord, Eq)
-- | A report to summarise the benchmarking phase of testing.
data BenchReport =
BenchReport
{
_reports :: [[SimpleReport]] -- ^ Individual reports for each test case, per test program.
, _baselines :: [SimpleReport] -- ^ Baseline measurements (will be empty if '_baseline' is set to @False@).
}
-- | A simplified version of Criterion's 'Report' datatype, see
-- 'Criterion.Types.Report'.
data SimpleReport =
SimpleReport
{
_name :: Id -- ^ Name of test program.
, _size :: DataSize -- ^ Size of test data.
, _samples :: Int -- ^ Number of samples used to calculate statistics below.
, _runtime :: Double -- ^ Estimate runtime.
, _stdDev :: Double -- ^ Estimate standard deviation.
, _outVarEff :: OutlierEffect -- ^ Outlier effect.
, _outVarFrac :: Double -- ^ Outlier effect as a percentage.
}
-- * Test results
-- | A report to summarise the system's testing phase.
data TestReport =
TestReport
{
_tProgs :: [String] -- ^ Names of all test programs.
, _tDataOpts :: DataOpts -- ^ Which test data options were used.
, _tNf :: Bool -- ^ Whether test cases were evaluated to normal form.
, _tGhcFlags :: [String] -- ^ Flags used when compiling the benchmarking file.
, _eql :: Bool -- ^ Whether test programs are semantically equal according to QuickCheck testing.
, _br :: BenchReport -- ^ Benchmarking report.
}
-- ** QuickBench
-- | A report to summarise the QuickBench testing phase.
data QuickReport =
QuickReport
{
_qName :: Id -- ^ Name of test program.
, _qRuntimes :: Either [Coord] [Coord3] -- ^ [(Input size(s), mean runtime)].
} deriving Show
-- * Statistical analysis
-- | A report to summarise the system's analysis phase.
data AnalysisReport =
AnalysisReport
{
_anlys :: [SimpleResults] -- ^ Simple statistical analysis results per test program.
, _imps :: [Improvement] -- ^ Improvement results.
, _blAn :: Maybe SimpleResults -- ^ Analysis of baseline measurements, if applicable.
}
-- | Simple statistical analysis results for each test program.
data SimpleResults =
SimpleResults
{
_srIdt :: Id -- ^ Name of test program.
, _srRaws :: Either [Coord] [Coord3] -- ^ Raw input size/runtime results.
, _srStdDev :: Double -- ^ Standard deviation of all runtime results.
, _srAvgOutVarEff :: OutlierEffect -- ^ Average outlier effect.
, _srAvgPutVarFrac :: Double -- ^ Average outlier effect as a percentage.
, _srFits :: [LinearFit] -- ^ Fitting statistics for each candidate model.
}
-- | An efficiency improvement is an ordering between two test programs and a
-- rating 0 <= d <= 1 that corresponds to the percentage of test cases that
-- support the ordering.
type Improvement = (Id, Ordering, Id, Double)
-- | Fitting statistics calculated for regression models per each iteration of
-- cross-validation. Cumulative fitting statistics are produced by combining
-- 'CVStats' from all iterations, for example, PMSE and PMAE. See 'Stats'.
data CVStats =
CVStats
{
_cv_mse :: Double -- ^ Mean squared error.
, _cv_mae :: Double -- ^ Mean absolute error.
, _cv_ss_tot :: Double -- ^ Total sum of squares.
, _cv_ss_res :: Double -- ^ Residual sum of squares.
} deriving Eq
-- | Expressions with 'Double' literals.
type Exp = E.Expr Double
-- | Each 'LinearType' gives rise to a 'LinearCandidate' that is then fitted to
-- a given data set generating a 'LinearFit'. Unlike a 'LinearType', which
-- just describes a particular regression model, a 'LinearCandidate'
-- encompasses the required information to fit a model to a given data set.
-- For example, it includes '_fxs' to transforms the raw x-coordinates
-- of the dataset before fitting the model, and '_fyhat' which can be used to
-- generate y-coordinates predicted by the model once it has been fit.
--
-- For example, if fitting a 'Log b 1' model, '_fxs' will transform each
-- x-coordinate in the data set to log_b(x) before fitting. Then the linear
-- relationship between the /resulting/ xy-coordinates corresponds to a
-- logarithmic relationship between the /initial/ xy-coordinates.
--
-- When the coefficients of a model are determined by regression analysis,
-- the corresponding 'LinearCandidate' gives rise to a 'LinearFit'.
data LinearCandidate =
LinearCandidate
{
_lct :: LinearType -- ^ The model.
, _fxs :: Vector Double -> Vector Double -- ^ A function to transform x-coords before fitting.
, _fex :: Vector Double -> Exp -- ^ A function to generate the model's equation as an 'Exp'.
, _fyhat :: Vector Double -> Vector Double -> Vector Double -- ^ A function to generate model's predicted y-coords.
}
-- | When a 'LinearCandidate' is fitted to a given data set and its coefficients
-- determined by regression analysis, a 'LinearFit' is generated.
-- A 'LinearFit' primarily includes the fitting statistics ('Stats') of the
-- model to be used to compare it against other models also fitted to the same
-- data set. In order to be able to plot a 'LinearFit' on a results graph
-- as a line of best fit, the '_yhat' function generates y-coordinates
-- predicted by the model for a given set of x-coordinates. To pretty print the
-- 'LinearFit', the '_ex' function generates an 'Exp' expression for the model's
-- equation that has a pretty printing function.
data LinearFit =
LinearFit
{
_lft :: LinearType -- ^ The model.
, _cfs :: Vector Double -- ^ The coefficients of the model.
, _ex :: Exp -- ^ The model's equation as an 'Exp'.
, _yhat :: Vector Double -> Vector Double -- ^ A function to generate the model's predicted y-coords for a given set of x-coords.
, _sts :: Stats -- ^ Fitting statistics.
}
-- | Number of predictors for each type of model.
numPredictors :: LinearType -> Int
numPredictors (Poly k) = k + 1
numPredictors (Log _ k) = k + 1
numPredictors (PolyLog _ k) = k + 1
numPredictors Exp{} = 2
-- | Convert a list of 'SimpleReport's to a list of (input size(s), runtime)
-- coordinates, i.e., a list 'Coord's or 'Coord3's. The name of each
-- simple report is verified against the given test program identifier.
simpleReportsToCoords :: Id -> [SimpleReport] -> Either [Coord] [Coord3]
simpleReportsToCoords idt srs = case (cs, cs3) of
([], _) -> Right cs3
(_, []) -> Left cs
_ -> Left [] -- Shouldn't happen.
where
srs' = filter (\sr -> _name sr == idt) srs
(cs, cs3) = partitionEithers (fmap simpleReportToCoord srs')
-- | Convert a 'SimpleReport' to a (input size(s), runtime) coordinate,
-- i.e., 'Coord' or 'Coord3'.
simpleReportToCoord :: SimpleReport -> Either Coord Coord3
simpleReportToCoord sr = case _size sr of
SizeUn n -> Left (fromIntegral n, _runtime sr)
SizeBin n1 n2 -> Right (fromIntegral n1, fromIntegral n2, _runtime sr)
-- ** QuickBench
-- | A report to summarise the system's analysis phase for QuickBenching.
data QuickAnalysis =
QuickAnalysis
{
_qAnlys :: [QuickResults] -- ^ Quick results per test program.
, _qImps :: [Improvement] -- ^ Improvement results.
}
-- | Simple statistical analysis results for each test program for QuickBenching.
data QuickResults =
QuickResults
{
_qrIdt :: Id -- ^ Name of test program.
, _qrRaws :: Either [Coord] [Coord3] -- ^ Raw input size/runtime results.
, _qrFits :: [LinearFit] -- ^ Fitting statistics for each candidate model.
}
-- * Errors
-- | Errors raised by the system due to implementation failures. These can be
-- generated at any time but are usually used to report unexpected IO results.
-- For example, when dynamically checking user inputs (see
-- 'AutoBench.Internal.UserInputChecks'), system errors are used to relay
-- 'InterpreterError's thrown by functions in the hint package in cases
-- where the system didn't expect errors to result.
data SystemError = InternalErr String
-- Note: needed for the 'Exception' instance.
instance Show SystemError where
show (InternalErr s) = "Internal error: " ++ s ++ "\n** Please report on GitHub **"
instance Exception SystemError
-- ** Input errors
-- | Input errors are generated by the system while analysing user input
-- files. Examples input errors include erroneous test options, invalid test
-- data, and test programs with missing Arbitrary/NFData instances.
--
-- In general, the system always attempts to continue with its execution for as
-- long as possible. Therefore, unless a critical error is encountered, such as
-- a filepath or file access error, it will collate all non-critical input
-- errors. These will then be summarised after the user input file has been
-- fully analysed.
data InputError =
FilePathErr String -- ^ Invalid filepath.
| FileErr String -- ^ File access error.
| TestSuiteErr String -- ^ Invalid test suite.
| DataOptsErr String -- ^ Invalid data options.
| AnalOptsErr String -- ^ Invalid statistical analysis options.
| TypeErr String -- ^ Invalid type signature.
| InstanceErr String -- ^ One or more missing instances
| TestReportErr String -- ^ Invalid test report.
| QuickOptsErr String -- ^ Invalid quick options. See AutoBench.QuickBench.
| QuickBenchErr String -- ^ QuickBench error. See AutoBench.QuickBench.
-- Note: needed for the 'Exception' instance.
instance Show InputError where
show (FilePathErr s) = "File path error: " ++ s
show (FileErr s) = "File error: " ++ s
show (TestSuiteErr s) = "Test suite error: " ++ s
show (DataOptsErr s) = "Test data error: " ++ s
show (AnalOptsErr s) = "Analysis options error: " ++ s
show (TypeErr s) = "Type error: " ++ s
show (InstanceErr s) = "Instance error: " ++ s
show (TestReportErr s) = "Test report error: " ++ s
show (QuickOptsErr s) = "Quick options error: " ++ s
show (QuickBenchErr s) = "QuickBench test error: " ++ s
instance Exception InputError |
cocktailsort <- function(x)
{
lenx <- length(x)
repeat
{
swapped <- FALSE
for(i in 1:(lenx-1))
{
if(x[i] > x[i+1])
{
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
swapped <- TRUE
}
}
if(!swapped) break
swapped <- FALSE
for(i in (lenx-1):1)
{
if(x[i] > x[i+1])
{
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
swapped <- TRUE
}
}
if(!swapped) break
}
x
}
print(cocktailsort(c(5, -1, 101, -4, 0, 1, 8, 6, 2, 3)))
|
(*
* Copyright 2018, Data61, CSIRO
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*)
theory Trace_Schematic_Insts
imports
Main
"ml-helpers/MLUtils"
"ml-helpers/TermPatternAntiquote"
begin
text \<open>
See Trace_Schematic_Insts_Test for tests and examples.
\<close>
locale data_stash
begin
text \<open>
We use this to stash a list of the schematics in the conclusion of the proof
state. After running a method, we can read off the schematic instantiations
(if any) from this list, then restore the original conclusion. Schematic
types are added as "undefined :: ?'a" (for now, we don't worry about types
that don't have sort "type").
TODO: there ought to be some standard way of stashing things into the proof
state. Find out what that is and refactor
\<close>
definition container :: "'a \<Rightarrow> bool \<Rightarrow> bool"
where
"container a b \<equiv> True"
lemma proof_state_add:
"Pure.prop PROP P \<equiv> PROP Pure.prop (container True xs \<Longrightarrow> PROP P)"
by (simp add: container_def)
lemma proof_state_remove:
"PROP Pure.prop (container True xs \<Longrightarrow> PROP P) \<equiv> Pure.prop (PROP P)"
by (simp add: container_def)
lemma rule_add:
"PROP P \<equiv> (container True xs \<Longrightarrow> PROP P)"
by (simp add: container_def)
lemma rule_remove:
"(container True xs \<Longrightarrow> PROP P) \<equiv> PROP P"
by (simp add: container_def)
lemma elim:
"container a b"
by (simp add: container_def)
ML \<open>
signature TRACE_SCHEMATIC_INSTS = sig
type instantiations = (term * (int * term)) list * (typ * typ) list
val trace_schematic_insts:
Method.method -> (instantiations -> unit) -> Method.method
val default_report:
Proof.context -> string -> instantiations -> unit
val trace_schematic_insts_tac:
Proof.context ->
(instantiations -> instantiations -> unit) ->
(thm -> int -> tactic) ->
thm -> int -> tactic
val default_rule_report:
Proof.context -> string -> instantiations -> instantiations -> unit
val skip_dummy_state: Method.method -> Method.method
val make_term_container: term list -> term
val dest_term_container: term -> term list
val attach_proof_annotations: Proof.context -> term list -> thm -> thm
val detach_proof_annotations: Proof.context -> thm -> (int * term) list * thm
val attach_rule_annotations: Proof.context -> term list -> thm -> thm
val detach_rule_result_annotations: Proof.context -> thm -> (int * term) list * thm
end
structure Trace_Schematic_Insts: TRACE_SCHEMATIC_INSTS = struct
\<comment>\<open>
Each pair is a (schematic, instantiation) pair.
The int in the term instantiations is the number of binders which are due to
subgoal bounds.
An explanation: if we instantiate some schematic `?P` within a subgoal like
@{term "\<And>x y. Q"}, it might be instantiated to @{term "\<lambda>a. R a
x"}. We need to capture `x` when reporting the instantiation, so we report
that `?P` has been instantiated to @{term "\<lambda>x y a. R a x"}. In order
to distinguish between the bound `x`, `y`, and `a`, we record that the two
outermost binders are actually due to the subgoal bounds.
\<close>
type instantiations = (term * (int * term)) list * (typ * typ) list
\<comment>\<open>
Work around Isabelle running every apply method on a dummy proof state
\<close>
fun skip_dummy_state method =
fn facts => fn (ctxt, st) =>
case Thm.prop_of st of
Const (@{const_name Pure.prop}, _) $
(Const (@{const_name Pure.term}, _) $ Const (@{const_name Pure.dummy_pattern}, _)) =>
Seq.succeed (Seq.Result (ctxt, st))
| _ => method facts (ctxt, st);
\<comment>\<open>
Utils
\<close>
fun rewrite_state_concl eqn st =
Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of st) (K eqn)) st
\<comment>\<open>
Strip the @{term Pure.prop} that wraps proof state conclusions
\<close>
fun strip_prop ct =
case Thm.term_of ct of
Const (@{const_name "Pure.prop"}, @{typ "prop \<Rightarrow> prop"}) $ _ => Thm.dest_arg ct
| _ => raise CTERM ("strip_prop: head is not Pure.prop", [ct])
fun cconcl_of st =
funpow (Thm.nprems_of st) Thm.dest_arg (Thm.cprop_of st)
|> strip_prop
fun vars_of_term t =
Term.add_vars t []
|> sort_distinct Term_Ord.var_ord
fun type_vars_of_term t =
Term.add_tvars t []
|> sort_distinct Term_Ord.tvar_ord
\<comment>\<open>
Create annotation list
\<close>
fun make_term_container ts =
fold (fn t => fn container =>
Const (@{const_name container},
fastype_of t --> @{typ "bool \<Rightarrow> bool"}) $
t $ container)
(rev ts) @{term "True"}
\<comment>\<open>
Retrieve annotation list
\<close>
fun dest_term_container
(Const (@{const_name container}, _) $ x $ list) =
x :: dest_term_container list
| dest_term_container _ = []
\<comment>\<open>
Attach some terms to a proof state, by "hiding" them in the protected goal.
\<close>
fun attach_proof_annotations ctxt terms st =
let
val container = make_term_container terms
(* FIXME: this might affect st's maxidx *)
val add_eqn =
Thm.instantiate
([],
[((("P", 0), @{typ prop}), cconcl_of st),
((("xs", 0), @{typ bool}), Thm.cterm_of ctxt container)])
@{thm proof_state_add}
in
rewrite_state_concl add_eqn st
end
\<comment>\<open>
Retrieve attached terms from a proof state
\<close>
fun detach_proof_annotations ctxt st =
let
val st_concl = cconcl_of st
val (ccontainer', real_concl) = Thm.dest_implies st_concl
val ccontainer =
ccontainer'
|> Thm.dest_arg (* strip Trueprop *)
|> Thm.dest_arg \<comment>\<open>strip outer @{term "container True"}\<close>
val terms =
ccontainer
|> Thm.term_of
|> dest_term_container
val remove_eqn =
Thm.instantiate
([],
[((("P", 0), @{typ prop}), real_concl),
((("xs", 0), @{typ bool}), ccontainer)])
@{thm proof_state_remove}
in
(map (pair 0) terms, rewrite_state_concl remove_eqn st)
end
\<comment> \<open>
Attaches the given terms to the given thm by stashing them as a new @{term
"container"} premise, *after* all the existing premises (this minimises
disruption when the rule is used with things like `erule`).
\<close>
fun attach_rule_annotations ctxt terms thm =
let
val container = make_term_container terms
(* FIXME: this might affect thm's maxidx *)
val add_eqn =
Thm.instantiate
([],
[((("P", 0), @{typ prop}), Thm.cconcl_of thm),
((("xs", 0), @{typ bool}), Thm.cterm_of ctxt container)])
@{thm rule_add}
in
rewrite_state_concl add_eqn thm
end
\<comment> \<open>
Finds all the variables and type variables in the given thm,
then uses `attach` to stash them in a @{const "container"} within
the thm.
Returns a tuple containing the variables and type variables which were attached this way.
\<close>
fun annotate_with_vars_using (attach: Proof.context -> term list -> thm -> thm) ctxt thm =
let
val tvars = type_vars_of_term (Thm.prop_of thm) |> map TVar
val tvar_carriers = map (fn tvar => Const (@{const_name undefined}, tvar)) tvars
val vars = vars_of_term (Thm.prop_of thm) |> map Var
val annotated_rule = attach ctxt (vars @ tvar_carriers) thm
in ((vars, tvars), annotated_rule) end
val annotate_rule = annotate_with_vars_using attach_rule_annotations
val annotate_proof_state = annotate_with_vars_using attach_proof_annotations
fun split_and_zip_instantiations (vars, tvars) insts =
let val (var_insts, tvar_insts) = chop (length vars) insts
in (vars ~~ var_insts, tvars ~~ map (snd #> fastype_of) tvar_insts) end
\<comment> \<open>
Term version of @{ML "Thm.dest_arg"}.
\<close>
val dest_arg = Term.dest_comb #> snd
\<comment> \<open>
Cousin of @{ML "Term.strip_abs"}.
\<close>
fun strip_all t = (Term.strip_all_vars t, Term.strip_all_body t)
\<comment>\<open>
Matches subgoals of the form:
@{term "\<And>A B C. X \<Longrightarrow> Y \<Longrightarrow> Z \<Longrightarrow> container True data"}
Extracts the instantiation variables from `?data`, and re-applies the surrounding
meta abstractions (in this case `\<And>A B C`).
\<close>
fun dest_instantiation_container_subgoal t =
let
val (vars, goal) = t |> strip_all
val goal = goal |> Logic.strip_imp_concl
in
case goal of
@{term_pat "Trueprop (container True ?data)"} =>
dest_term_container data
|> map (fn t => (length vars, Logic.rlist_abs (rev vars, t))) (* reapply variables *)
|> SOME
| _ => NONE
end
\<comment>\<open>
Finds the first subgoal with a @{term container} conclusion. Extracts the data from
the container and removes the subgoal.
\<close>
fun detach_rule_result_annotations ctxt st =
let
val (idx, data) =
st
|> Thm.prems_of
|> Library.get_index dest_instantiation_container_subgoal
|> OptionExtras.get_or_else (fn () => error "No container subgoal!")
val st' =
st
|> resolve_tac ctxt @{thms elim} (idx + 1)
|> Seq.hd
in
(data, st')
end
\<comment>\<open>
`abs_all n t` wraps the first `n` lambda abstractions in `t` with interleaved
@{term Pure.all} constructors. For example, `abs_all 2 @{term "\<lambda>a b c. P"}` becomes
"\<And>a b. \<lambda>c. P". The resulting term is usually not well-typed.
Used to disambiguate schematic instantiations where the instantiation is a lambda.
\<close>
fun abs_all 0 t = t
| abs_all n (t as (Abs (v, typ, body))) =
if n < 0 then error "Number of lambdas to wrap should be positive." else
Const (@{const_name Pure.all}, dummyT)
$ Abs (v, typ, abs_all (n - 1) body)
| abs_all n _ = error ("Expected at least " ^ Int.toString n ^ " more lambdas.")
fun filtered_instantiation_lines ctxt (var_insts, tvar_insts) =
let
val vars_lines =
map (fn (var, (abs, inst)) =>
if var = inst then "" (* don't show unchanged *) else
" " ^ Syntax.string_of_term ctxt var ^ " => " ^
Syntax.string_of_term ctxt (abs_all abs inst) ^ "\n")
var_insts
val tvars_lines =
map (fn (tvar, inst) =>
if tvar = inst then "" (* don't show unchanged *) else
" " ^ Syntax.string_of_typ ctxt tvar ^ " => " ^
Syntax.string_of_typ ctxt inst ^ "\n")
tvar_insts
in
vars_lines @ tvars_lines
end
\<comment>\<open>
Default callback for black-box method tracing. Prints nontrivial instantiations to tracing output
with the given title line.
\<close>
fun default_report ctxt title insts =
let
val all_insts = String.concat (filtered_instantiation_lines ctxt insts)
(* TODO: add a quiet flag, to suppress output when nothing was instantiated *)
in title ^ "\n" ^ (if all_insts = "" then " (no instantiations)\n" else all_insts)
|> tracing
end
\<comment> \<open>
Default callback for tracing rule applications. Prints nontrivial
instantiations to tracing output with the given title line. Separates
instantiations of rule variables and goal variables.
\<close>
fun default_rule_report ctxt title rule_insts proof_insts =
let
val rule_lines = String.concat (filtered_instantiation_lines ctxt rule_insts)
val rule_lines =
if rule_lines = ""
then "(no rule instantiations)\n"
else "rule instantiations:\n" ^ rule_lines;
val proof_lines = String.concat (filtered_instantiation_lines ctxt proof_insts)
val proof_lines =
if proof_lines = ""
then "(no goal instantiations)\n"
else "goal instantiations:\n" ^ proof_lines;
in title ^ "\n" ^ rule_lines ^ "\n" ^ proof_lines |> tracing end
\<comment> \<open>
`trace_schematic_insts_tac ctxt callback tactic thm idx` does the following:
- Produce a @{term container}-annotated version of `thm`.
- Runs `tactic` on subgoal `idx`, using the annotated version of `thm`.
- If the tactic succeeds, call `callback` with the rule instantiations and the goal
instantiations, in that order.
\<close>
fun trace_schematic_insts_tac
ctxt
(callback: instantiations -> instantiations -> unit)
(tactic: thm -> int -> tactic)
thm idx st =
let
val (rule_vars, annotated_rule) = annotate_rule ctxt thm
val (proof_vars, annotated_proof_state) = annotate_proof_state ctxt st
val st = tactic annotated_rule idx annotated_proof_state
in
st |> Seq.map (fn st =>
let
val (rule_terms, st) = detach_rule_result_annotations ctxt st
val (proof_terms, st) = detach_proof_annotations ctxt st
val rule_insts = split_and_zip_instantiations rule_vars rule_terms
val proof_insts = split_and_zip_instantiations proof_vars proof_terms
val () = callback rule_insts proof_insts
in
st
end
)
end
\<comment>\<open>
ML interface, calls the supplied function with schematic unifications
(will be given all variables, including those that haven't been instantiated).
\<close>
fun trace_schematic_insts (method: Method.method) callback
= fn facts => fn (ctxt, st) =>
let
val (vars, annotated_st) = annotate_proof_state ctxt st
in (* Run the method *)
method facts (ctxt, annotated_st)
|> Seq.map_result (fn (ctxt', annotated_st') => let
(* Retrieve the stashed list, now with unifications *)
val (annotations, st') = detach_proof_annotations ctxt' annotated_st'
val insts = split_and_zip_instantiations vars annotations
(* Report the list *)
val _ = callback insts
in (ctxt', st') end)
end
end
\<close>
end
method_setup trace_schematic_insts = \<open>
let
open Trace_Schematic_Insts
in
(Scan.option (Scan.lift Parse.liberal_name) -- Method.text_closure) >>
(fn (maybe_title, method_text) => fn ctxt =>
trace_schematic_insts
(Method.evaluate method_text ctxt)
(default_report ctxt
(Option.getOpt (maybe_title, "trace_schematic_insts:")))
|> skip_dummy_state
)
end
\<close> "Method combinator to trace schematic variable and type instantiations"
end
|
subroutine zblas3
call zgemm
call zhemm
call zherk
call ztrmm
call ztrsm
call zsymm
call zsyrk
call zher2k
call zsyr2k
end
|
State Before: x y : β
β’ sin 0 = 0 State After: no goals Tactic: simp [sin] |
/-
Copyright (c) 2022 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.abelian.subobject
import category_theory.limits.essentially_small
import category_theory.preadditive.injective
import category_theory.preadditive.generator
import category_theory.preadditive.yoneda.limits
/-!
# A complete abelian category with enough injectives and a separator has an injective coseparator
## Future work
* Once we know that Grothendieck categories have enough injectives, we can use this to conclude
that Grothendieck categories have an injective coseparator.
## References
* [Peter J Freyd, *Abelian Categories* (Theorem 3.37)][freyd1964abelian]
-/
open category_theory category_theory.limits opposite
universes v u
namespace category_theory.abelian
variables {C : Type u} [category.{v} C] [abelian C]
theorem has_injective_coseparator [has_limits C] [enough_injectives C] (G : C)
(hG : is_separator G) : β G : C, injective G β§ is_coseparator G :=
begin
haveI : well_powered C := well_powered_of_is_detector G hG.is_detector,
haveI : has_products_of_shape (subobject (op G)) C := has_products_of_shape_of_small _ _,
let T : C := injective.under (pi_obj (Ξ» P : subobject (op G), unop P)),
refine β¨T, infer_instance, (preadditive.is_coseparator_iff _).2 (Ξ» X Y f hf, _)β©,
refine (preadditive.is_separator_iff _).1 hG _ (Ξ» h, _),
suffices hh : factor_thru_image (h β« f) = 0,
{ rw [β limits.image.fac (h β« f), hh, zero_comp] },
let R := subobject.mk (factor_thru_image (h β« f)).op,
let qβ : image (h β« f) βΆ unop R :=
(subobject.underlying_iso (factor_thru_image (h β« f)).op).unop.hom,
let qβ : unop (R : Cα΅α΅) βΆ pi_obj (Ξ» P : subobject (op G), unop P) :=
section_ (pi.Ο (Ξ» P : subobject (op G), unop P) R),
let q : image (h β« f) βΆ T := qβ β« qβ β« injective.ΞΉ _,
exact zero_of_comp_mono q (by rw [β injective.comp_factor_thru q (limits.image.ΞΉ (h β« f)),
limits.image.fac_assoc, category.assoc, hf, comp_zero])
end
theorem has_projective_separator [has_colimits C] [enough_projectives C] (G : C)
(hG : is_coseparator G) : β G : C, projective G β§ is_separator G :=
begin
obtain β¨T, hTβ, hTββ© := has_injective_coseparator (op G) ((is_separator_op_iff _).2 hG),
exactI β¨unop T, infer_instance, (is_separator_unop_iff _).2 hTββ©
end
end category_theory.abelian
|
[STATEMENT]
lemma HInter_hinsert [simp]: "A\<noteq>0 \<Longrightarrow> \<Sqinter>(A \<triangleleft> a) = a \<sqinter> \<Sqinter>A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A \<noteq> 0 \<Longrightarrow> \<Sqinter>(A \<triangleleft> a) = a \<sqinter> \<Sqinter>A
[PROOF STEP]
by (auto simp: hf_ext HInter_iff [OF hinsert_nonempty]) |
We are one of the leading automotive car service centres in the southern highlands providing quality mechanical repairs and detailing. AJ Automotive is a family owned and operated business which has been running for over 15 years. The Workshop is conveniently located close to the shopping centre of Bowral.
Telephone: 02 4861 4940. Open Monday-Friday from 8am to 5pm. Closed on Public Holidays. |
# This file is a part of Julia. License is MIT: https://julialang.org/license
"""
AbstractInterpreter
An abstract base class that allows multiple dispatch to determine the method of
executing Julia code. The native Julia LLVM pipeline is enabled by using the
`NativeInterpreter` concrete instantiation of this abstract class, others can be
swapped in as long as they follow the AbstractInterpreter API.
All AbstractInterpreters are expected to provide at least the following methods:
- InferenceParams(interp) - return an `InferenceParams` instance
- OptimizationParams(interp) - return an `OptimizationParams` instance
- get_world_counter(interp) - return the world age for this interpreter
- get_inference_cache(interp) - return the runtime inference cache
"""
abstract type AbstractInterpreter; end
"""
InferenceResult
A type that represents the result of running type inference on a chunk of code.
"""
mutable struct InferenceResult
linfo::MethodInstance
argtypes::Vector{Any}
overridden_by_const::BitVector
result # ::Type, or InferenceState if WIP
src #::Union{CodeInfo, OptimizationState, Nothing} # if inferred copy is available
function InferenceResult(linfo::MethodInstance, given_argtypes = nothing)
argtypes, overridden_by_const = matching_cache_argtypes(linfo, given_argtypes)
return new(linfo, argtypes, overridden_by_const, Any, nothing)
end
end
"""
OptimizationParams
Parameters that control optimizer operation.
"""
struct OptimizationParams
inlining::Bool # whether inlining is enabled
inline_cost_threshold::Int # number of CPU cycles beyond which it's not worth inlining
inline_nonleaf_penalty::Int # penalty for dynamic dispatch
inline_tupleret_bonus::Int # extra willingness for non-isbits tuple return types
inline_error_path_cost::Int # cost of (un-optimized) calls in blocks that throw
# Duplicating for now because optimizer inlining requires it.
# Keno assures me this will be removed in the near future
MAX_METHODS::Int
MAX_TUPLE_SPLAT::Int
MAX_UNION_SPLITTING::Int
function OptimizationParams(;
inlining::Bool = inlining_enabled(),
inline_cost_threshold::Int = 100,
inline_nonleaf_penalty::Int = 1000,
inline_tupleret_bonus::Int = 400,
inline_error_path_cost::Int = 20,
max_methods::Int = 3,
tuple_splat::Int = 32,
union_splitting::Int = 4,
)
return new(
inlining,
inline_cost_threshold,
inline_nonleaf_penalty,
inline_tupleret_bonus,
inline_error_path_cost,
max_methods,
tuple_splat,
union_splitting,
)
end
end
"""
InferenceParams
Parameters that control type inference operation.
"""
struct InferenceParams
ipo_constant_propagation::Bool
aggressive_constant_propagation::Bool
# don't consider more than N methods. this trades off between
# compiler performance and generated code performance.
# typically, considering many methods means spending lots of time
# obtaining poor type information.
# It is important for N to be >= the number of methods in the error()
# function, so we can still know that error() is always Bottom.
MAX_METHODS::Int
# the maximum number of union-tuples to swap / expand
# before computing the set of matching methods
MAX_UNION_SPLITTING::Int
# the maximum number of union-tuples to swap / expand
# when inferring a call to _apply
MAX_APPLY_UNION_ENUM::Int
# parameters limiting large (tuple) types
TUPLE_COMPLEXITY_LIMIT_DEPTH::Int
# when attempting to inlining _apply, abort the optimization if the tuple
# contains more than this many elements
MAX_TUPLE_SPLAT::Int
function InferenceParams(;
ipo_constant_propagation::Bool = true,
aggressive_constant_propagation::Bool = false,
max_methods::Int = 3,
union_splitting::Int = 4,
apply_union_enum::Int = 8,
tupletype_depth::Int = 3,
tuple_splat::Int = 32,
)
return new(
ipo_constant_propagation,
aggressive_constant_propagation,
max_methods,
union_splitting,
apply_union_enum,
tupletype_depth,
tuple_splat,
)
end
end
"""
NativeInterpreter
This represents Julia's native type inference algorithm and codegen backend.
It contains many parameters used by the compilation pipeline.
"""
struct NativeInterpreter <: AbstractInterpreter
# Cache of inference results for this particular interpreter
cache::Vector{InferenceResult}
# The world age we're working inside of
world::UInt
# Parameters for inference and optimization
inf_params::InferenceParams
opt_params::OptimizationParams
function NativeInterpreter(world::UInt = get_world_counter();
inf_params = InferenceParams(),
opt_params = OptimizationParams(),
)
# Sometimes the caller is lazy and passes typemax(UInt).
# we cap it to the current world age
if world == typemax(UInt)
world = get_world_counter()
end
# If they didn't pass typemax(UInt) but passed something more subtly
# incorrect, fail out loudly.
@assert world <= get_world_counter()
return new(
# Initially empty cache
Vector{InferenceResult}(),
# world age counter
world,
# parameters for inference and optimization
inf_params,
opt_params,
)
end
end
# Quickly and easily satisfy the AbstractInterpreter API contract
InferenceParams(ni::NativeInterpreter) = ni.inf_params
OptimizationParams(ni::NativeInterpreter) = ni.opt_params
get_world_counter(ni::NativeInterpreter) = ni.world
get_inference_cache(ni::NativeInterpreter) = ni.cache
code_cache(ni::NativeInterpreter) = WorldView(GLOBAL_CI_CACHE, ni.world)
"""
lock_mi_inference(ni::NativeInterpreter, mi::MethodInstance)
Hint that `mi` is in inference to help accelerate bootstrapping. This helps limit the amount of wasted work we might do when inference is working on initially inferring itself by letting us detect when inference is already in progress and not running a second copy on it. This creates a data-race, but the entry point into this code from C (jl_type_infer) already includes detection and restriction on recursion, so it is hopefully mostly a benign problem (since it should really only happen during the first phase of bootstrapping that we encounter this flag).
"""
lock_mi_inference(ni::NativeInterpreter, mi::MethodInstance) = (mi.inInference = true; nothing)
"""
See lock_mi_inference
"""
unlock_mi_inference(ni::NativeInterpreter, mi::MethodInstance) = (mi.inInference = false; nothing)
"""
Emit an analysis remark during inference for the current line (`sv.pc`). These annotations are ignored
by the native interpreter, but can be used by external tooling to annotate
inference results.
"""
add_remark!(ni::NativeInterpreter, sv, s) = nothing
may_optimize(ni::NativeInterpreter) = true
may_compress(ni::NativeInterpreter) = true
may_discard_trees(ni::NativeInterpreter) = true
|
args = commandArgs(trailingOnly=TRUE)
if (length(args)==0) {
stop("At least one argument must be supplied (input file).n", call.=FALSE)
inputfile<-"args[1]"
WD<-getwd()
setwd (WD)
outputfile<-"all_lim_167"
library(calibrate)
data1<- read.table (inputfile, header = TRUE)
attach (data1)
data2 <- as.dist(data1) #this gives a triangular matrix dist 2 is triangular matrix
output1<-cmdscale(data2, k = 2, eig = FALSE, add = FALSE, x.ret = FALSE)
pdf (file =paste(outputfile,"_mds.pdf", sep=""), width =10, height = 10, pointsize =12)
plot (output1[,1], output1[,2], col = "aquamarine4", pch = 20, asp = 1, xlab="Component1", ylab="Component2", main= paste("MDS off:",inputfile))
text(output1[,1], output1[,2], rownames(output1), cex = 0.8, col = "black")
dev.off()
q()
N
|
\documentclass[]{article}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage[hypcap=false]{caption}
\usepackage{graphicx}
\usepackage{hyperref}
\hypersetup{
hidelinks
}
\title{Data Analytics Capstone: Reading 3-A}
\author{Brandon Hosley}
\date{\today}
\begin{document}
\maketitle
\section{Summary}
Sculley et al.\cite{Sculley2015} write about a common software life-cycle problem called technical debt, specifically as it applies to software utilizing machine learning.
The research team make the argument that this type of software is especially vulnerable to the added costs of technical debt due to a number of reasons, including costs associated with increasingly complex models.
When software is improved over its lifetime a lot of vestigial code may remain, and for the 'black box' of most machine learning models this vestigial code is even more difficult to manage.
They describe how data dependencies and digestion can cause debt as the software or input signals change over time.
Another problem characteristic of any machine learning application is the vulnerability to problems caused by feedback both in initial training and if using a model to develop training data that ends up being used to train future models.
Finally, they describe how reproducibility and the inherent non-deterministic nature of training models creates a large amount of development debt.
\section{Analysis}
The arguments presented by the research team are well structured and convincing.
The team proposes two additional potential sources of debt not mentioned above because they are not characteristic of machine learning applications per se, but rather sources of debt that may affect any piece of software.
The team describes a set of anti-patterns that will create technical debt.
The anti-patterns should bear strong consideration for any developer and aren't exclusive or significantly more applicable to machine learning over other types of software.
Similarly the team describes configuration debt,
a type of debt incurred in which certain options are applied sub-optimally.
Not only does this problem apply to any types of software with significant configuration options, the solutions proposed by the team should be considered good practice for any software project.
\clearpage
\bibliographystyle{acm}
\bibliography{\jobname}
\end{document} |
vars = Array{Any,1}()
vals = Array{Any,1}()
c = 0
for line in eachline(STDIN)
if ismatch(r"======", line)
if length(vars) > 0
if c == 0
println(STDOUT, "| " * join(vars, " | ") * " |")
println(STDOUT, "|" * repeat("--|", length(vars)))
c += 1
end
println(STDOUT, "| " * join(vals, " | ") * " |")
empty!(vars)
empty!(vals)
end
elseif ismatch(r"hostname|jobnumber|jobname|ru_wallclock|maxvmem|taskid", chomp(line))
m = match(r"([^ ]+) +([^ ]+)", chomp(line)).captures
push!(vars, m[1])
push!(vals, m[2])
end
end
if length(vars) > 0
if c == 0
println(STDOUT, "| " * join(vars, " | ") * " |")
println(STDOUT, "|" * repeat("--|", length(vars)))
c += 1
end
println(STDOUT, "| " * join(vals, " | ") * " |")
empty!(vars)
empty!(vals)
end
|
Require Import Coq.Reals.Rdefinitions.
Require Import Coq.micromega.Psatz.
Require Import ExtLib.Structures.Applicative.
Require Import ChargeCore.Logics.ILogic.
Require Import ChargeCore.Tactics.Tactics.
Require Import SLogic.Logic.
Require Import SLogic.LTLNotation.
Require Import SLogic.BasicProofRules.
Require Import SMTC.Tactic.
Ltac specialize_arith_hyp H :=
repeat match type of H with
| ?G -> _ =>
let HH := fresh "H" in
assert G as HH by (psatzl R);
specialize (H HH); clear HH
end.
Ltac destruct_ite :=
match goal with
| [ |- context [ if ?e then _ else _ ] ]
=> destruct e
end.
Ltac charge_revert :=
lazymatch goal with
| [ |- ltrue |-- _ ] => fail
| [ |- _ ] =>
first
[ simple eapply landAdj | simple eapply Lemmas.landAdj_true ]
end.
Ltac reason_action_tac :=
repeat rewrite always_now;
repeat rewrite <- landA;
repeat charge_revert;
repeat rewrite starts_impl;
apply reason_action;
let pre_st := fresh "pre_st" in
let post_st := fresh "post_st" in
intros pre_st post_st.
Ltac clear_not_always :=
repeat rewrite landA;
repeat match goal with
| [ |- always ?A //\\ ?B |-- _ ] =>
rewrite landC with (P:=always A); charge_revert
| [ |- ?A //\\ ?B |-- _ ]=>
apply landL2
| [ |- always _ |-- _ ] => fail 1
| [ |- _ |-- _ ] => charge_clear
end; charge_intros.
Local Open Scope LTL_scope.
Ltac exists_val_now name :=
match goal with
|- _ |-- Exists x : _, [!(pure x `= ?e)] //\\ _ =>
apply Exists_with_st with (y:=e); intro name;
charge_intros; charge_split; [ charge_assumption | ]
end.
(* Runs z3 on the goal, and admits the goal if z3 succeeds. *)
Ltac z3_prove :=
smt solve; admit.
|
%test script fgg_2D_experiment.m for the 2D NFFT based on Fast Gaussian
%Gridding.
%
%NOTE: In order for this FGG_2D to work, the C
%file "FGG_Convolution2D.c" must be compiled into a Matlab executable
%(cmex) with the following command: mex FGG_Convolution2D.c
%
%Code by (send correspondence to):
%Matthew Ferrara, Research Mathematician
%AFRL Sensors Directorate Innovative Algorithms Branch (AFRL/RYAT)
%[email protected]
clear all;
close all;
%clc
%path(path, './nfftde');%NFFT mex files from Potts, et al.
% make an "image"
%Note for even lengths, the Nfft routine defines the image-space origin
% at pixel location [Nx/2 + 1, Ny/2 + 1].
% Convention: x counts down rows, y counts L to R columns.
N=16;%even length assumed below...tedious to generalize...
z = zeros(N,N);%
%Make a smiley face:
z(N/2+3,N/2-1 : N/2+1 ) = 1;
z(N/2+2,N/2-2 ) = 1;
z(N/2+2,N/2+2 ) = 1;
z(N/2-1,N/2-1) = 1;
z(N/2+1,N/2) = 1;
z(N/2-1,N/2+1) = 1;
%imagesc(z)
N=[N,N];
img=double(z);
% Now, let's compute a matlab DFT in d dimensions using the "nfft" command.
% Note, use fftshifts to match indexing convention as used above in Pott's
% nfft.
data=fftshift(ifftn(ifftshift(img)));
DFTout = fftshift(fftn(ifftshift(data),N));
z=z(:);
% We need knots on [-1/2, 1-1/Nx]x[-1/2, 1-1/Ny] as fundamental period.
% make square grid of knots for exact comparison to fft
tmpx = linspace(-1/2,1/2 -1/N(1), N(1));% tmpx(end)=[];
tmpy = linspace(-1/2,1/2 -1/N(2), N(2));% tmpy(end)=[];
%this creates N+1 points, then discards point at +0.5.
%store my K knots as a d-by-K matrix (d=2 dimension here)
%...following four lines could be cleverly vectorized, avoiding loop.
[Y,X]=meshgrid(tmpy,tmpx);
knots=[X(:),Y(:)];
Nx=N(1);
Ny=N(2);
%set the desired number of digits of accuracy desired from the NUFFT
%routine:
Desired_accuracy = 6;%6=single precision, 12=double precision.
tic
MattOut_Gauss=FGG_2d_type1(data(:),knots,[Nx,Ny],Desired_accuracy);
imagesc(abs(MattOut_Gauss))
colorbar
title('(Type-I Fast Gaussian Gridding) NFFT output')
disp(['NUFFT evaluated in ',num2str(toc),' seconds'])
MattOut_t2=iFGG_2d_type2(MattOut_Gauss,knots,Desired_accuracy);
MattOut_Gauss=FGG_2d_type1(MattOut_t2(:),knots,[Nx,Ny],Desired_accuracy);
figure
imagesc(abs(MattOut_Gauss))
colorbar
title('(Type-I Fast Gaussian Gridding) NFFT output from Type-II-generated data')
norm(MattOut_t2-z(:))
figure
imagesc(abs(img-MattOut_Gauss))
colorbar
title('Error between DFT and NFFT')
Mean_Error=mean(abs(MattOut_Gauss(:)-DFTout(:))) |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
module GraphBuilder (
shortDistMat,
shortestDists,
joinContext,
EContext(..),
EShortDists(..),
theContextsAndDists,
) where
import Control.DeepSeq (NFData (..))
import Control.Monad (ap, join, liftM2)
import Control.Monad.ST
import Control.Parallel.Strategies
import Data.Graph.Inductive hiding (ap)
import qualified Data.Graph.Inductive.PatriciaTree as GP
import Data.List (sortOn)
import qualified Data.Strict.Tuple as T hiding (uncurry)
import Foreign.C (CInt)
import GHC.Generics
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Devel
data EContext =
EContext
{ vertex :: {-# UNPACK #-} !Int
, dstToCtr :: {-# UNPACK #-} !Double
, dists :: {-# UNPACK #-} !(Vector Double)
, ns :: {-# UNPACK #-} !(Vector Int)
}
deriving (Show, Generic)
instance NFData EContext
data EShortDists =
EShortDists
{ vertex' :: {-# UNPACK #-} !Int
, dists' :: {-# UNPACK #-} !(Vector Double)
}
deriving (Show, Generic)
instance NFData EShortDists
shortDistMat :: Int -> [EShortDists] -> Matrix Double
shortDistMat size' !sdists =
let mat = konst 0 (length', size') :: Matrix Double
length' = length sdists
in runST $ do
m <- unsafeThawMatrix mat
mapM_ (`setRow` m) $ zip sdists [0 ..]
unsafeFreezeMatrix m
where
setRow (e, pt) mat = setMatrix mat pt 0 . asRow . dists' $ e
joinContext :: EContext -> GP.Gr Double Double -> GP.Gr Double Double
joinContext (EContext pt dstCtr edists vs) graph =
let zipped = zip (toList edists) (toList vs)
in (zipped, pt, dstCtr, zipped) & graph
matD2 :: Matrix Double -> Matrix Double
matD2 = join pairwiseD2
theContextsAndDists :: (Int, Int) -- ^ Graph neighborhood size and PCA neighborhood size
-> Int
-> Matrix Double
-> ([EContext], Matrix Double, [Int])
theContextsAndDists (n1, n2) bpt mat =
(makeContexts . theNearest n1 $ mat', extract' . idxs $ idxs'', idxs''')
where
makeContexts = zipWith makeContext [0 :: Int ..] . map unzip
makeContext a (b, c) = EContext a (mat' `atIndex` (a, bpt)) (fromList b) (fromList c)
mat' = matD2 mat
idxs'' = map (toEnum . snd) idxs'
idxs' = (!! bpt) . theNearest n2 $ mat'
idxs''' = map snd idxs'
extract' a = mat ?? (Pos a, All)
theNearest :: Int -> Matrix Double -> [[(Double, Int)]]
theNearest n = filterKNearest . findNearestWithInd
where
findNearestWithInd = helper1 . helper2
filterKNearest = map (take n . filter ((/= 0.0) . fst) . uncurry zip)
helper1 in' = uncurry zip (map toList (T.fst in'), map (map fromEnum . toList) (T.snd in'))
helper2 = strUnzip . map (liftM2 (T.:!:) sortVector sortIndex) . toRows
shortestDists :: [Int] -> GP.Gr Double Double -> [EShortDists]
shortestDists inds g = parMap rseq (clean `ap` (sortIndDumpDist . makeList)) inds
where
clean x' a = EShortDists x' $ fromList a
sortIndDumpDist = map T.snd . sortOn T.fst
makeList = map (Prelude.uncurry (T.:!:)) . join . map (take 1 . unLPath) . flip spTree g
-- UTILITY FUNCTION(S) --
strUnzip :: [T.Pair (Vector Double) (Vector CInt)] -> T.Pair [Vector Double] [Vector CInt]
strUnzip = foldr (\((T.:!:) a b) acc -> ((T.:!:) (a : T.fst acc) (b : T.snd acc))) ((T.:!:) [] [])
-- -- For debugging!
-- remember to import Control.Arrow ((&&&)) when using this function.
-- checkSymRowsCols :: (Container Vector a, Eq a, S.Storable a)
-- => Matrix a
-- -> Bool
-- checkSymRowsCols = uncurry (==) . (map sumElements . toColumns &&& map sumElements . toRows)
|
[STATEMENT]
lemma "Fr_1b \<F> \<Longrightarrow> Fr_2 \<F> \<Longrightarrow> cl \<longrightarrow> ECQ(\<^bold>\<not>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Fr_1b \<F>; Fr_2 \<F>\<rbrakk> \<Longrightarrow> ECQ \<^bold>\<not> \<longleftarrow> (\<forall>P. contains ((\<^bold>\<and>) P\<^sup>c (\<^bold>\<not> P)) (\<^bold>\<not> (\<bullet>P)))
[PROOF STEP]
unfolding Defs
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Fr_1b \<F>; Fr_2 \<F>\<rbrakk> \<Longrightarrow> (\<forall>a. [\<^bold>\<turnstile> \<lambda>w. (\<bullet>a) w = \<^bold>\<bottom> w]) \<longleftarrow> (\<forall>P. contains ((\<^bold>\<and>) P\<^sup>c (\<^bold>\<not> P)) (\<^bold>\<not> (\<bullet>P)))
[PROOF STEP]
by (metis BC_rel Br_Border Br_cl_def bottom_def compl_def eq_ext' meet_def neg_C_def) |
/*
* Copyright 2010 Savarese Software Research Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.savarese.com/software/ApacheLicense-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <ssrc/spatial/distance.h>
#include <array>
#define BOOST_TEST_MODULE DistanceTest
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
using namespace ssrc::spatial;
typedef boost::mpl::list<unsigned int, int, double> coordinate_types;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_0, coordinate_type, coordinate_types) {
typedef NS_TR1::array<coordinate_type, 1> Point;
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1}}, Point{{1}}), 0);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1}}, Point{{2}}), 1);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{48}},
Point{{52}}), 16);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{4}},
Point{{1}}), 9);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_1, coordinate_type, coordinate_types) {
typedef NS_TR1::array<coordinate_type, 2> Point;
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1}},
Point{{1,1}}), 0);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1}},
Point{{2,2}}), 2);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{83,9451}},
Point{{4382,2383}}),
68438025);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_2, coordinate_type, coordinate_types) {
typedef NS_TR1::array<coordinate_type, 3> Point;
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1}},
Point{{1,1,1}}), 0);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1}},
Point{{2,2,2}}), 3);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{9,0,4}},
Point{{100,32,0}}), 9321);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_4, coordinate_type, coordinate_types) {
typedef NS_TR1::array<coordinate_type, 4> Point;
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1,1}},
Point{{1,1,1,1}}), 0);
BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1,1}},
Point{{2,2,2,2}}), 4);
}
|
[STATEMENT]
theorem B_trusts_protocol:
"\<lbrakk>A \<notin> bad; B \<notin> bad; evs \<in> ns_public\<rbrakk> \<Longrightarrow>
Crypt (pubEK B) (Nonce NB) \<in> parts (spies evs) \<longrightarrow>
Says B A (Crypt (pubEK A) \<lbrace>Nonce NA, Nonce NB, Agent B\<rbrace>) \<in> set evs \<longrightarrow>
Says A B (Crypt (pubEK B) \<lbrace>Nonce NA, Agent A\<rbrace>) \<in> set evs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>A \<notin> bad; B \<notin> bad; evs \<in> ns_public\<rbrakk> \<Longrightarrow> Crypt (pubK B) (Nonce NB) \<in> parts (knows Spy evs) \<longrightarrow> Says B A (Crypt (pubK A) \<lbrace>Nonce NA, Nonce NB, Agent B\<rbrace>) \<in> set evs \<longrightarrow> Says A B (Crypt (pubK B) \<lbrace>Nonce NA, Agent A\<rbrace>) \<in> set evs
[PROOF STEP]
by (erule ns_public.induct, auto) |
Also in 2006 , the Washington Post noted " the ADL repeatedly accused " Norman Finkelstein of being a " Holocaust denier " and that " These charges have proved baseless . " Finkelstein 's mother survived the Majdanek concentration camp , his father survived the Auschwitz concentration camp , and most of his family died in the Holocaust
|
[STATEMENT]
lemma proots_card_usphere_eq:
fixes z0::complex and r::real
defines "q\<equiv>[:z0, of_real r:]"
assumes "r>0"
shows "card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
have ?thesis
when "p=0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
have "card (sphere z0 r) = 0" "card (sphere (0::complex) 1) = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card (sphere z0 r) = 0 &&& card (sphere 0 1) = 0
[PROOF STEP]
using infinite_sphere[OF \<open>r>0\<close>,of z0] infinite_sphere[of 1 "0::complex"]
[PROOF STATE]
proof (prove)
using this:
infinite (sphere z0 r)
0 < 1 \<Longrightarrow> infinite (sphere 0 1)
goal (1 subgoal):
1. card (sphere z0 r) = 0 &&& card (sphere 0 1) = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
card (sphere z0 r) = 0
card (sphere 0 1) = 0
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
card (sphere z0 r) = 0
card (sphere 0 1) = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
card (sphere z0 r) = 0
card (sphere 0 1) = 0
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
using that
[PROOF STATE]
proof (prove)
using this:
card (sphere z0 r) = 0
card (sphere 0 1) = 0
p = 0
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
p = 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
p = 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
have ?thesis
when "p\<noteq>0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
apply (rule proots_card_pcompose_bij_eq[OF _ \<open>p\<noteq>0\<close>])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. bij_betw (poly q) (sphere 0 1) (sphere z0 r)
2. degree q = 1
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. bij_betw (poly q) (sphere 0 1) (sphere z0 r)
[PROOF STEP]
unfolding q_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. bij_betw (poly [:z0, complex_of_real r:]) (sphere 0 1) (sphere z0 r)
[PROOF STEP]
using bij_betw_sphere_usphere[OF \<open>r>0\<close>,of z0]
[PROOF STATE]
proof (prove)
using this:
bij_betw (\<lambda>x. complex_of_real r * x + z0) (sphere 0 1) (sphere z0 r)
goal (1 subgoal):
1. bij_betw (poly [:z0, complex_of_real r:]) (sphere 0 1) (sphere z0 r)
[PROOF STEP]
by (auto simp:algebra_simps)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree q = 1
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree q = 1
[PROOF STEP]
unfolding q_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. degree [:z0, complex_of_real r:] = 1
[PROOF STEP]
using \<open>r>0\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r
goal (1 subgoal):
1. degree [:z0, complex_of_real r:] = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
p \<noteq> 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
p = 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
p \<noteq> 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
show "card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))"
[PROOF STATE]
proof (prove)
using this:
p = 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
p \<noteq> 0 \<Longrightarrow> card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal (1 subgoal):
1. card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
card (proots_within p (sphere z0 r)) = card (proots_within (p \<circ>\<^sub>p q) (sphere 0 1))
goal:
No subgoals!
[PROOF STEP]
qed |
// Copyright (c) 2001-2011 Joel de Guzman
// Copyright (c) 2001-2011 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(SPIRIT_KARMA_ENCODING_MARCH_05_2010_0550PM)
#define SPIRIT_KARMA_ENCODING_MARCH_05_2010_0550PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/karma/meta_compiler.hpp>
#include <boost/spirit/home/support/common_terminals.hpp>
namespace boost {
namespace spirit {
///////////////////////////////////////////////////////////////////////////
// Enablers
///////////////////////////////////////////////////////////////////////////
// enables encoding
template <typename CharEncoding>
struct use_directive<karma::domain, tag::char_code<tag::encoding, CharEncoding>>
: mpl::true_ {};
template <typename CharEncoding>
struct is_modifier_directive<karma::domain,
tag::char_code<tag::encoding, CharEncoding>>
: mpl::true_ {};
} // namespace spirit
} // namespace boost
#endif
|
lemma measure_UNION_le: "finite I \<Longrightarrow> (\<And>i. i \<in> I \<Longrightarrow> F i \<in> sets M) \<Longrightarrow> measure M (\<Union>i\<in>I. F i) \<le> (\<Sum>i\<in>I. measure M (F i))" |
function u1_unit(nbit::Int, i::Int, j::Int)
chain(nbit, put(nbit, i=>Rz(0)),
put(nbit, j=>Rz(0)),
put(nbit, (i,j)=>rot(SWAP, 0))
)
end
function u1_circuit(nbit_measure::Int, nbit_virtual::Int, nlayer::Int, nrepeat::Int, entangler_pairs)
circuit = sequence()
nbit_used = nbit_measure + nbit_virtual
for i=1:nrepeat
unit = chain(nbit_used)
for j=1:nlayer
push!(unit, chain(nbit_used, u1_unit(nbit_used, i, j) for (i,j) in entangler_pairs))
for k=1:(i==nrepeat ? nbit_used : nbit_measure)
put(nbit_used, k=>Rz(0))
end
end
push!(circuit, unit)
end
dispatch!(circuit, :random)
end
function model(::Val{:u1}; nbit = 20, V=4, B=4096, nlayer=5, pairs)
nrepeat = (nbit - V)
c = u1_circuit(1, V, nlayer, nrepeat, pairs) |> autodiff(:QC)
chem = QuantumMPS(1, V, 0, c, zero_state(V+1, B), [i%2 for i=1:nbit])
chem
end
|
= = Effects = =
|
import data.quot
import .homotopy_classes
universes v u
open category_theory
local notation f ` β `:80 g:80 := g β« f
namespace homotopy_theory.cofibrations
-- Homotopy equivalences as the weak equivalences of an I-category.
open homotopy_theory.weak_equivalences
variables {C : Type u} [category.{v} C]
[has_initial_object.{v} C] [has_coproducts.{v} C] [I_category.{v} C]
instance homotopy_category.category_with_weak_equivalences :
category_with_weak_equivalences (category_mod_congruence C homotopy_congruence) :=
isomorphisms_as_weak_equivalences
instance I_category.category_with_weak_equivalences : category_with_weak_equivalences C :=
preimage_with_weak_equivalences (quotient_functor C homotopy_congruence)
def homotopy_equivalence {x y : C} (f : x βΆ y) : Prop := is_weq f
lemma homotopic_iff_equal_in_ho {x y : C} {f g : x βΆ y} : f β g β β¦fβ§ = β¦gβ§ :=
by symmetry; apply quotient.eq
lemma homotopy_equivalence_iff {x y : C} {f : x βΆ y} :
homotopy_equivalence f β β g, g β f β π _ β§ f β g β π _ :=
begin
split,
{ intro h, cases h with i hi,
cases quotient.exists_rep i.inv with g hg,
existsi g, split; rw homotopic_iff_equal_in_ho,
{ have := i.hom_inv_id',
rw [hi, βhg] at this, exact this },
{ have := i.inv_hom_id',
rw [hi, βhg] at this, exact this } },
{ intro h, rcases h with β¨g, hβ, hββ©,
refine β¨iso.mk β¦fβ§ β¦gβ§ _ _, rflβ©;
{ dsimp [auto_param], change β¦_β§ = β¦_β§, rw βhomotopic_iff_equal_in_ho,
exact hβ <|> exact hβ } }
end
end homotopy_theory.cofibrations
|
theory Tree_Diameter
imports "../DP_CRelVS"
begin
datatype tree = Node "(int \<times> tree) list"
term 0 (**)
context dp_consistency begin
definition hd\<^sub>T :: "('M, 'a list =='M\<Longrightarrow> 'a) state" where
"hd\<^sub>T \<equiv> lift_3 hd"
definition "cc \<equiv> case_list"
context
includes lifting_syntax
begin
thm hd_def[folded cc_def]
thm list.rel_intros list.rel_induct list.rel_transfer list.rel_inject
thm list.rel_cases list.rel_cong
thm list.rel_flip list.rel_sel
lemma "list_all2 P (x#xs) (y#ys) \<Longrightarrow> P x y \<and> list_all2 P xs ys"
using [[simp_trace]]
by simp
term 0 (**
lemma "crel_vs (list_all2 R ===>\<^sub>T R) hd hd\<^sub>T"
thm lift_3_transfer
unfolding hd\<^sub>T_def
apply transfer_prover_start
apply transfer_step
|
lemma analytic_on_ident [analytic_intros,simp]: "(\<lambda>x. x) analytic_on S" |
import Kenny_comm_alg.ideal_lattice
noncomputable theory
local attribute [instance] classical.prop_decidable
universe u
namespace is_ideal
section avoid_powers
parameters {Ξ± : Type u} [comm_ring Ξ±]
parameters (f : Ξ±) (P : set Ξ±) [hp : is_ideal P]
parameters (hf : β n : β, f^n β P)
include hp hf
private def avoid_powers_aux :
β (M : {S : set Ξ± // is_ideal S β§ P β S β§ β n, f ^ n β S}),
β x, M β€ x β x = M :=
@@zorn.zorn' {S // is_ideal S β§ P β S β§ β n, f^n β S} _ β¨β¨P, hp, set.subset.refl P, hfβ©β© $
Ξ» c x hx hc, β¨β¨{y | β S : {S // is_ideal S β§ P β S β§ β n, f^n β S}, S β c β§ y β S.val},
{ zero_ := β¨x, hx, @@is_ideal.zero _ x.1 x.2.1β©,
add_ := Ξ» x y β¨Sx, hxc, hxβ© β¨Sy, hyc, hyβ©,
or.cases_on (hc Sx Sy hxc hyc)
(Ξ» hxy, β¨Sy, hyc, @@is_ideal.add _ Sy.2.1 (hxy hx) hyβ©)
(Ξ» hyx, β¨Sx, hxc, @@is_ideal.add _ Sx.2.1 hx (hyx hy)β©),
smul := Ξ» x y β¨Sy, hyc, hyβ©,
β¨Sy, hyc, @@is_ideal.mul_left _ Sy.2.1 hyβ© },
Ξ» z hz, β¨x, hx, x.2.2.1 hzβ©,
Ξ» n β¨S, hsc, hfnsβ©, S.2.2.2 n hfnsβ©,
Ξ» S hsc z hzs, β¨S, hsc, hzsβ©β©
def avoid_powers : set Ξ± :=
(classical.some avoid_powers_aux).1
theorem avoid_powers.contains : P β avoid_powers :=
(classical.some avoid_powers_aux).2.2.1
theorem avoid_powers.avoid_powers : β n : β, f^n β avoid_powers :=
(classical.some avoid_powers_aux).2.2.2
def avoid_powers.is_prime_ideal : is_prime_ideal avoid_powers :=
{ ne_univ := Ξ» h,
have h1 : (1:Ξ±) β (set.univ:set Ξ±), from show true, by trivial,
have h2 : (1:Ξ±) β avoid_powers, by rwa h,
avoid_powers.avoid_powers 0 h2,
mem_or_mem_of_mul_mem := Ξ» x y hxy,
have h1 : β x, classical.some avoid_powers_aux β€ x β x = classical.some avoid_powers_aux,
from classical.some_spec avoid_powers_aux,
have hax : avoid_powers β span (insert x avoid_powers),
from set.subset.trans (set.subset_insert x _) subset_span,
have hay : avoid_powers β span (insert y avoid_powers),
from set.subset.trans (set.subset_insert y _) subset_span,
have hax2 : P β span (insert x avoid_powers),
from set.subset.trans avoid_powers.contains hax,
have hay2 : P β span (insert y avoid_powers),
from set.subset.trans avoid_powers.contains hay,
have hnx : (Β¬β n, f^n β span (insert x avoid_powers)) β x β avoid_powers,
from Ξ» h,
have h2 : _ := h1 β¨_, is_ideal_span, hax2, Ξ» n hnfs, h β¨n, hnfsβ©β© hax,
suffices x β span (insert x avoid_powers),
by unfold avoid_powers; rw β h2; exact this,
subset_span $ set.mem_insert x _,
have hny : (Β¬β n, f^n β span (insert y avoid_powers)) β y β avoid_powers,
from Ξ» h,
have h2 : _ := h1 β¨_, is_ideal_span, hay2, Ξ» n hnfs, h β¨n, hnfsβ©β© hay,
suffices y β span (insert y avoid_powers),
by unfold avoid_powers; rw β h2; exact this,
subset_span $ set.mem_insert y _,
begin
haveI ha : is_submodule (avoid_powers f P hf) :=
(classical.some (avoid_powers_aux f P hf)).2.1.to_is_submodule,
by_cases hx : β m : β, f^m β span (insert x (avoid_powers f P hf)),
{ by_cases hy : β n : β, f^n β span (insert y (avoid_powers f P hf)),
{ exfalso,
cases hx with m hx,
cases hy with n hy,
rw span_insert at hx hy,
rcases hx with β¨x1, x2, hx2, hxβ©,
rcases hy with β¨y1, y2, hy2, hyβ©,
haveI ha : is_submodule (avoid_powers f P hf) :=
(classical.some (avoid_powers_aux f P hf)).2.1.to_is_submodule,
rw span_eq_of_is_submodule ha at hx2 hy2,
apply avoid_powers.avoid_powers f P hf (m+n),
exact calc
f ^ (m + n) = (x1 β’ x + x2) * (y1 β’ y + y2) : by rw [pow_add, hx, hy]
... = (x1 * x + x2) * (y1 * y + y2) : rfl
... = (x1 * y1) * (x * y) + (x1 * x) * y2 + (y1 * y) * x2 + x2 * y2 : by ring
... β avoid_powers f P hf :
is_submodule.add
(is_submodule.add
(is_submodule.add
(is_submodule.smul _ hxy)
(is_submodule.smul _ hy2))
(is_submodule.smul _ hx2))
(is_submodule.smul _ hy2) },
{ right,
exact hny hy } },
{ left,
exact hnx hx }
end,
.. (classical.some avoid_powers_aux).2.1 }
end avoid_powers
end is_ideal |
Repaired and painted :
|
# Copyright 2018-2019, Carnegie Mellon University
# See LICENSE for details
Class(implies, AutoFoldExp, rec( computeType := self >> TBool ));
Class(RulesTest, RuleSet, rec(inType := "iCode", outType := "iCode"));
RewriteRules(RulesTest, rec(
float_reduction := ARule(DirectSum, [@(1), @(2, OLCompose, e->ObjId(e.child(1))=Reduction)],
e->[DirectSum(@(2).val, @(1).val)]),
));
Class(RulesEagarEval, RuleSet, rec(inType := "iCode", outType := "iCode"));
RewriteRules(RulesEagarEval, rec(
eagar_eval_eq := Rule([@(1, eq), @(2), @(3).cond( e->e=@(2).val)],
e->let(V(true))),
eagar_eval_ands_1 := Rule([@(1, logic_and),
@(2, Value).cond(e->IsBool(e.v)),
@(3,Value).cond(e->IsBool(e.v))],
e->logic_and(@(2).val, @(3).val)),
eagar_eval_ands_2 := Rule([@(1, logic_and),
@(2, Value).cond(e->IsBool(e.v)),
@(3)],
e->Cond(@(2).val.v, @(3).val, V(false))),
eagar_eval_ands_3 := Rule([@(1, logic_and),
@(2),
@(3, Value).cond(e->IsBool(e.v))],
e->Cond(@(3).val.v, @(2).val, V(false))),
));
update_params := function(cx, d)
cx.opts.params := cx.opts.params::[d];
end;
Class(RulesTranslate, RuleSet, rec(inType := "iCode", outType := "SigmaSPL"));
RewriteRules(RulesTranslate, rec(
abs_inclusion := ARule(logic_and, [@(1,implies), @(2,implies, e->let(
e.args[1].args[1]=@(1).val.args[1].args[1] and #anthesdent must be the same
e.args[1].args[2]=@(1).val.args[1].args[2] and #anthesdent must be the same
((ObjId(e.args[1])=leq and ObjId(@(1).val.args[1])=geq) or
(ObjId(e.args[1])=geq and ObjId(@(1).val.args[1])=leq)) and
e.args[2].args[2]=@(1).val.args[2].args[2]))],
e->[let(x := var.fresh_t("x", T_Real(32)),
i := Ind(1),
PointWise(1, Lambda([x, i], ObjId(@(1).val.args[2])(abs(@(2).val.args[1].args[1]), @(1).val.args[2].args[2]))))]),
ands_translate := ARule(logic_and, [@(1), @(2)],
e-> [let(i := Ind(1), x := var.fresh_t("x", T_Real(32)),
lhs := ObjId(@(1).val), rhs:= ObjId(@(2).val),
OLCompose(
Reduction(2, (a, b)->logic_and(a, b), V(true), False),
DirectSum(
Cond(lhs<>PointWise, PointWise(1, Lambda([x, i], @(1).val)), @(1).val),
Cond(rhs<>PointWise, PointWise(1, Lambda([x, i], @(2).val)), @(2).val) )) )]),
ors_translate := ARule(logic_or, [@(1), @(2)],
e-> [let(i := Ind(1), x := var.fresh_t("x", T_Real(32)),
lhs := ObjId(@(1).val), rhs:= ObjId(@(2).val),
OLCompose(
Reduction(2, (a, b)->logic_or(a, b), V(false), False),
DirectSum(
Cond(lhs<>PointWise, PointWise(1, Lambda([x, i], @(1).val)), @(1).val),
Cond(rhs<>PointWise, PointWise(1, Lambda([x, i], @(2).val)), @(2).val) )) )]),
undo_nesting := Rule(@(1,PointWise, e->IsLambda(e.op) and IsSPL(e.op.expr)),
e->Cond(
ObjId(e.op.expr).name="OLCompose", OLCompose(e.op.expr.children()),
ObjId(e.op.expr).name="PointWise", PointWise(e.op.expr.N, Lambda( e.op.expr.op.vars, e.op.expr.op.expr)),
Error("Not Implemented") )),
swap_ds_child := Rule([@(1, DirectSum), @(2).cond(e->ObjId(e)<>OLCompose), [@(3, OLCompose), @(4, Reduction), @(5)]],
e->DirectSum(@(3).val, @(2).val)),
swap_ds_child_1 := ARule(DirectSum, [@(1, PointWise), @(2, OLCompose)],
e->[DirectSum(@(2).val, @(1).val)]),
max_intro := Rule([@(1, OLCompose), @(2, Reduction).cond(e->e.idval=false and e.N=2),
[@(3, DirectSum), @(4, PointWise),
@(5, PointWise).cond(e->ObjId(e.op.expr)=ObjId(@(4).val.op.expr) and
ObjId(e.op.expr) = gt and
e.op.expr.args[2] = @(4).val.op.expr.args[2])]],
e-> PointWise(1, Lambda(@(4).val.op.vars, gt(max(@(4).val.op.expr.args[1], @(5).val.op.expr.args[1]), @(4).val.op.expr.args[2]))) ),
reduce_reduction := Rule([@(1, OLCompose), @(2, Reduction), [@(3, DirectSum), [@(4, OLCompose), @(5, Reduction).cond(e->e.idval=@(2).val.idval), @(6)], @(7)]],
e-> OLCompose(
Reduction(@(2).val.N + @(5).val.N-1, @(2).val.op, @(2).val.idval, @(2).val.isSaturated),
DirectSum(@(6).val, @(7).val) )),
intro_polynomial := Rule([@(1, PointWise), @(2), @(3, Lambda).cond(e->ObjId(e.expr)=gt and
ObjId(e.expr.args[1]) = max and #check max of all abs values
Length(Filtered(List(e.expr.args[1].args, i->ObjId(i)=abs), x->x=false))=0 and
Length(Collect(e.expr.args[2], pow))<>0 #has degree higher than 1
#Length(Filtered(List(Collect(e.expr.args[2], pow), i->IsInt(i.args[2])), x->x=false))=0 # and exponents are numeric
#still need to check for sub within the abs operator to be sure that it is TDistance
)],
(e, cx)->let(d := var.fresh_t("d", TPtr(T_Real(64))),
update_params(cx,d),
degree := ApplyFunc(max, List(Collect(@(3).val.expr.args[2], pow), i->i.args[2])),
TLess(TEvalPolynomial(degree.v, d), TDistance(TInfinityNorm(2)))))
));
TInt_Base.check := v->Cond(IsExp(v), Int(v.ev()),
IsInt(v), v,
IsBool(v), When(v, true, false),
IsDouble(v) and IsInt(IntDouble(v)), IntDouble(v),
IsValue(v) and IsInt(v.v), v.v,
Error("<v> must be an integer or an expression"));
TReal.check := (self, v) >> Cond(
IsExp(v), ReComplex(Complex(code.EvalScalar(v))),
IsInt(v), Double(v),
IsRat(v), v,
IsDouble(v), When(AbsFloat(v) < self.cutoff, 0.0, v),
IsCyc(v), ReComplex(Complex(v)),
IsComplex(v), ReComplex(v),
IsBool(v), When(v, true, false),
Error("<v> must be a double or an expression"));
|
def f : (xs : List Nat) β Nat β xs β [] β Nat
| [], _, _ => _
| [a,b], _, _ => _
| _, _, _ => _
set_option pp.inaccessibleNames true in
def f' : (xs : List Nat) β Nat β xs β [] β Nat
| [], _, _ => _ -- TODO: figure out why hyp `Ne (Ξ± := List Nat) xβΒ² []` needs Ξ±
| [a,b], _, _ => _
| _, _, _ => _
theorem ex1 : p β¨ q β q β¨ p := by
intro h
cases h
trace_state
apply Or.inr
assumption
apply Or.inl
assumption
done
theorem ex2 : {p : Prop} β [Decidable p] β p β decide p = true
| _, isTrue _, _ => _
| _, isFalse hβ, hβ => absurd hβ hβ
theorem ex3 : β {c d : Char}, c = d β c.val = d.val
| _, _, rfl => _
|
using ProjectEuler
using Base.Test
@test ProjectEuler.problem001() == 233168
@test ProjectEuler.problem002() == 4613732
@test ProjectEuler.problem003() == 6857
@test ProjectEuler.problem004() == 906609
@test ProjectEuler.problem005() == 232792560
@test ProjectEuler.problem006() == 25164150
@test ProjectEuler.problem007() == 104743
@test ProjectEuler.problem008() == 23514624000
@test ProjectEuler.problem009() == 31875000 |
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
! This file was ported from Lean 3 source module data.fintype.parity
! leanprover-community/mathlib commit 327c3c0d9232d80e250dc8f65e7835b82b266ea5
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Fintype.Card
import Mathbin.Algebra.Parity
/-!
# The cardinality of `fin (bit0 n)` is even.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variable {Ξ± : Type _}
namespace Fintype
#print Fintype.IsSquare.decidablePred /-
instance IsSquare.decidablePred [Mul Ξ±] [Fintype Ξ±] [DecidableEq Ξ±] :
DecidablePred (IsSquare : Ξ± β Prop) := fun a => Fintype.decidableExistsFintype
#align fintype.is_square.decidable_pred Fintype.IsSquare.decidablePred
-/
end Fintype
#print Fintype.card_fin_even /-
/-- The cardinality of `fin (bit0 n)` is even, `fact` version.
This `fact` is needed as an instance by `matrix.special_linear_group.has_neg`. -/
theorem Fintype.card_fin_even {n : β} : Fact (Even (Fintype.card (Fin (bit0 n)))) :=
β¨by
rw [Fintype.card_fin]
exact even_bit0 _β©
#align fintype.card_fin_even Fintype.card_fin_even
-/
|
lines = readlines("inputs/05.txt")
function day_5(lines)
grid = zeros(Int64, 1000,1000)
pairs = []
for line in lines
x1 = parse(Int64, split(line,',')[1])
y2 = parse(Int64, split(line,',')[3])
mid = split(line,',')[2]
y1 = parse(Int64, split(mid, ' ')[1])
x2 = parse(Int64, split(mid, ' ')[3])
push!(pairs, [x1, y1, x2, y2])
end
for p in pairs
x1, y1, x2, y2 = p
if x1 == x2
for y in min(y1, y2):max(y1, y2)
grid[x1, y] += 1
end
elseif y1 == y2
for x in min(x1, x2):max(x1, x2)
grid[x, y1] += 1
end
end
end
count(i -> i > 1, grid)
end
println(day_5(lines))
|
[STATEMENT]
lemma eint_ord_code [code]:
"eint m \<le> eint n \<longleftrightarrow> m \<le> n"
"eint m < eint n \<longleftrightarrow> m < n"
"q \<le> (\<infinity>::eint) \<longleftrightarrow> True"
"eint m < \<infinity> \<longleftrightarrow> True"
"\<infinity> \<le> eint n \<longleftrightarrow> False"
"(\<infinity>::eint) < q \<longleftrightarrow> False"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ((eint m \<le> eint n) = (m \<le> n) &&& (eint m < eint n) = (m < n) &&& (q \<le> \<infinity>) = True) &&& (eint m < \<infinity>) = True &&& (\<infinity> \<le> eint n) = False &&& (\<infinity> < q) = False
[PROOF STEP]
by simp_all |
[STATEMENT]
lemma trapped_sol_right:
\<comment> \<open>TODO: when building on afp-devel (??? outdated):
\<^url>\<open>https://bitbucket.org/isa-afp/afp-devel/commits/0c3edf9248d5389197f248c723b625c419e4d3eb\<close>\<close>
assumes "compact K" "K \<subseteq> X"
assumes "x \<in> X" "trapped_forward x K"
shows "{0..} \<subseteq> existence_ivl0 x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {0..} \<subseteq> existence_ivl0 x
[PROOF STEP]
proof (rule ccontr)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> {0..} \<subseteq> existence_ivl0 x \<Longrightarrow> False
[PROOF STEP]
assume "\<not> {0..} \<subseteq> existence_ivl0 x"
[PROOF STATE]
proof (state)
this:
\<not> {0..} \<subseteq> existence_ivl0 x
goal (1 subgoal):
1. \<not> {0..} \<subseteq> existence_ivl0 x \<Longrightarrow> False
[PROOF STEP]
from this
[PROOF STATE]
proof (chain)
picking this:
\<not> {0..} \<subseteq> existence_ivl0 x
[PROOF STEP]
obtain t where "0 \<le> t" "t \<notin> existence_ivl0 x"
[PROOF STATE]
proof (prove)
using this:
\<not> {0..} \<subseteq> existence_ivl0 x
goal (1 subgoal):
1. (\<And>t. \<lbrakk>0 \<le> t; t \<notin> existence_ivl0 x\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
0 \<le> t
t \<notin> existence_ivl0 x
goal (1 subgoal):
1. \<not> {0..} \<subseteq> existence_ivl0 x \<Longrightarrow> False
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
0 \<le> t
t \<notin> existence_ivl0 x
[PROOF STEP]
have bdd: "bdd_above (existence_ivl0 x)"
[PROOF STATE]
proof (prove)
using this:
0 \<le> t
t \<notin> existence_ivl0 x
goal (1 subgoal):
1. bdd_above (existence_ivl0 x)
[PROOF STEP]
by (auto intro!: bdd_above_is_intervalI \<open>x \<in> X\<close>)
[PROOF STATE]
proof (state)
this:
bdd_above (existence_ivl0 x)
goal (1 subgoal):
1. \<not> {0..} \<subseteq> existence_ivl0 x \<Longrightarrow> False
[PROOF STEP]
from flow_leaves_compact_ivl_right [OF UNIV_I \<open>x \<in> X\<close> bdd UNIV_I assms(1-2)]
[PROOF STATE]
proof (chain)
picking this:
(\<And>t. \<lbrakk>0 \<le> t; t \<in> existence_ivl0 x; flow0 x t \<notin> K\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
(\<And>t. \<lbrakk>0 \<le> t; t \<in> existence_ivl0 x; flow0 x t \<notin> K\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. False
[PROOF STEP]
by (metis assms(4) trapped_forward_def IntI atLeast_iff image_subset_iff)
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed |
/-
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Authors: Moritz Firsching
-/
import tactic
/-!
# On a lemma of Littlewook and Offord
## TODO
- statement
- proof
- Claim
-/
|
------------------------------------------------------------------------------
-- Test case due to Agda new unifier
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module Agda.NewUnifier where
infixl 7 _Β·_
infixr 5 _β·_
infix 4 _β‘_
-- The universe of discourse/universal domain.
postulate D : Set
-- The identity type on the universe of discourse.
data _β‘_ (x : D) : D β Set where
refl : x β‘ x
postulate
_Β·_ : D β D β D -- FOTC application.
-- List constants.
postulate [] cons head tail null : D -- FOTC partial lists.
-- Definitions
abstract
_β·_ : D β D β D
x β· xs = cons Β· x Β· xs
-- The FOTC lists type (inductive predicate for total lists).
data List : D β Set where
lnil : List []
lcons : β x {xs} β List xs β List (x β· xs)
{-# ATP axioms lnil lcons #-}
postulate
_++_ : D β D β D
++-[] : β ys β [] ++ ys β‘ ys
++-β· : β x xs ys β (x β· xs) ++ ys β‘ x β· (xs ++ ys)
{-# ATP axioms ++-[] ++-β· #-}
++-List : β {xs ys} β List xs β List ys β List (xs ++ ys)
++-List {ys = ys} lnil Lys = prf
where postulate prf : List ([] ++ ys)
{-# ATP prove prf #-}
++-List {ys = ys} (lcons x {xs} Lxs) Lys = prf (++-List Lxs Lys)
where postulate prf : List (xs ++ ys) β List ((x β· xs) ++ ys)
{-# ATP prove prf #-}
|
I know a good few of you guys are lightpainting so I'd be interested to find out what kind of gear you're using?
Maybe Saturday wasn't the best time to post this?
LED isn't the way to go as you get separation in the bulbs which gives a very streaky effect.
I use a 12V fluero tube which I run off a car battery. It's not really powerful enough, but when it's not, I just do shorter exposures, moving the light slower, and link them up in pp.
I used to use LED's but would either get the streaks (even through a built in defuser) mentioned above, or the light was to soft once defused in a softbox.
recently I've been carrying a vagabond and painting with a softbox covering the modelling lamp on a studio light. Been getting super clean results!
This shot was 3 layers. Top. Side. Front(Bonnet grille). Took about 5 minutes in shop layering and killing a few stray light trails from a hole in the back of light box. clean as!
Very clean! This seems to be the way most people are going about light painting recently.
Took two takes. Once for the side of the car, and once for the rear. Ambient sources caused the small highlights.
Yup have looked at these but really want to go fully portable - and as you've mentioned 12v isn't quite powerful enough. In an ideal world I'd like a large portable fluoro for less than Β£100 - but probably asking the impossible!
Been using this for a few years now. You can use it with or without modifiers to suit. It'll burn your eyes out if you want (ie it's quite powerful), or you can turn down the brightness or number of banks of LED's operating to suite. I made it because I couldn't buy anything like it. Still works well although I hardly ever light paint any more.
battery powered, no cables, light enough to comfortably use for long periods.
small softbox fitted, but can have a larger modifier fitted if needed.
No problem. There are lots of different methods you can use, it just depends on what you want. Custom building things isn't for everyone, but I don't mind doing that kind of thing. |
module Dave.Embedding where
open import Dave.Functions
open import Dave.Equality
open import Dave.Isomorphism
infix 0 _β²_
record _β²_ (A B : Set) : Set where
field
to : A β B
from : B β A
fromβto : β (x : A) β from (to x) β‘ x
open _β²_
β²-refl : β {A : Set} β A β² A
β²-refl = record
{
to = Ξ» a β a ;
from = Ξ» b β b ;
fromβto = Ξ» a β refl
}
β²-trans : β {A B C : Set} β A β² B β B β² C β A β² C
β²-trans Aβ²B Bβ²C = record
{
to = Ξ» a β to Bβ²C (to Aβ²B a) ;
from = Ξ» c β from Aβ²B (from Bβ²C c) ;
fromβto = Ξ» a β begin
(from Aβ²B β from Bβ²C) ((to Bβ²C β to Aβ²B) a) β‘β¨β©
from Aβ²B (from Bβ²C (to Bβ²C (to Aβ²B a))) β‘β¨ cong (from Aβ²B) (fromβto Bβ²C (to Aβ²B a)) β©
from Aβ²B (to Aβ²B a) β‘β¨ fromβto Aβ²B a β©
a β
}
β²-antisym : β {A B : Set}
β (Aβ²B : A β² B)
β (Bβ²A : B β² A)
β (to Aβ²B β‘ from Bβ²A)
β (from Aβ²B β‘ to Bβ²A)
β A β B
β²-antisym Aβ²B Bβ²A toβ‘from fromβ‘to = record
{
to = Ξ» a β to Aβ²B a ;
from = Ξ» b β from Aβ²B b ;
fromβto = fromβto Aβ²B;
toβfrom = Ξ» b β begin
to Aβ²B (from Aβ²B b) β‘β¨ cong (Ξ» x β (to Aβ²B (x b))) fromβ‘to β©
to Aβ²B (to Bβ²A b) β‘β¨ cong-app toβ‘from (to Bβ²A b) β©
from Bβ²A (to Bβ²A b) β‘β¨ fromβto Bβ²A b β©
b β
}
module β²-Reasoning where
infix 1 β²-begin_
infixr 2 _β²β¨_β©_
infix 3 _β²-β
β²-begin_ : β {A B : Set}
β A β² B
-----
β A β² B
β²-begin Aβ²B = Aβ²B
_β²β¨_β©_ : β (A : Set) {B C : Set}
β A β² B
β B β² C
-----
β A β² C
A β²β¨ Aβ²B β© Bβ²C = β²-trans Aβ²B Bβ²C
_β²-β : β (A : Set)
-----
β A β² A
A β²-β = β²-refl
open β²-Reasoning
β-implies-β² : β {A B : Set} β A β B β A β² B
β-implies-β² AβB = record
{
to = _β_.to AβB;
from = _β_.from AβB;
fromβto = _β_.fromβto AβB
}
|
! Reads a complete file into memory, making use of allocatable
! deferred-length character strings in Fortran 2003. No assumptions
! are made about the width of the file.
module read_mod
implicit none
integer, parameter :: bufsize = 256
integer, parameter :: default_lun = 15
contains
! read the entire input file into a character variable
subroutine read_file(lun, string)
integer, intent(in) :: lun
character(len=bufsize) :: buf
character(len=:), allocatable, intent(out) :: string
integer :: n, point, stat
if (allocated(string)) then
deallocate(string)
end if
point = 1
allocate(character(len=bufsize) :: string)
do
! read at most BUFSIZE characters
read (unit=lun, iostat=stat, advance='no', fmt='(a)', size=n) buf
print *, 'READ ', n, ' characters'
print *, 'LENGTH of string: ', len(string)
! if stat is negative, but not iostat_end, then end of record
if (is_iostat_end(stat)) then
! exit loop upon reaching EOF
print *, 'EOF'
exit
else
! Append to str, expanding if necessary (adding new_line at EOR)
if (is_iostat_eor(stat)) then
call append(trim(buf) // new_line(string), n + 1)
print *, 'EOR'
else
call append(buf, n)
end if
end if
end do
contains
subroutine append(c, sz)
character(len=*), intent(in) :: c
integer, intent(in) :: sz
character(len=:), allocatable :: tmp
integer :: length, new_length
length = len(string)
! Expand STRING if the resulting string is too long
if (point + sz > length) then
! Expand the string by BUFSIZE
new_length = length + bufsize
! Store contents in TMP while reallocating
allocate(character(len=length) :: tmp)
tmp = string
deallocate(string)
allocate(character(len=new_length) :: string)
! Copy contents back to STRING
string(1:point-1) = tmp
deallocate(tmp)
end if
string(point:point+sz) = c(1:sz)
string(point+sz:) = ''
point = point + sz
end subroutine append
end subroutine read_file
end module read_mod
program read
use iso_fortran_env
use read_mod
implicit none
character(len=bufsize) :: filename
character(len=:), allocatable :: string
integer :: lun, n, stat
! check for a filename
call get_command_argument(1, filename, length=n, status=stat)
! status is positive if get_command_argument failed, zero if
! successful, and negative if the argument was truncated
if (stat > 0) then
lun = input_unit
else if (stat == 0) then
lun = default_lun
open(unit=lun, file=filename)
else
stop 'ERROR: filename too long!'
end if
! Read source into string and print
call read_file(lun, string)
print '(a)', trim(string)
! close the input source
close(lun)
! clean up
if (allocated(string)) then
deallocate(string)
end if
end program read
|
lemma complex_Re_of_nat [simp]: "Re (of_nat n) = of_nat n" |
module Hezarfen
import Hezarfen.Prover
import Hezarfen.Simplify
import Hezarfen.FunDefn
import Hezarfen.Hint
import Language.Reflection.Utils
%access public export
forget' : TT -> Elab Raw
forget' t = case forget t of
Nothing => fail [TextPart "Couldn't forget type"]
Just x => pure x
getCtx : Elab Context
getCtx = Ctx <$> xs <*> pure []
where
xs : Elab (List (TTName, Ty))
xs = do env <- getEnv
pure $ mapMaybe id $ map (\(n, b) =>
MkPair n <$> forget (binderTy b)) env
getTy : TTName -> Elab (TTName, Ty)
getTy n = case !(lookupTyExact n) of
(n, _, ty) => pure (n, !(forget' ty))
add : List TTName -> Elab Context
add xs = (flip Ctx) [] <$> traverse getTy xs
hezarfenExpr' : Context -> Elab ()
hezarfenExpr' c =
do goal <- forget' (snd !getGoal)
fill !(reduceLoop !(breakdown False $ Seq (c <+> !getCtx) goal))
solve
hezarfenExpr : Elab ()
hezarfenExpr = hezarfenExpr' neutral
-- Generate declarations
hezarfenDecl : TTName -> Context -> Elab (FunDefn Raw)
hezarfenDecl n c = case !(lookupTy n) of
[] => fail [TextPart "No type found for", NamePart n]
[(_, _, tt)] =>
do tt' <- normalise !getEnv tt
-- normalization is necessary to change `Not p` into `p -> Void`, etc
ty <- forget' tt'
tm <- breakdown False (Seq (c <+> !getCtx) ty)
proofTerm <- reduceLoop tm
definitionize n proofTerm
_ => fail [TextPart "Ambiguity: multiple types found for", NamePart n]
hezarfen' : TTName -> Context -> Elab ()
hezarfen' n c = defineFunction !(hezarfenDecl n c)
||| Generates a function definition for a previously undefined name.
||| Note that there should already be a type signature for that name.
||| Example usage:
||| ```
||| f : a -> a
||| derive f
||| ```
hezarfen : TTName -> Elab ()
hezarfen n = hezarfen' n neutral
||| Returns reflected proof term directly
hezarfenTT : (shouldReduce : Bool) -> TTName -> Elab TT
hezarfenTT b n =
do (_, _, ty) <- lookupTyExact n
pf <- breakdown False (Seq !getCtx !(forget' ty))
pf' <- (if b then reduceLoop else pure) pf
env <- getEnv
fst <$> check env pf'
decl syntax "derive" {n} = %runElab (hezarfen `{n})
decl syntax "derive'" {n} = %runElab (hezarfen' `{n} !(add !getHints))
decl syntax "obtain" {n} "from" [xs] = %runElab (hezarfen' `{n} !(add xs))
decl syntax "obtain'" {n} "from" [xs] =
%runElab (hezarfen' `{n} !(add (Prelude.List.(++) xs !getHints)))
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Strict #-}
module FourierPinwheel.AsteriskGaussian where
import Data.Array.Repa as R
import Data.Complex
import Data.List as L
import Data.Vector.Generic as VG
import Data.Vector.Storable as VS
import Data.Vector.Unboxed as VU
import DFT.Plan
import Filter.Utils
import FourierPinwheel.Array
import FourierPinwheel.Hypergeo1F1
import Math.Gamma
import Pinwheel.FourierSeries2D
import Utils.Distribution
import Utils.Parallel
-- The envelope in R2 is r ^ alpha, where -2 < alpha < -0.5
{-# INLINE asteriskGaussian #-}
asteriskGaussian ::
( VG.Vector vector (Complex e)
, RealFloat e
, NFData (vector (Complex e))
, Gamma (Complex e)
, Unbox e
)
=> Int
-> Int
-> e
-> e
-> e
-> e
-> [vector (Complex e)]
asteriskGaussian numR2Freqs thetaFreq alpha periodR2 periodEnv std =
parMap
rdeepseq
(\angularFreq ->
let arr =
R.map
(* (sqrt (pi / std) *
exp (fromIntegral angularFreq ^ 2 / (-4) / std) :+
0)) .
centerHollowArray numR2Freqs $
analyticalFourierCoefficients1
numR2Freqs
1
angularFreq
0
alpha
periodR2
periodEnv
in VG.convert . toUnboxed . computeS $ arr)
[-thetaFreq .. thetaFreq]
{-# INLINE asteriskGaussianEnvelope #-}
asteriskGaussianEnvelope ::
(R.Source s (Complex Double))
=> DFTPlan
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> R.Array s DIM2 (Complex Double)
-> IO (VS.Vector (Complex Double))
asteriskGaussianEnvelope plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta filter = do
let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]
inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]
vecs =
asteriskGaussian numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta
filterF <-
dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $
filter
asteriskGaussianF <- dftExecuteBatchP plan planID vecs
fmap VS.concat .
dftExecuteBatchP plan inversePlanID .
parMap rdeepseq (VS.zipWith (*) filterF) $
asteriskGaussianF
-- The envelope is r^alpha X Gaussian
asteriskGaussian2 ::
DFTPlan
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> IO (VS.Vector (Complex Double))
asteriskGaussian2 plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdR2 stdTheta = do
let centerFreq = div numR2Freqs 2
gaussian2D =
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i' :. j') ->
let i = i' - centerFreq
j = j' - centerFreq
in exp
(pi * fromIntegral (i ^ 2 + j ^ 2) /
((-1) * periodR2 ^ 2 * stdR2 ^ 2)) /
(2 * pi * stdR2 ^ 2) :+
0
asteriskGaussianEnvelope
plan
numR2Freqs
thetaFreq
alpha
periodR2
periodEnv
stdTheta
gaussian2D
-- The envelope is r^alpha X LowPass
asteriskGaussianLowPass ::
DFTPlan
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> IO (VS.Vector (Complex Double))
asteriskGaussianLowPass plan numR2Freqs thetaFreq alpha periodR2 periodEnv stdTheta radius = do
let lpf =
fromUnboxed (Z :. numR2Freqs :. numR2Freqs) $
idealLowPassFilter radius periodR2 numR2Freqs
asteriskGaussianEnvelope
plan
numR2Freqs
thetaFreq
alpha
periodR2
periodEnv
stdTheta
lpf
{-# INLINE asteriskGaussianFull #-}
asteriskGaussianFull ::
( VG.Vector vector (Complex e)
, RealFloat e
, NFData (vector (Complex e))
, Gamma (Complex e)
, Unbox e
)
=> Int
-> Int
-> Int
-> e
-> e
-> e
-> e
-> e
-> [vector (Complex e)]
asteriskGaussianFull numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR =
let zeroVec = VG.replicate (numR2Freqs ^ 2) 0
in parMap
rdeepseq
(\(radialFreq, angularFreq) ->
let pinwheel =
analyticalFourierCoefficients1
numR2Freqs
1
angularFreq
radialFreq
alpha
periodR2
periodEnv
-- arr =
-- R.map
-- (* ((-- gaussian1DFreq (fromIntegral angularFreq) stdTheta *
-- gaussian1DFourierCoefficients
-- (fromIntegral radialFreq)
-- (log periodEnv)
-- stdR
-- :+
-- 0) -- *
-- -- cis
-- -- (2 * pi / log periodEnv * fromIntegral radialFreq *
-- -- log 0.5)
-- )) $
-- -- if radialFreq == 0 && angularFreq == 0
-- -- then pinwheel
-- -- else
-- centerHollowArray numR2Freqs pinwheel
arr =
R.map
(* ((1 / (1 + (2 * pi / log periodEnv * fromIntegral radialFreq )^2)) :+ 0)
) $
centerHollowArray numR2Freqs pinwheel
in if angularFreq == 0
then VG.convert . toUnboxed . computeS $ arr
else zeroVec)
[ (radialFreq, angularFreq)
| radialFreq <- [-rFreq .. rFreq]
, angularFreq <- [-thetaFreq .. thetaFreq]
]
{-# INLINE gaussianFull #-}
gaussianFull ::
( VG.Vector vector (Complex e)
, RealFloat e
, NFData (vector (Complex e))
, Gamma (Complex e)
, Unbox e
)
=> Int
-> Int
-> Int
-> e
-> e
-> [vector (Complex e)]
gaussianFull numR2Freqs thetaFreq rFreq periodR2 stdR2 =
let zeroVec = VG.replicate (numR2Freqs ^ 2) 0
periodEnv = periodR2 ^ 2 / 4
in parMap
rdeepseq
(\(radialFreq, angularFreq) ->
if angularFreq == 0 -- && radialFreq == 0
then VG.convert . toUnboxed . computeS $
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i' :. j') ->
let i = fromIntegral $ i' - div numR2Freqs 2
j = fromIntegral $ j' - div numR2Freqs 2
in (gaussian2DFourierCoefficients i j periodR2 stdR2 :+ 0) /
(1 :+ (2 * pi / log periodEnv * fromIntegral radialFreq)^2)
else zeroVec)
[ (radialFreq, angularFreq)
| radialFreq <- [-rFreq .. rFreq]
, angularFreq <- [-thetaFreq .. thetaFreq]
]
{-# INLINE asteriskGaussianFullEnvelope #-}
asteriskGaussianFullEnvelope ::
(R.Source s (Complex Double))
=> DFTPlan
-> Int
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> R.Array s DIM2 (Complex Double)
-> IO (VS.Vector (Complex Double))
asteriskGaussianFullEnvelope plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR filter = do
let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]
inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]
vecs =
asteriskGaussianFull
numR2Freqs
thetaFreq
rFreq
alpha
periodR2
periodEnv
stdTheta
stdR
-- vecs =
-- gaussianFull
-- numR2Freqs
-- thetaFreq
-- rFreq
-- periodR2
-- stdR
filterF <-
dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $
filter
asteriskGaussianF <- dftExecuteBatchP plan planID vecs
fmap VS.concat .
dftExecuteBatchP plan inversePlanID .
parMap rdeepseq (VS.zipWith (*) filterF) $
asteriskGaussianF
-- return . VS.concat $ vecs
-- The envelope is r^alpha X LowPass
asteriskGaussianFullLowPass ::
DFTPlan
-> Int
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> Double
-> IO (VS.Vector (Complex Double))
asteriskGaussianFullLowPass plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR radius = do
let lpf =
fromUnboxed (Z :. numR2Freqs :. numR2Freqs) $
idealLowPassFilter radius periodR2 numR2Freqs
asteriskGaussianFullEnvelope
plan
numR2Freqs
thetaFreq
rFreq
alpha
periodR2
periodEnv
stdTheta
stdR
lpf
-- The envelope is r^alpha X LowPass
asteriskGaussian2Full ::
DFTPlan
-> Int
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> Double
-> IO (VS.Vector (Complex Double))
asteriskGaussian2Full plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR stdR2 = do
let centerFreq = div numR2Freqs 2
gaussian2D =
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i' :. j') ->
let i = fromIntegral $ i' - centerFreq
j = fromIntegral $ j' - centerFreq
in gaussian2DFourierCoefficients i j periodR2 stdR2 :+ 0
asteriskGaussianFullEnvelope
plan
numR2Freqs
thetaFreq
rFreq
alpha
periodR2
periodEnv
stdTheta
stdR
gaussian2D
asteriskGaussianRFull ::
DFTPlan
-> Int
-> Int
-> Int
-> Double
-> Double
-> Double
-> Double
-> Double
-> Double
-> IO (VS.Vector (Complex Double))
asteriskGaussianRFull plan numR2Freqs thetaFreq rFreq alpha periodR2 periodEnv stdTheta stdR stdR2 = do
let planID = DFTPlanID DFT1DG [numR2Freqs, numR2Freqs] [0, 1]
inversePlanID = DFTPlanID IDFT1DG [numR2Freqs, numR2Freqs] [0, 1]
centerFreq = div numR2Freqs 2
gaussian2D =
fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i' :. j') ->
let i = i' - centerFreq
j = j' - centerFreq
in exp
(pi * fromIntegral (i ^ 2 + j ^ 2) /
((-1) * periodR2 ^ 2 * stdR2 ^ 2)) /
(2 * pi * stdR2 ^ 2) :+
0
r =
centerHollowArray' numR2Freqs $ analyticalFourierCoefficients3 numR2Freqs 1 0 0 alpha periodR2 periodEnv
vecs =
asteriskGaussianFull
numR2Freqs
thetaFreq
rFreq
alpha
periodR2
periodEnv
stdTheta
stdR
gaussian2DF <-
dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $
gaussian2D
rF <-
dftExecute plan planID . VU.convert . toUnboxed . computeS . makeFilter2D $
r
let filterF = VS.zipWith (\x y -> x + y ^ 2) gaussian2DF rF
asteriskGaussianF <- dftExecuteBatchP plan planID vecs
fmap VS.concat .
dftExecuteBatchP plan inversePlanID .
parMap rdeepseq (VS.zipWith (*) filterF) $
asteriskGaussianF
|
/-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import algebraic_geometry.prime_spectrum
import ring_theory.polynomial.basic
/-!
The morphism `Spec R[x] --> Spec R` induced by the natural inclusion `R --> R[x]` is an open map.
The main result is the first part of the statement of Lemma 00FB in the Stacks Project.
https://stacks.math.columbia.edu/tag/00FB
-/
open ideal polynomial prime_spectrum set
namespace algebraic_geometry
namespace polynomial
variables {R : Type*} [comm_ring R] {f : polynomial R}
/-- Given a polynomial `f β R[x]`, `image_of_Df` is the subset of `Spec R` where at least one
of the coefficients of `f` does not vanish. Lemma `image_of_Df_eq_comap_C_compl_zero_locus`
proves that `image_of_Df` is the image of `(zero_locus {f})αΆ` under the morphism
`comap C : Spec R[x] β Spec R`. -/
def image_of_Df (f) : set (prime_spectrum R) :=
{p : prime_spectrum R | β i : β , (coeff f i) β p.as_ideal}
lemma is_open_image_of_Df : is_open (image_of_Df f) :=
begin
rw [image_of_Df, set_of_exists (Ξ» i (x : prime_spectrum R), coeff f i β x.val)],
exact is_open_Union (Ξ» i, is_open_basic_open),
end
/-- If a point of `Spec R[x]` is not contained in the vanishing set of `f`, then its image in
`Spec R` is contained in the open set where at least one of the coefficients of `f` is non-zero.
This lemma is a reformulation of `exists_coeff_not_mem_C_inverse`. -/
lemma comap_C_mem_image_of_Df {I : prime_spectrum (polynomial R)}
(H : I β (zero_locus {f} : set (prime_spectrum (polynomial R)))αΆ ) :
comap (polynomial.C : R β+* polynomial R) I β image_of_Df f :=
exists_coeff_not_mem_C_inverse (mem_compl_zero_locus_iff_not_mem.mp H)
/-- The open set `image_of_Df f` coincides with the image of `basic_open f` under the
morphism `CβΊ : Spec R[x] β Spec R`. -/
lemma image_of_Df_eq_comap_C_compl_zero_locus :
image_of_Df f = comap C '' (zero_locus {f})αΆ :=
begin
refine ext (Ξ» x, β¨Ξ» hx, β¨β¨map C x.val, (is_prime_map_C_of_is_prime x.property)β©, β¨_, _β©β©, _β©),
{ rw [mem_compl_eq, mem_zero_locus, singleton_subset_iff],
cases hx with i hi,
exact Ξ» a, hi (mem_map_C_iff.mp a i) },
{ refine subtype.ext (ext (Ξ» x, β¨Ξ» h, _, Ξ» h, subset_span (mem_image_of_mem C.1 h)β©)),
rw β @coeff_C_zero R x _,
exact mem_map_C_iff.mp h 0 },
{ rintro β¨xli, complement, rflβ©,
exact comap_C_mem_image_of_Df complement }
end
/-- The morphism `CβΊ : Spec R[x] β Spec R` is open.
Stacks Project "Lemma 00FB", first part.
https://stacks.math.columbia.edu/tag/00FB
-/
theorem is_open_map_comap_C :
is_open_map (comap (C : R β+* polynomial R)) :=
begin
rintros U β¨s, zβ©,
rw [β compl_compl U, β z, β Union_of_singleton_coe s, zero_locus_Union, compl_Inter, image_Union],
simp_rw [β image_of_Df_eq_comap_C_compl_zero_locus],
exact is_open_Union (Ξ» f, is_open_image_of_Df),
end
end polynomial
end algebraic_geometry
|
(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below *)
Require Import BuiltIn.
Require BuiltIn.
Require HighOrd.
Require set.Set.
Require map.Map.
Require map.Const.
(* Why3 assumption *)
Definition rel (a:Type) (b:Type) := (a* b)%type -> bool.
Parameter power:
forall {a:Type} {a_WT:WhyType a}, (a -> bool) -> (a -> bool) -> bool.
Axiom mem_power :
forall {a:Type} {a_WT:WhyType a},
forall (x:a -> bool) (y:a -> bool),
(set.Set.mem x (power y)) <-> (set.Set.subset x y).
Parameter times:
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}, (a -> bool) ->
(b -> bool) -> (a* b)%type -> bool.
Axiom times_def :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (a1:a -> bool) (b1:b -> bool) (x:a) (y:b),
(set.Set.mem (x, y) (times a1 b1)) <->
((set.Set.mem x a1) /\ (set.Set.mem y b1)).
(* Why3 assumption *)
Definition relations {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b}
(u:a -> bool) (v:b -> bool) : ((a* b)%type -> bool) -> bool :=
power (times u v).
Axiom break_mem_in_add :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (c:(a* b)%type) (s:(a* b)%type -> bool) (x:a) (y:b),
(set.Set.mem c (map.Map.set s (x, y) true)) <->
((c = (x, y)) \/ (set.Set.mem c s)).
Axiom break_power_times :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (r:(a* b)%type -> bool) (u:a -> bool) (v:b -> bool),
(set.Set.mem r (power (times u v))) <-> (set.Set.subset r (times u v)).
Axiom subset_of_times :
forall {a:Type} {a_WT:WhyType a} {b:Type} {b_WT:WhyType b},
forall (r:(a* b)%type -> bool) (u:a -> bool) (v:b -> bool),
(set.Set.subset r (times u v)) <->
forall (x:a) (y:b), (set.Set.mem (x, y) r) ->
(set.Set.mem x u) /\ (set.Set.mem y v).
|
Formal statement is: lemma content_0 [simp]: "content 0 = 0" Informal statement is: The content of the empty set is zero. |
##
## Java Information Dynamics Toolkit (JIDT)
## Copyright (C) 2012, Joseph T. Lizier
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
# Example 6 - Mutual information calculation with dynamic specification of calculator
# This example shows how to write R code to take advantage of the
# common interfaces defined for various information-theoretic calculators.
# Here, we use the common form of the infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
# interface (which is never named here) to write common code into which we can plug
# one of three concrete implementations (kernel estimator, Kraskov estimator or
# linear-Gaussian estimator) by dynamically supplying the class name of
# the concrete implementation.
# Load the rJava library and start the JVM
library("rJava")
.jinit()
# Change location of jar to match yours:
# IMPORTANT -- If using the default below, make sure you have set the working directory
# in R (e.g. with setwd()) to the location of this file (i.e. demos/r) !!
.jaddClassPath("../../infodynamics.jar")
#---------------------
# 1. Properties for the calculation (these are dynamically changeable, you could
# load them in from another properties file):
# The name of the data file (relative to this directory)
datafile <- "../data/4ColsPairedNoisyDependence-1.txt"
# List of column numbers for variables 1 and 2:
# (you can select any columns you wish to be contained in each variable)
variable1Columns <- c(1,2) # array indices start from 1 in R
variable2Columns <- c(3,4)
# The name of the concrete implementation of the interface
# infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
# which we wish to use for the calculation.
# Note that one could use any of the following calculators (try them all!):
# implementingClass <- "infodynamics/measures/continuous/kraskov/MutualInfoCalculatorMultiVariateKraskov1" # MI([1,2], [3,4]) = 0.36353
# implementingClass <- "infodynamics/measures/continuous/kernel/MutualInfoCalculatorMultiVariateKernel"
# implementingClass <- "infodynamics/measures/continuous/gaussian/MutualInfoCalculatorMultiVariateGaussian"
implementingClass <- "infodynamics/measures/continuous/kraskov/MutualInfoCalculatorMultiVariateKraskov1"
#---------------------
# 2. Load in the data
data <- read.csv(datafile, header=FALSE, sep="")
# Pull out the columns from the data set which correspond to each of variable 1 and 2:
variable1 <- data[, variable1Columns]
variable2 <- data[, variable2Columns]
# Extra step to extract the raw values from these data.frame objects:
variable1 <- apply(variable1, 2, function(x) as.numeric(x))
variable2 <- apply(variable2, 2, function(x) as.numeric(x))
#---------------------
# 3. Dynamically instantiate an object of the given class:
# (in fact, all java object creation in octave/matlab is dynamic - it has to be,
# since the languages are interpreted. This makes our life slightly easier at this
# point than it is in demos/java/example6LateBindingMutualInfo where we have to handle this manually)
miCalc<-.jnew(implementingClass)
#---------------------
# 4. Start using the MI calculator, paying attention to only
# call common methods defined in the interface type
# infodynamics.measures.continuous.MutualInfoCalculatorMultiVariate
# not methods only defined in a given implementation class.
# a. Initialise the calculator to use the required number of
# dimensions for each variable:
.jcall(miCalc,"V","initialise", length(variable1Columns), length(variable2Columns))
# b. Supply the observations to compute the PDFs from:
.jcall(miCalc,"V","setObservations",
.jarray(variable1, "[D", dispatch=TRUE),
.jarray(variable2, "[D", dispatch=TRUE))
# c. Make the MI calculation:
miValue <- .jcall(miCalc,"D","computeAverageLocalOfObservations")
cat("MI calculator", implementingClass, "\n computed the joint MI as ",
miValue, "\n")
|
Monument 106 is the earliest securely dated monument at the site , dating to AD 593 . It depicts Ruler 1 .
|
lemmas sums_Im = bounded_linear.sums [OF bounded_linear_Im] |
We understand the basic detoxification needs of drug abusers who have to pace with the advanced business requirements. To work in drug free environment is on prior choice of every employee but maintenance of pure business setup depends upon employees concerns for How To Beat Drug Testing processes. According to toxicologists, FDA approved detoxification programs are the most effective approach on part of those who wish for health safety simultaneously learning How To Beat Drug Testing for desired results.
Present-day needs for knowing How To Beat Drug Tests are increasing with every passing day because this is impossible to achieve dreamed professional chance without beating a drug test. Drug experts immediately analyze health compatible needs of drug abusers and then prescribe some special medication keeping their needs in mind.
After learning How To Beat Drugs Screening, pay attention to these guaranteed methods.
Abstinence: if you are among those who just started drug addiction, you can detoxify your body using Detox Drink. Natural cleansing process takes more than double time to cleanse your system while our guaranteed detoxification products do not waste consumersοΏ½ time when you effectively apply them. This is impossible to eliminate toxins using ineffective home remedies as some of the drug metabolites are of chronic type. And drug abusers with heavy body weight also have to struggle for the cleansing purposes when they remain away from the recommended detoxification products. Using these very products, you can easily learn How To Pass A Drug Test.
It frequently happens when drug abusers experience false positive drug screening results when they indulge into learning How To Pass A Drug Test At Home. In fact, they have no experience of detoxification and they cannot flush out toxins from their systems leaving recommended guidelines far behind. You should combine your efforts with the detoxification products for desired completion of your aim behind knowing everything about How To Pass A Drug Test At Home.
You may substitute your urine specimen with the Synthetic Urine for insurance, random and pre-employment drug screening intentions. However, you should be confident enough at the moment of donating this fake sample so that no one may suspect you. Despite the reality that you are going to submit an alternative specimen of your own fluids, you should not consume drugs at all.
How To Pass A Drug Test Information is not out of reach, the only need is to contact lab technician and enjoy this reliable source of information. Millions of drug abusers have changed overall look of their lives making their lives drug free with the simple applications of FDA approved detoxification products. You can frankly collect How To Pass A Drug Test Information visiting www.passusa.com. This particular website makes you familiar with the detoxification products, their price range and herbal ingredients.
After having command over detoxification information, you can easily beat drug screening test regardless of its form. Just pay attention towards absolute cleansing of your system and learn to believe in the most recommended herbal formulas of detoxification products. |
Formal statement is: lemma measurable_Min_nat[measurable (raw)]: fixes P :: "nat \<Rightarrow> 'a \<Rightarrow> bool" assumes [measurable]: "\<And>i. Measurable.pred M (P i)" shows "(\<lambda>x. Min {i. P i x}) \<in> measurable M (count_space UNIV)" Informal statement is: If $P_i$ is a measurable predicate for each $i$, then the function $x \mapsto \min\{i \mid P_i(x)\}$ is measurable. |
After much planning and preparation Soul Food Farm (http://soulfoodfarm.com/) is installing a irrigation system on their 50 acres of land near Vacaville. The installation will be taking place over four full days (9AM to 4PM - September 11, 18, 24, 25) and they are looking for volunteers interested in helping to set up the system. Volunteers will see the farm operation and be able to ask the irrigation designer and engineer questions about the system, design decisions, and other technical considerations. Volunteers are welcome on any or all the days (but need to RSVP with Alexis Koefoed (farmer/owner) so they can plan the work accordingly) and will be connecting pipes/drip lines, attaching sprinklers, or working on other farm projects.
This is a great opportunity for anyone interested in or considering installing a large irrigation system on their land. It is also a unique chance to visit an incredible pastured chicken operation that sells through farmers markets, a CSA, and direct to many fine restaurants in the Bay Area.
On a different note, with some extra acres and a need for some additional labor, Soul Food Farm is also looking for a few farmers interested in farming 5-10 acres of their certified organic land in Vacaville. Instead of leasing the land, they would like to explore work-trade arrangements, with the farmers paying for the parcel through work on Soul Food Farm.
If you have any questions about these opportunities please let me know, or if you'd like to RSVP for one of the workdays please call Alexis directly at 707--365-1798. |
module LongMultiplication
using Compat
function addwithcarry!(r, addend, addendpos)
while true
pad = max(0, addendpos - lastindex(r))
append!(r, fill(0, pad))
addendrst = addend + r[addendpos]
addend, r[addendpos] = divrem(addendrst, 10)
iszero(addend) && break
addendpos += 1
end
return r
end
function longmult(mult1::AbstractVector{T}, mult2::AbstractVector{T}) where T <: Integer
r = T[]
for (offset1, digit1) in enumerate(mult1), (offset2, digit2) in zip(eachindex(mult2) + offset1 - 1, mult2)
single_multrst = digits(digit1 * digit2)
for (addoffset, rstdigit) in zip(eachindex(single_multrst) + offset2 - 1, single_multrst)
addwithcarry!(r, rstdigit, addoffset)
end
end
return r
end
function longmult(a::T, b::T)::T where T <: Integer
mult1 = digits(a)
mult2 = digits(b)
r = longmult(mult1, mult2)
return sum(d * T(10) ^ (e - 1) for (e, d) in enumerate(r))
end
function longmult(a::AbstractString, b::AbstractString)
if !ismatch(r"^\d+", a) || !ismatch(r"^\d+", b)
throw(ArgumentError("string must contain only digits"))
end
mult1 = reverse(collect(Char, a) .- '0')
mult2 = reverse(collect(Char, b) .- '0')
r = longmult(mult1, mult2)
return reverse(join(r))
end
end # module LongMultiplication
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
! This file was ported from Lean 3 source module data.list.sort
! leanprover-community/mathlib commit 327c3c0d9232d80e250dc8f65e7835b82b266ea5
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.List.OfFn
import Mathbin.Data.List.Perm
/-!
# Sorting algorithms on lists
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `list.sorted r l` to be an alias for `pairwise r l`. This alias is preferred
in the case that `r` is a `<` or `β€`-like relation. Then we define two sorting algorithms:
`list.insertion_sort` and `list.merge_sort`, and prove their correctness.
-/
open List.Perm
universe uu
namespace List
/-!
### The predicate `list.sorted`
-/
section Sorted
variable {Ξ± : Type uu} {r : Ξ± β Ξ± β Prop} {a : Ξ±} {l : List Ξ±}
#print List.Sorted /-
/-- `sorted r l` is the same as `pairwise r l`, preferred in the case that `r`
is a `<` or `β€`-like relation (transitive and antisymmetric or asymmetric) -/
def Sorted :=
@Pairwise
#align list.sorted List.Sorted
-/
#print List.decidableSorted /-
instance decidableSorted [DecidableRel r] (l : List Ξ±) : Decidable (Sorted r l) :=
List.instDecidablePairwise _
#align list.decidable_sorted List.decidableSorted
-/
#print List.sorted_nil /-
@[simp]
theorem sorted_nil : Sorted r [] :=
Pairwise.nil
#align list.sorted_nil List.sorted_nil
-/
#print List.Sorted.of_cons /-
theorem Sorted.of_cons : Sorted r (a :: l) β Sorted r l :=
Pairwise.of_cons
#align list.sorted.of_cons List.Sorted.of_cons
-/
#print List.Sorted.tail /-
theorem Sorted.tail {r : Ξ± β Ξ± β Prop} {l : List Ξ±} (h : Sorted r l) : Sorted r l.tail :=
h.tail
#align list.sorted.tail List.Sorted.tail
-/
#print List.rel_of_sorted_cons /-
theorem rel_of_sorted_cons {a : Ξ±} {l : List Ξ±} : Sorted r (a :: l) β β b β l, r a b :=
rel_of_pairwise_cons
#align list.rel_of_sorted_cons List.rel_of_sorted_cons
-/
#print List.sorted_cons /-
@[simp]
theorem sorted_cons {a : Ξ±} {l : List Ξ±} : Sorted r (a :: l) β (β b β l, r a b) β§ Sorted r l :=
pairwise_cons
#align list.sorted_cons List.sorted_cons
-/
#print List.Sorted.nodup /-
protected theorem Sorted.nodup {r : Ξ± β Ξ± β Prop} [IsIrrefl Ξ± r] {l : List Ξ±} (h : Sorted r l) :
Nodup l :=
h.Nodup
#align list.sorted.nodup List.Sorted.nodup
-/
#print List.eq_of_perm_of_sorted /-
theorem eq_of_perm_of_sorted [IsAntisymm Ξ± r] {lβ lβ : List Ξ±} (p : lβ ~ lβ) (sβ : Sorted r lβ)
(sβ : Sorted r lβ) : lβ = lβ :=
by
induction' sβ with a lβ hβ sβ IH generalizing lβ
Β· exact p.nil_eq
Β· have : a β lβ := p.subset (mem_cons_self _ _)
rcases mem_split this with β¨uβ, vβ, rflβ©
have p' := (perm_cons a).1 (p.trans perm_middle)
obtain rfl := IH p' (sβ.sublist <| by simp)
change a :: uβ ++ vβ = uβ ++ ([a] ++ vβ)
rw [β append_assoc]
congr
have : β (x : Ξ±) (h : x β uβ), x = a := fun x m =>
antisymm ((pairwise_append.1 sβ).2.2 _ m a (mem_cons_self _ _)) (hβ _ (by simp [m]))
rw [(@eq_replicate _ a (length uβ + 1) (a :: uβ)).2,
(@eq_replicate _ a (length uβ + 1) (uβ ++ [a])).2] <;>
constructor <;>
simp [iff_true_intro this, or_comm']
#align list.eq_of_perm_of_sorted List.eq_of_perm_of_sorted
-/
#print List.sublist_of_subperm_of_sorted /-
theorem sublist_of_subperm_of_sorted [IsAntisymm Ξ± r] {lβ lβ : List Ξ±} (p : lβ <+~ lβ)
(sβ : lβ.Sorted r) (sβ : lβ.Sorted r) : lβ <+ lβ :=
by
let β¨_, h, h'β© := p
rwa [β eq_of_perm_of_sorted h (sβ.sublist h') sβ]
#align list.sublist_of_subperm_of_sorted List.sublist_of_subperm_of_sorted
-/
#print List.sorted_singleton /-
@[simp]
theorem sorted_singleton (a : Ξ±) : Sorted r [a] :=
pairwise_singleton _ _
#align list.sorted_singleton List.sorted_singleton
-/
#print List.Sorted.rel_nthLe_of_lt /-
theorem Sorted.rel_nthLe_of_lt {l : List Ξ±} (h : l.Sorted r) {a b : β} (ha : a < l.length)
(hb : b < l.length) (hab : a < b) : r (l.nthLe a ha) (l.nthLe b hb) :=
List.pairwise_iff_nthLe.1 h a b hb hab
#align list.sorted.rel_nth_le_of_lt List.Sorted.rel_nthLe_of_lt
-/
#print List.Sorted.rel_nthLe_of_le /-
theorem Sorted.rel_nthLe_of_le [IsRefl Ξ± r] {l : List Ξ±} (h : l.Sorted r) {a b : β}
(ha : a < l.length) (hb : b < l.length) (hab : a β€ b) : r (l.nthLe a ha) (l.nthLe b hb) :=
by
cases' eq_or_lt_of_le hab with H H
Β· subst H
exact refl _
Β· exact h.rel_nth_le_of_lt _ _ H
#align list.sorted.rel_nth_le_of_le List.Sorted.rel_nthLe_of_le
-/
#print List.Sorted.rel_of_mem_take_of_mem_drop /-
theorem Sorted.rel_of_mem_take_of_mem_drop {l : List Ξ±} (h : List.Sorted r l) {k : β} {x y : Ξ±}
(hx : x β List.take k l) (hy : y β List.drop k l) : r x y :=
by
obtain β¨iy, hiy, rflβ© := nth_le_of_mem hy
obtain β¨ix, hix, rflβ© := nth_le_of_mem hx
rw [nth_le_take', nth_le_drop']
rw [length_take] at hix
exact h.rel_nth_le_of_lt _ _ (ix.lt_add_right _ _ (lt_min_iff.mp hix).left)
#align list.sorted.rel_of_mem_take_of_mem_drop List.Sorted.rel_of_mem_take_of_mem_drop
-/
end Sorted
section Monotone
variable {n : β} {Ξ± : Type uu} [Preorder Ξ±] {f : Fin n β Ξ±}
/- warning: list.monotone_iff_of_fn_sorted -> List.monotone_iff_ofFn_sorted is a dubious translation:
lean 3 declaration is
forall {n : Nat} {Ξ± : Type.{u1}} [_inst_1 : Preorder.{u1} Ξ±] {f : (Fin n) -> Ξ±}, Iff (Monotone.{0, u1} (Fin n) Ξ± (PartialOrder.toPreorder.{0} (Fin n) (Fin.partialOrder n)) _inst_1 f) (List.Sorted.{u1} Ξ± (LE.le.{u1} Ξ± (Preorder.toLE.{u1} Ξ± _inst_1)) (List.ofFn.{u1} Ξ± n f))
but is expected to have type
forall {n : Nat} {Ξ± : Type.{u1}} [_inst_1 : Preorder.{u1} Ξ±] {f : (Fin n) -> Ξ±}, Iff (Monotone.{0, u1} (Fin n) Ξ± (PartialOrder.toPreorder.{0} (Fin n) (Fin.instPartialOrderFin n)) _inst_1 f) (List.Sorted.{u1} Ξ± (fun ([email protected]._hyg.1422 : Ξ±) ([email protected]._hyg.1424 : Ξ±) => LE.le.{u1} Ξ± (Preorder.toLE.{u1} Ξ± _inst_1) [email protected]._hyg.1422 [email protected]._hyg.1424) (List.ofFn.{u1} Ξ± n f))
Case conversion may be inaccurate. Consider using '#align list.monotone_iff_of_fn_sorted List.monotone_iff_ofFn_sortedβ'. -/
/-- A tuple is monotone if and only if the list obtained from it is sorted. -/
theorem monotone_iff_ofFn_sorted : Monotone f β (ofFn f).Sorted (Β· β€ Β·) :=
by
simp_rw [sorted, pairwise_iff_nth_le, length_of_fn, nth_le_of_fn', monotone_iff_forall_lt]
exact β¨fun h i j hj hij => h <| fin.mk_lt_mk.mpr hij, fun h β¨i, _β© β¨j, hjβ© hij => h i j hj hijβ©
#align list.monotone_iff_of_fn_sorted List.monotone_iff_ofFn_sorted
/- warning: list.monotone.of_fn_sorted -> Monotone.ofFn_sorted is a dubious translation:
lean 3 declaration is
forall {n : Nat} {Ξ± : Type.{u1}} [_inst_1 : Preorder.{u1} Ξ±] {f : (Fin n) -> Ξ±}, (Monotone.{0, u1} (Fin n) Ξ± (PartialOrder.toPreorder.{0} (Fin n) (Fin.partialOrder n)) _inst_1 f) -> (List.Sorted.{u1} Ξ± (LE.le.{u1} Ξ± (Preorder.toLE.{u1} Ξ± _inst_1)) (List.ofFn.{u1} Ξ± n f))
but is expected to have type
forall {n : Nat} {Ξ± : Type.{u1}} [_inst_1 : Preorder.{u1} Ξ±] {f : (Fin n) -> Ξ±}, (Monotone.{0, u1} (Fin n) Ξ± (PartialOrder.toPreorder.{0} (Fin n) (Fin.instPartialOrderFin n)) _inst_1 f) -> (List.Sorted.{u1} Ξ± (fun ([email protected]._hyg.1381 : Ξ±) ([email protected]._hyg.1383 : Ξ±) => LE.le.{u1} Ξ± (Preorder.toLE.{u1} Ξ± _inst_1) [email protected]._hyg.1381 [email protected]._hyg.1383) (List.ofFn.{u1} Ξ± n f))
Case conversion may be inaccurate. Consider using '#align list.monotone.of_fn_sorted Monotone.ofFn_sortedβ'. -/
/-- The list obtained from a monotone tuple is sorted. -/
theorem Monotone.ofFn_sorted (h : Monotone f) : (ofFn f).Sorted (Β· β€ Β·) :=
monotone_iff_ofFn_sorted.1 h
#align list.monotone.of_fn_sorted Monotone.ofFn_sorted
end Monotone
section Sort
variable {Ξ± : Type uu} (r : Ξ± β Ξ± β Prop) [DecidableRel r]
-- mathport name: Β«expr βΌ Β»
local infixl:50 " βΌ " => r
/-! ### Insertion sort -/
section InsertionSort
#print List.orderedInsert /-
/-- `ordered_insert a l` inserts `a` into `l` at such that
`ordered_insert a l` is sorted if `l` is. -/
@[simp]
def orderedInsert (a : Ξ±) : List Ξ± β List Ξ±
| [] => [a]
| b :: l => if a βΌ b then a :: b :: l else b :: ordered_insert l
#align list.ordered_insert List.orderedInsert
-/
#print List.insertionSort /-
/-- `insertion_sort l` returns `l` sorted using the insertion sort algorithm. -/
@[simp]
def insertionSort : List Ξ± β List Ξ±
| [] => []
| b :: l => orderedInsert r b (insertion_sort l)
#align list.insertion_sort List.insertionSort
-/
#print List.orderedInsert_nil /-
@[simp]
theorem orderedInsert_nil (a : Ξ±) : [].orderedInsert r a = [a] :=
rfl
#align list.ordered_insert_nil List.orderedInsert_nil
-/
#print List.orderedInsert_length /-
theorem orderedInsert_length : β (L : List Ξ±) (a : Ξ±), (L.orderedInsert r a).length = L.length + 1
| [], a => rfl
| hd :: tl, a => by
dsimp [ordered_insert]
split_ifs <;> simp [ordered_insert_length]
#align list.ordered_insert_length List.orderedInsert_length
-/
#print List.orderedInsert_eq_take_drop /-
/-- An alternative definition of `ordered_insert` using `take_while` and `drop_while`. -/
theorem orderedInsert_eq_take_drop (a : Ξ±) :
β l : List Ξ±,
l.orderedInsert r a = (l.takeWhile fun b => Β¬a βΌ b) ++ a :: l.dropWhileβ fun b => Β¬a βΌ b
| [] => rfl
| b :: l => by
dsimp only [ordered_insert]
split_ifs <;> simp [take_while, drop_while, *]
#align list.ordered_insert_eq_take_drop List.orderedInsert_eq_take_drop
-/
#print List.insertionSort_cons_eq_take_drop /-
theorem insertionSort_cons_eq_take_drop (a : Ξ±) (l : List Ξ±) :
insertionSort r (a :: l) =
((insertionSort r l).takeWhile fun b => Β¬a βΌ b) ++
a :: (insertionSort r l).dropWhileβ fun b => Β¬a βΌ b :=
orderedInsert_eq_take_drop r a _
#align list.insertion_sort_cons_eq_take_drop List.insertionSort_cons_eq_take_drop
-/
section Correctness
open Perm
#print List.perm_orderedInsert /-
theorem perm_orderedInsert (a) : β l : List Ξ±, orderedInsert r a l ~ a :: l
| [] => Perm.refl _
| b :: l => by
by_cases a βΌ b <;> [simp [ordered_insert, h],
simpa [ordered_insert, h] using ((perm_ordered_insert l).cons _).trans (perm.swap _ _ _)]
#align list.perm_ordered_insert List.perm_orderedInsert
-/
#print List.orderedInsert_count /-
theorem orderedInsert_count [DecidableEq Ξ±] (L : List Ξ±) (a b : Ξ±) :
count a (L.orderedInsert r b) = count a L + if a = b then 1 else 0 :=
by
rw [(L.perm_ordered_insert r b).count_eq, count_cons]
split_ifs <;> simp only [Nat.succ_eq_add_one, add_zero]
#align list.ordered_insert_count List.orderedInsert_count
-/
#print List.perm_insertionSort /-
theorem perm_insertionSort : β l : List Ξ±, insertionSort r l ~ l
| [] => Perm.nil
| b :: l => by
simpa [insertion_sort] using (perm_ordered_insert _ _ _).trans ((perm_insertion_sort l).cons b)
#align list.perm_insertion_sort List.perm_insertionSort
-/
variable {r}
#print List.Sorted.insertionSort_eq /-
/-- If `l` is already `list.sorted` with respect to `r`, then `insertion_sort` does not change
it. -/
theorem Sorted.insertionSort_eq : β {l : List Ξ±} (h : Sorted r l), insertionSort r l = l
| [], _ => rfl
| [a], _ => rfl
| a :: b :: l, h =>
by
rw [insertion_sort, sorted.insertion_sort_eq, ordered_insert, if_pos]
exacts[rel_of_sorted_cons h _ (Or.inl rfl), h.tail]
#align list.sorted.insertion_sort_eq List.Sorted.insertionSort_eq
-/
section TotalAndTransitive
variable [IsTotal Ξ± r] [IsTrans Ξ± r]
#print List.Sorted.orderedInsert /-
theorem Sorted.orderedInsert (a : Ξ±) : β l, Sorted r l β Sorted r (orderedInsert r a l)
| [], h => sorted_singleton a
| b :: l, h => by
by_cases h' : a βΌ b
Β· simpa [ordered_insert, h', h] using fun b' bm => trans h' (rel_of_sorted_cons h _ bm)
Β· suffices β b' : Ξ±, b' β ordered_insert r a l β r b b' by
simpa [ordered_insert, h', h.of_cons.ordered_insert l]
intro b' bm
cases' show b' = a β¨ b' β l by simpa using (perm_ordered_insert _ _ _).Subset bm with be bm
Β· subst b'
exact (total_of r _ _).resolve_left h'
Β· exact rel_of_sorted_cons h _ bm
#align list.sorted.ordered_insert List.Sorted.orderedInsert
-/
variable (r)
#print List.sorted_insertionSort /-
/-- The list `list.insertion_sort r l` is `list.sorted` with respect to `r`. -/
theorem sorted_insertionSort : β l, Sorted r (insertionSort r l)
| [] => sorted_nil
| a :: l => (sorted_insertion_sort l).orderedInsert a _
#align list.sorted_insertion_sort List.sorted_insertionSort
-/
end TotalAndTransitive
end Correctness
end InsertionSort
/-! ### Merge sort -/
section MergeSort
#print List.split /-
-- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the
-- equation compiler can't prove the third equation
/-- Split `l` into two lists of approximately equal length.
split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/
@[simp]
def split : List Ξ± β List Ξ± Γ List Ξ±
| [] => ([], [])
| a :: l =>
let (lβ, lβ) := split l
(a :: lβ, lβ)
#align list.split List.split
-/
#print List.split_cons_of_eq /-
theorem split_cons_of_eq (a : Ξ±) {l lβ lβ : List Ξ±} (h : split l = (lβ, lβ)) :
split (a :: l) = (a :: lβ, lβ) := by rw [split, h] <;> rfl
#align list.split_cons_of_eq List.split_cons_of_eq
-/
#print List.length_split_le /-
theorem length_split_le :
β {l lβ lβ : List Ξ±}, split l = (lβ, lβ) β length lβ β€ length l β§ length lβ β€ length l
| [], _, _, rfl => β¨Nat.le_refl 0, Nat.le_refl 0β©
| a :: l, lβ', lβ', h => by
cases' e : split l with lβ lβ
injection (split_cons_of_eq _ e).symm.trans h; substs lβ' lβ'
cases' length_split_le e with hβ hβ
exact β¨Nat.succ_le_succ hβ, Nat.le_succ_of_le hββ©
#align list.length_split_le List.length_split_le
-/
#print List.length_split_lt /-
theorem length_split_lt {a b} {l lβ lβ : List Ξ±} (h : split (a :: b :: l) = (lβ, lβ)) :
length lβ < length (a :: b :: l) β§ length lβ < length (a :: b :: l) :=
by
cases' e : split l with lβ' lβ'
injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h; substs lβ lβ
cases' length_split_le e with hβ hβ
exact β¨Nat.succ_le_succ (Nat.succ_le_succ hβ), Nat.succ_le_succ (Nat.succ_le_succ hβ)β©
#align list.length_split_lt List.length_split_lt
-/
#print List.perm_split /-
theorem perm_split : β {l lβ lβ : List Ξ±}, split l = (lβ, lβ) β l ~ lβ ++ lβ
| [], _, _, rfl => Perm.refl _
| a :: l, lβ', lβ', h => by
cases' e : split l with lβ lβ
injection (split_cons_of_eq _ e).symm.trans h; substs lβ' lβ'
exact ((perm_split e).trans perm_append_comm).cons a
#align list.perm_split List.perm_split
-/
#print List.merge /-
/-- Merge two sorted lists into one in linear time.
merge [1, 2, 4, 5] [0, 1, 3, 4] = [0, 1, 1, 2, 3, 4, 4, 5] -/
def merge : List Ξ± β List Ξ± β List Ξ±
| [], l' => l'
| l, [] => l
| a :: l, b :: l' => if a βΌ b then a :: merge l (b :: l') else b :: merge (a :: l) l'
#align list.merge List.merge
-/
include r
#print List.mergeSort /-
/-- Implementation of a merge sort algorithm to sort a list. -/
def mergeSort : List Ξ± β List Ξ±
| [] => []
| [a] => [a]
| a :: b :: l => by
cases' e : split (a :: b :: l) with lβ lβ
cases' length_split_lt e with hβ hβ
exact merge r (merge_sort lβ) (merge_sort lβ)termination_by'
β¨_, InvImage.wf length Nat.lt_wfRelβ©
#align list.merge_sort List.mergeSort
-/
#print List.mergeSort_cons_cons /-
theorem mergeSort_cons_cons {a b} {l lβ lβ : List Ξ±} (h : split (a :: b :: l) = (lβ, lβ)) :
mergeSort r (a :: b :: l) = merge r (mergeSort r lβ) (mergeSort r lβ) :=
by
suffices
β (L : List Ξ±) (h1),
@And.ndrec (fun a a (_ : length lβ < length l + 1 + 1 β§ length lβ < length l + 1 + 1) => L) h1
h1 =
L
by
simp [merge_sort, h]
apply this
intros
cases h1
rfl
#align list.merge_sort_cons_cons List.mergeSort_cons_cons
-/
section Correctness
#print List.perm_merge /-
theorem perm_merge : β l l' : List Ξ±, merge r l l' ~ l ++ l'
| [], [] => by simp [merge]
| [], b :: l' => by simp [merge]
| a :: l, [] => by simp [merge]
| a :: l, b :: l' => by
by_cases a βΌ b
Β· simpa [merge, h] using perm_merge _ _
Β· suffices b :: merge r (a :: l) l' ~ a :: (l ++ b :: l') by simpa [merge, h]
exact ((perm_merge _ _).cons _).trans ((swap _ _ _).trans (perm_middle.symm.cons _))
#align list.perm_merge List.perm_merge
-/
#print List.perm_mergeSort /-
theorem perm_mergeSort : β l : List Ξ±, mergeSort r l ~ l
| [] => by simp [merge_sort]
| [a] => by simp [merge_sort]
| a :: b :: l => by
cases' e : split (a :: b :: l) with lβ lβ
cases' length_split_lt e with hβ hβ
rw [merge_sort_cons_cons r e]
apply (perm_merge r _ _).trans
exact
((perm_merge_sort lβ).append (perm_merge_sort lβ)).trans (perm_split e).symm termination_by'
β¨_, InvImage.wf length Nat.lt_wfRelβ©
#align list.perm_merge_sort List.perm_mergeSort
-/
#print List.length_mergeSort /-
@[simp]
theorem length_mergeSort (l : List Ξ±) : (mergeSort r l).length = l.length :=
(perm_mergeSort r _).length_eq
#align list.length_merge_sort List.length_mergeSort
-/
section TotalAndTransitive
variable {r} [IsTotal Ξ± r] [IsTrans Ξ± r]
#print List.Sorted.merge /-
theorem Sorted.merge : β {l l' : List Ξ±}, Sorted r l β Sorted r l' β Sorted r (merge r l l')
| [], [], hβ, hβ => by simp [merge]
| [], b :: l', hβ, hβ => by simpa [merge] using hβ
| a :: l, [], hβ, hβ => by simpa [merge] using hβ
| a :: l, b :: l', hβ, hβ => by
by_cases a βΌ b
Β· suffices β (b' : Ξ±) (_ : b' β merge r l (b :: l')), r a b' by
simpa [merge, h, hβ.of_cons.merge hβ]
intro b' bm
rcases show b' = b β¨ b' β l β¨ b' β l' by
simpa [or_left_comm] using (perm_merge _ _ _).Subset bm with
(be | bl | bl')
Β· subst b'
assumption
Β· exact rel_of_sorted_cons hβ _ bl
Β· exact trans h (rel_of_sorted_cons hβ _ bl')
Β· suffices β (b' : Ξ±) (_ : b' β merge r (a :: l) l'), r b b' by
simpa [merge, h, hβ.merge hβ.of_cons]
intro b' bm
have ba : b βΌ a := (total_of r _ _).resolve_left h
rcases show b' = a β¨ b' β l β¨ b' β l' by simpa using (perm_merge _ _ _).Subset bm with
(be | bl | bl')
Β· subst b'
assumption
Β· exact trans ba (rel_of_sorted_cons hβ _ bl)
Β· exact rel_of_sorted_cons hβ _ bl'
#align list.sorted.merge List.Sorted.merge
-/
variable (r)
#print List.sorted_mergeSort /-
theorem sorted_mergeSort : β l : List Ξ±, Sorted r (mergeSort r l)
| [] => by simp [merge_sort]
| [a] => by simp [merge_sort]
| a :: b :: l => by
cases' e : split (a :: b :: l) with lβ lβ
cases' length_split_lt e with hβ hβ
rw [merge_sort_cons_cons r e]
exact (sorted_merge_sort lβ).merge (sorted_merge_sort lβ)termination_by'
β¨_, InvImage.wf length Nat.lt_wfRelβ©
#align list.sorted_merge_sort List.sorted_mergeSort
-/
#print List.mergeSort_eq_self /-
theorem mergeSort_eq_self [IsAntisymm Ξ± r] {l : List Ξ±} : Sorted r l β mergeSort r l = l :=
eq_of_perm_of_sorted (perm_mergeSort _ _) (sorted_mergeSort _ _)
#align list.merge_sort_eq_self List.mergeSort_eq_self
-/
#print List.mergeSort_eq_insertionSort /-
theorem mergeSort_eq_insertionSort [IsAntisymm Ξ± r] (l : List Ξ±) :
mergeSort r l = insertionSort r l :=
eq_of_perm_of_sorted ((perm_mergeSort r l).trans (perm_insertionSort r l).symm)
(sorted_mergeSort r l) (sorted_insertionSort r l)
#align list.merge_sort_eq_insertion_sort List.mergeSort_eq_insertionSort
-/
end TotalAndTransitive
end Correctness
#print List.mergeSort_nil /-
@[simp]
theorem mergeSort_nil : [].mergeSort r = [] := by rw [List.mergeSort]
#align list.merge_sort_nil List.mergeSort_nil
-/
#print List.mergeSort_singleton /-
@[simp]
theorem mergeSort_singleton (a : Ξ±) : [a].mergeSort r = [a] := by rw [List.mergeSort]
#align list.merge_sort_singleton List.mergeSort_singleton
-/
end MergeSort
end Sort
-- try them out!
--#eval insertion_sort (Ξ» m n : β, m β€ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
--#eval merge_sort (Ξ» m n : β, m β€ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
end List
|
Require Import
Coq.Strings.String
Fiat.Common.String_as_OT
Fiat.QueryStructure.Specification.Representation.QueryStructureNotations
Fiat.QueryStructure.Specification.SearchTerms.ListInclusion
Fiat.QueryStructure.Implementation.DataStructures.BagADT.IndexSearchTerms
Fiat.QueryStructure.Automation.IndexSelection
Fiat.QueryStructure.Automation.Common
Fiat.QueryStructure.Implementation.DataStructures.Bags.CountingListBags
Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsOfTuples.
(* Instances for building indexes with make simple indexes. *)
(* Every Kind of index is keyed on an inductive type with a single constructor*)
Local Open Scope string_scope.
Definition InclusionIndex : string := "InclusionIndex".
Instance ExpressionAttributeCounterIncludedIn {A }
{qsSchema : RawQueryStructureSchema}
{a}
{a' : list A}
(RidxL : Fin.t _)
(BAidxL : @Attributes (Vector.nth _ RidxL))
(ExpCountL : @TermAttributeCounter _ qsSchema a' RidxL BAidxL)
: @ExpressionAttributeCounter _ qsSchema (IncludedIn a a')
(@InsertOccurenceOfAny _ _ RidxL (InclusionIndex, BAidxL)
(InitOccurences _)) | 0 := { }.
Ltac IncludedInExpressionAttributeCounter k :=
psearch_combine
ltac:(eapply @ExpressionAttributeCounterIncludedIn; intros) k.
Ltac BuildLastInclusionIndex
heading indices kind index k k_fail :=
let is_equality := eval compute in (string_dec kind InclusionIndex) in
let A := eval compute in (Domain heading index) in
let A' := match A with | list ?A' => A' end in
match is_equality with
| left _ => k
(fun (search_term : prod (Domain heading index) (@RawTuple heading -> bool)) (tup : @RawTuple heading) =>
andb (if IncludedIn_dec (X := A')
(fst search_term) (GetAttributeRaw tup index) then
true
else false)
(snd search_term tup))
| right _ => k_fail heading indices kind index k
end.
Ltac BuildEarlyInclusionIndex
heading indices kind index matcher k k_fail :=
k_fail heading indices kind index matcher k.
Ltac InclusionIndexUse SC F indexed_attrs f k k_fail :=
match type of f with
(* Inclusion Search Terms *)
| forall a, {IncludedIn ?X (GetAttributeRaw _ ?fd)} + {_} =>
let H := fresh in
assert (List.In (@Build_KindIndex SC "InclusionIndex" fd) indexed_attrs) as H
by (clear; subst_all; simpl; intuition eauto); clear H;
k (@Build_KindIndex SC "InclusionIndex" fd, X) (fun _ : @RawTuple SC => true)
| _ => k_fail SC F indexed_attrs f k
end.
Ltac InclusionIndexUse_dep SC F indexed_attrs visited_attrs f T k k_fail :=
match type of f with
| forall a b, {IncludedIn (@?X a) (GetAttributeRaw _ ?fd)} + {_} =>
let H := fresh in
assert (List.In (@Build_KindIndex SC "InclusionIndex" fd) indexed_attrs) as H
by (clear; subst_all; simpl; intuition eauto); clear H;
match eval simpl in
(in_dec fin_eq_dec fd visited_attrs) with
| right _ => k (fd :: visited_attrs)
(@Build_KindIndex SC "InclusionIndex" fd, X)
(fun (a : T) (_ : @RawTuple SC) => true)
| left _ => k visited_attrs tt F
end
| _ => k_fail SC F indexed_attrs visited_attrs f T k
end.
Ltac createLastInclusionTerm f fds tail fs kind s k k_fail :=
let is_equality := eval compute in (string_dec kind "InclusionIndex") in
match is_equality with
| left _ =>
(findMatchingTerm
fds kind s
ltac:(fun X => k (X : (Domain f s), tail)))
|| k (nil : (Domain f s), tail)
| _ => k_fail f fds tail fs kind s k
end.
Ltac createLastInclusionTerm_dep dom f fds tail fs kind s k k_fail :=
let is_equality := eval compute in (string_dec kind "InclusionIndex") in
match is_equality with
| left _ =>
(findMatchingTerm
fds kind s
ltac:(fun X => k (fun x : dom => (X x : (Domain f s), tail x )))
|| k (fun x : dom => (nil : (Domain f s), tail x)))
| _ => k_fail dom f fds tail fs kind s k
end.
Ltac createEarlyInclusionTerm f fds tail fs kind EarlyIndex LastIndex rest s k k_fail :=
let is_equality := eval compute in (string_dec kind "InclusionIndex") in
match is_equality with
| left _ =>
(findMatchingTerm
fds kind s
ltac:(fun X => k (X, rest)))
|| k (nil : (Domain f s), rest)
| _ => k_fail f fds tail fs kind EarlyIndex LastIndex rest s k
end.
Ltac createEarlyInclusionTerm_dep dom f fds tail fs kind EarlyIndex LastIndex rest s k k_fail :=
let is_equality := eval compute in (string_dec kind "InclusionIndex") in
match is_equality with
| left _ =>
(findMatchingTerm
fds kind s
ltac:(fun X => k (fun x : dom => (X x, rest x))))
|| k (fun x : dom => (nil : (Domain f s), rest x))
| _ => k_fail dom f fds tail fs kind EarlyIndex LastIndex rest s k
end.
Require Import
Coq.FSets.FMapInterface
Coq.FSets.FMapFacts
Coq.FSets.FMapAVL
Coq.Structures.OrderedTypeEx
Fiat.Common.String_as_OT
Fiat.QueryStructure.Implementation.DataStructures.Bags.InvertedIndexBags.
Module StringInvertedIndexBag := InvertedIndexBag StringIndexedMap NatIndexedMap.
Module NatInvertedIndexBag := InvertedIndexBag NatIndexedMap NatIndexedMap.
Module NInvertedIndexBag := InvertedIndexBag NIndexedMap NatIndexedMap.
Module ZInvertedIndexBag := InvertedIndexBag ZIndexedMap NatIndexedMap.
Ltac BuildLastInclusionIndexBag heading AttrList AttrKind AttrIndex k k_fail :=
let is_equality := eval compute in (string_dec AttrKind InclusionIndex) in
match is_equality with
| left _ =>
let AttrType := eval compute in (Domain heading AttrIndex) in
match AttrType with
| list string =>
k (@StringInvertedIndexBag.InvertedIndexAsCorrectBag _ _ (fun x => GetAttributeRaw (heading := heading) x AttrIndex)
(IndexedTreebupdate_transform heading)
)
| list nat =>
k (@NatInvertedIndexBag.InvertedIndexAsCorrectBag _ _ (fun x => GetAttributeRaw (heading := heading) x AttrIndex)
(IndexedTreebupdate_transform heading)
)
| list N =>
k (@NInvertedIndexBag.InvertedIndexAsCorrectBag _ _ (fun x => GetAttributeRaw (heading := heading) x AttrIndex)
(IndexedTreebupdate_transform heading)
)
| list Z =>
k (@ZInvertedIndexBag.InvertedIndexAsCorrectBag _ _ (fun x => GetAttributeRaw (heading := heading) x AttrIndex)
(IndexedTreebupdate_transform heading)
)
end
| right _ => k_fail heading AttrList AttrKind AttrIndex k
end.
Ltac BuildEarlyInclusionIndexBag heading AttrList AttrKind AttrIndex subtree k k_fail :=
k_fail heading AttrList AttrKind AttrIndex subtree k.
Ltac InclusionIndexTactics f :=
PackageIndexTactics
IncludedInExpressionAttributeCounter
BuildEarlyInclusionIndex BuildLastInclusionIndex
InclusionIndexUse createEarlyInclusionTerm createLastInclusionTerm
InclusionIndexUse_dep createEarlyInclusionTerm_dep createLastInclusionTerm_dep
BuildEarlyInclusionIndexBag BuildLastInclusionIndexBag f.
|
/*
Copyright (c) 2014 Glen Joseph Fernandes
glenfe at live dot com
Distributed under the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt
or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_ALIGN_DETAIL_TYPE_TRAITS_HPP
#define BOOST_ALIGN_DETAIL_TYPE_TRAITS_HPP
#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS)
#include <type_traits>
#else
#include <cstddef>
#endif
namespace boost {
namespace alignment {
namespace detail {
#if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS)
using std::remove_reference;
using std::remove_all_extents;
using std::remove_cv;
#else
template<class T>
struct remove_reference {
typedef T type;
};
template<class T>
struct remove_reference<T&> {
typedef T type;
};
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template<class T>
struct remove_reference<T&&> {
typedef T type;
};
#endif
template<class T>
struct remove_all_extents {
typedef T type;
};
template<class T>
struct remove_all_extents<T[]> {
typedef typename remove_all_extents<T>::type type;
};
template<class T, std::size_t N>
struct remove_all_extents<T[N]> {
typedef typename remove_all_extents<T>::type type;
};
template<class T>
struct remove_const {
typedef T type;
};
template<class T>
struct remove_const<const T> {
typedef T type;
};
template<class T>
struct remove_volatile {
typedef T type;
};
template<class T>
struct remove_volatile<volatile T> {
typedef T type;
};
template<class T>
struct remove_cv {
typedef typename remove_volatile<typename
remove_const<T>::type>::type type;
};
#endif
}
}
}
#endif
|
A function $f$ is continuous at $x$ if and only if the function $h \mapsto f(x + h)$ converges to $f(x)$ as $h$ approaches $0$. |
@var container;
@var camera, scene, renderer;
@var geometry, material, mesh;
function init()
renderer = new THREE.WebGLRenderer();
container = document.createElement("div");
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 5000 );
camera.position.z = 1400;
scene = new THREE.Scene();
@var circleGeometry = new THREE.CircleBufferGeometry( 1, 6 );
geometry = new THREE.InstancedBufferGeometry();
geometry.index = circleGeometry.index;
geometry.attributes = circleGeometry.attributes;
@var particleCount = 75000;
@var translateArray = new Float32Array( particleCount * 3 );
for ( @var i = 0, i3 = 0, l = particleCount; i < l; i ++, i3 += 3 ) {
translateArray[ i3 + 0 ] = Math.random() * 2 - 1;
translateArray[ i3 + 1 ] = Math.random() * 2 - 1;
translateArray[ i3 + 2 ] = Math.random() * 2 - 1;
}
geometry.addAttribute( 'translate', new THREE.InstancedBufferAttribute( translateArray, 3, 1 ) );
material = new THREE.RawShaderMaterial( {
uniforms: {
map: { value: new THREE.TextureLoader().load( 'file:///home/s/Desktop/circle.png' ) },
time: { value: 0.0 }
},
vertexShader: document.getElementById( 'vshader' ).textContent,
fragmentShader: document.getElementById( 'fshader' ).textContent,
depthTest: true,
depthWrite: true
} );
mesh = new THREE.Mesh( geometry, material );
mesh.scale.set( 500, 500, 500 );
scene.add( mesh );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
return true;
}
function onWindowResize( event ) {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
@var time = performance.now() * 0.0005;
material.uniforms.time.value = time;
mesh.rotation.x = time * 0.2;
mesh.rotation.y = time * 0.4;
renderer.render( scene, camera );
}
if ( init() ) {
animate();
}
|
INTEGER SEED
DATA SEED/987654321/
DATA EXACT/.78540/
FUNC(X)=1./(1.+X**2)
10 PRINT *, ' Enter number of points (0 to stop)'
READ *, N
IF (N .EQ. 0) STOP
SUMF=0.
SUMF2=0.
DO 20 IX=1,N
FX=FUNC(RAN(SEED))
SUMF=SUMF+FX
SUMF2=SUMF2+FX**2
20 CONTINUE
FAVE=SUMF/N
F2AVE=SUMF2/N
SIGMA=SQRT((F2AVE-FAVE**2)/N)
PRINT *,' integral =',FAVE,' +- ',SIGMA,' error = ',EXACT-FAVE
GOTO 10
END
|
Formal statement is: lemma interiorE [elim?]: assumes "x \<in> interior S" obtains T where "open T" and "x \<in> T" and "T \<subseteq> S" Informal statement is: If $x$ is an interior point of $S$, then there exists an open set $T$ such that $x \in T \subseteq S$. |
(*
Copyright 2016 University of Luxembourg
This file is part of our formalization of Platzer's
"A Complete Uniform Substitution Calculus for Differential Dynamic Logic"
available here: http://arxiv.org/pdf/1601.06183.pdf (July 27, 2016).
We refer to this formalization as DdlCoq here.
DdlCoq 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.
DdlCoq 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 DdlCoq. If not, see <http://www.gnu.org/licenses/>.
authors:
Vincent Rahli
Marcus VΓΆlp
Ivana Vukotic
*)
Require Export symbol.
Require Export list_util.
Require Export tactics_util.
Require Export reals_util.
(**
In this file conversion between KAssignables, variables and strings is introduced, as well as symbol decidability.
Also, this file introduces definition of state, and implements some lemmas about states.
Beside that, this file includes some useful definitions which we used in order to define syntax and semantics of ddl.
*)
(** some useful conversions between KAssignables, variables and strings *)
(* Used in definition of interpretation of primed terms *)
(** extract variable form KAssignable *)
Fixpoint KAssignable2variable (a : KAssignable) : KVariable :=
match a with
| KAssignVar x => x
| KAssignDiff a => KAssignable2variable a
end.
Coercion KAssignable2variable : KAssignable >-> KVariable.
Coercion KAssignVar : KVariable >-> KAssignable.
(** converts KVariable to string *)
Definition KVariable2string (v : KVariable) : String.string :=
match v with
| variable name => name
end.
Coercion KVariable2string : KVariable >-> String.string.
(** converts KAssignable to string *)
Definition KAssignable2string (a : KAssignable) : String.string := a.
(* Used in definition of interpretation of theta prime *)
(** extracts variables form KAssignable *)
Definition KVar_of_KAssignable (a : KAssignable) : list KVariable :=
match a with
| KAssignVar x => [x]
| KAssignDiff _ => []
end.
(** Decidability for symbols *)
(* used in definition of interpretation of teta prime *)
(** decidability for variables *)
Lemma KVariable_dec :
forall a b : KVariable, {a = b} + {a <> b}.
Proof.
destruct a as [x], b as [y]; prove_dec.
destruct (string_dec x y); subst; prove_dec.
Defined.
(* decidability for channels *)
Lemma KChannel_dec :
forall a b : KChannel, {a = b} + {a <> b}.
Proof.
destruct a as [x], b as [y]; prove_dec.
destruct (string_dec x y); subst; prove_dec.
Defined.
(** decidability for function symbols *)
Lemma FunctionSymbol_dec : forall (t u : FunctionSymbol), {t = u} + {t <> u}.
Proof.
destruct t as [n1], u as [n2].
destruct (string_dec n1 n2); subst; prove_dec.
Defined.
(** decidability for predicate symbols *)
Lemma PredicateSymbol_dec : forall (t u : PredicateSymbol), {t = u} + {t <> u}.
Proof.
destruct t as [n1], u as [n2].
destruct (string_dec n1 n2); subst; prove_dec.
Defined.
(** decidability for quantifier symbol *)
Lemma QuantifierSymbol_dec : forall (t u : QuantifierSymbol), {t = u} + {t <> u}.
Proof.
destruct t as [n1], u as [n2].
destruct (string_dec n1 n2); subst; prove_dec.
Defined.
(** decidability for constants *)
Lemma ProgramConstName_dec : forall (t u : ProgramConstName), {t = u} + {t <> u}.
Proof.
destruct t as [n1], u as [n2].
destruct (string_dec n1 n2); subst; prove_dec.
Defined.
(** decidability for constants *)
Lemma ODEConst_dec : forall (t u : ODEConst), {t = u} + {t <> u}.
Proof.
destruct t as [n1], u as [n2].
destruct (string_dec n1 n2); subst; prove_dec.
Defined.
(** decidability for KAssignables *)
Lemma KAssignable_dec : forall (t u : KAssignable), {t = u} + {t <> u}.
Proof.
induction t as [v1|d1], u as [v2|d2]; prove_dec.
{ destruct (KVariable_dec v1 v2) as [d|d]; subst; prove_dec. }
{ destruct (IHd1 d2) as [d|d]; subst; prove_dec. }
Defined.
(** returns differential of some variable x *)
Definition DVar (x : KVariable) : KAssignable :=
KAssignDiff (KAssignVar x).
Definition remove_var v l := remove_elt KVariable_dec v l.
Lemma not_in_remove_var :
forall v l, ~ In v (remove_var v l).
Proof.
introv; unfold remove_var; eauto with core.
Qed.
Hint Resolve not_in_remove_var : core.
|
/-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .fol
open fol
local notation h :: t := dvector.cons h t
local notation `[]` := dvector.nil
local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l
namespace nnf
section
/- Recurse through a formula, rewriting f βΉ β₯ to (βΌf) when possible -/
def not_rewrite {L} : β{l}, preformula L l β preformula L l
| l falsum := falsum
| l (tβ β tβ) := tβ β tβ
| l (rel R) := rel R
| l (apprel f t) := apprel f t
| l (f βΉ falsum) := (βΌf)
| l (f βΉ g) := (not_rewrite f) βΉ (not_rewrite g)
| l (β' f) := β' not_rewrite f
/- Recurse through a formula, rewriting βΌ(f βΉ βΌg) to f β g -/
def and_rewrite {L} : β{l}, preformula L l β preformula L l
| l falsum := falsum
| l (tβ β tβ) := tβ β tβ
| l (rel R) := rel R
| l (apprel f t) := apprel f t
--| l βΌ(f βΉ (βΌ g)) := f β g -- this pattern makes the equation compiler complain
| l ((f βΉ (g βΉ falsum)) βΉ falsum) := f β g
| l (f βΉ g) := (and_rewrite f) βΉ (and_rewrite g)
| l (β' f) := β' and_rewrite f
def or_rewrite {L} : β{l}, preformula L l β preformula L l
| l falsum := falsum
| l (tβ β tβ) := tβ β tβ
| l (rel R) := rel R
| l (apprel f t) := apprel f t
| l ((f βΉ falsum) βΉ g) := f β g
| l (f βΉ g) := (or_rewrite f) βΉ (or_rewrite g)
| l (β' f) := β' or_rewrite f
def imp_rewrite {L} : β{l}, preformula L l β preformula L l
| l falsum := falsum
| l (tβ β tβ) := tβ β tβ
| l (rel R) := rel R
| l (apprel f t) := apprel f t
| l (f βΉ g) := βΌ(imp_rewrite f) β (imp_rewrite g)
| l (β' f) := β' imp_rewrite f
lemma neg_rewrite_sanity_check {L} {f : formula L} : not_rewrite (f βΉ β₯) = (βΌf) :=
by {conv {to_lhs, rw[not_rewrite]}}
lemma and_rewrite_sanity_check {L} {f g : formula L} : and_rewrite βΌ(f βΉ (βΌg)) = f β g :=
by {conv {to_lhs, simp[fol.not], rw[and_rewrite]}}
--the simp[fol.not] is unfortunate, but the equation compiler doesn't let me use `βΌ` in and_rewrite
/- To put formulas into normal form,
1. replace implication with material implication, and
2. simplify with de-morgan's laws
maybe hijack the simplifier?
-/
end
end nnf
|
(******************************************************************************)
(* Project: Isabelle/UTP: Unifying Theories of Programming in Isabelle/HOL *)
(* File: utype.thy *)
(* Authors: Frank Zeyda and Simon Foster (University of York, UK) *)
(* Emails: [email protected] and [email protected] *)
(******************************************************************************)
(* LAST REVIEWED: 09 Jun 2022 *)
section \<open>Universal Types\<close>
theory utype
imports "../ucommon"
begin
text \<open>We are going to use the colon for model typing.\<close>
no_notation (ASCII)
Set.member ("'(:')") and
Set.member ("(_/ : _)" [51, 51] 50)
default_sort typerep
subsection \<open>Unified Types\<close>
text \<open>
We use Isabelle's @{typ typerep} mechanism to encode UTP model types. This
avoids having to fix the UTP type model upfront and thereby renders it open
for extension by the user. A downside of this approach is that there exist
@{type typerep} objects that do not correspond to permissible types in any
UTP model, as they may not be injectable into our unified value model.
\<close>
type_synonym utype = "typerep"
translations (type) "utype" \<leftharpoondown> (type) "typerep"
subsection \<open>Type Syntax\<close>
text \<open>@{text "UTYPE('a)"} is synonymous to @{text "TYPEREP('a)"}.\<close>
syntax "_UTYPE" :: "type \<Rightarrow> typerep" ("UTYPE'(_')")
translations "UTYPE('a)" \<rightleftharpoons> (* \<rightharpoonup> *) "TYPEREP('a)"
subsection \<open>Polymorphic Typing\<close>
definition p_type_rel :: "'a \<Rightarrow> utype \<Rightarrow> bool" (infix ":" 50) where
[typing]: "x : t \<longleftrightarrow> UTYPE('a) = t"
subsection \<open>Proof Support\<close>
text \<open>
The subsequent interpretation for type definitions automatically collects
@{class typerep} theorems in the theorem attribute @{text typing}. Hence,
the user does not have to worry about collecting them manually for any of
the existing or newly-defined HOL types. The @{text typing} attribute is
generally useful to facilitate proofs about model typing.
\<close>
ML_file "../utils/Typerep_Collect.ML"
text \<open>\todo{The below fails to collect the typerep theorem for @{type String.literal}?}\<close>
setup \<open>
(Typedef.interpretation
(Local_Theory.background_theory o Typerep_Collect.collect_typerep_thm))
\<close>
text \<open>
The following are not collected by the interpretation above as they are
ground types; we hence add them manually.
\<close>
declare typerep_bool_def [typing]
declare typerep_ind_def [typing]
declare typerep_fun_def [typing]
declare typerep_set_def [typing]
subsection \<open>Experiments\<close>
text \<open>The next shows that all typing theorems have been collected.\<close>
thm typing
text \<open>The examples in the sequel illustrates reasoning about types.\<close>
theorem "(1::nat) : UTYPE(nat)"
apply (simp add: typing)
done
theorem "1 : UTYPE(nat)"
apply (simp add: typing)
oops
theorem "\<not> (1::nat) : UTYPE(int)"
apply (simp add: typing)
done
theorem "(x::'a) : UTYPE('a)"
apply (simp add: typing)
done
theorem "{1::nat} : UTYPE('a set)"
apply (simp add: typing)
oops
theorem "{1::nat} : UTYPE(nat set)"
apply (simp add: typing)
done
theorem "{1} : UTYPE('a set)"
apply (simp add: typing)
oops
theorem "{1::('a::{numeral,typerep})} : UTYPE('a set)"
apply (simp add: typing)
done
end |
[GOAL]
β’ StableUnderComposition fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf
[PROOFSTEP]
introv R hf hg
[GOAL]
R S T : Type u_1
instβΒ² : CommRing R
instβΒΉ : CommRing S
instβ : CommRing T
f : R β+* S
g : S β+* T
hf : Function.Surjective βf
hg : Function.Surjective βg
β’ Function.Surjective β(comp g f)
[PROOFSTEP]
exact hg.comp hf
[GOAL]
β’ RespectsIso fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf
[PROOFSTEP]
apply surjective_stableUnderComposition.respectsIso
[GOAL]
β’ β {R S : Type u_1} [inst : CommRing R] [inst_1 : CommRing S] (e : R β+* S),
Function.Surjective β(RingEquiv.toRingHom e)
[PROOFSTEP]
intros _ _ _ _ e
[GOAL]
Rβ Sβ : Type u_1
instβΒΉ : CommRing Rβ
instβ : CommRing Sβ
e : Rβ β+* Sβ
β’ Function.Surjective β(RingEquiv.toRingHom e)
[PROOFSTEP]
exact e.surjective
[GOAL]
β’ StableUnderBaseChange fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf
[PROOFSTEP]
refine' StableUnderBaseChange.mk _ surjective_respectsIso _
[GOAL]
β’ β β¦R S T : Type u_1β¦ [inst : CommRing R] [inst_1 : CommRing S] [inst_2 : CommRing T] [inst_3 : Algebra R S]
[inst_4 : Algebra R T], Function.Surjective β(algebraMap R T) β Function.Surjective βincludeLeftRingHom
[PROOFSTEP]
classical
introv h x
skip
induction x using TensorProduct.induction_on with
| zero => exact β¨0, map_zero _β©
| tmul x y =>
obtain β¨y, rflβ© := h y; use y β’ x; dsimp
rw [TensorProduct.smul_tmul, Algebra.algebraMap_eq_smul_one]
| add x y ex ey => obtain β¨β¨x, rflβ©, β¨y, rflβ©β© := ex, ey; exact β¨x + y, map_add _ x yβ©
[GOAL]
β’ β β¦R S T : Type u_1β¦ [inst : CommRing R] [inst_1 : CommRing S] [inst_2 : CommRing T] [inst_3 : Algebra R S]
[inst_4 : Algebra R T], Function.Surjective β(algebraMap R T) β Function.Surjective βincludeLeftRingHom
[PROOFSTEP]
introv h x
[GOAL]
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S β[R] T
β’ β a, βincludeLeftRingHom a = x
[PROOFSTEP]
skip
[GOAL]
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S β[R] T
β’ β a, βincludeLeftRingHom a = x
[PROOFSTEP]
induction x using TensorProduct.induction_on with
| zero => exact β¨0, map_zero _β©
| tmul x y =>
obtain β¨y, rflβ© := h y; use y β’ x; dsimp
rw [TensorProduct.smul_tmul, Algebra.algebraMap_eq_smul_one]
| add x y ex ey => obtain β¨β¨x, rflβ©, β¨y, rflβ©β© := ex, ey; exact β¨x + y, map_add _ x yβ©
[GOAL]
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S β[R] T
β’ β a, βincludeLeftRingHom a = x
[PROOFSTEP]
induction x using TensorProduct.induction_on with
| zero => exact β¨0, map_zero _β©
| tmul x y =>
obtain β¨y, rflβ© := h y; use y β’ x; dsimp
rw [TensorProduct.smul_tmul, Algebra.algebraMap_eq_smul_one]
| add x y ex ey => obtain β¨β¨x, rflβ©, β¨y, rflβ©β© := ex, ey; exact β¨x + y, map_add _ x yβ©
[GOAL]
case zero
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
β’ β a, βincludeLeftRingHom a = 0
[PROOFSTEP]
| zero => exact β¨0, map_zero _β©
[GOAL]
case zero
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
β’ β a, βincludeLeftRingHom a = 0
[PROOFSTEP]
exact β¨0, map_zero _β©
[GOAL]
case tmul
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S
y : T
β’ β a, βincludeLeftRingHom a = x ββ[R] y
[PROOFSTEP]
| tmul x y =>
obtain β¨y, rflβ© := h y; use y β’ x; dsimp
rw [TensorProduct.smul_tmul, Algebra.algebraMap_eq_smul_one]
[GOAL]
case tmul
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S
y : T
β’ β a, βincludeLeftRingHom a = x ββ[R] y
[PROOFSTEP]
obtain β¨y, rflβ© := h y
[GOAL]
case tmul.intro
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S
y : R
β’ β a, βincludeLeftRingHom a = x ββ[R] β(algebraMap R T) y
[PROOFSTEP]
use y β’ x
[GOAL]
case h
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S
y : R
β’ βincludeLeftRingHom (y β’ x) = x ββ[R] β(algebraMap R T) y
[PROOFSTEP]
dsimp
[GOAL]
case h
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x : S
y : R
β’ (y β’ x) ββ[R] 1 = x ββ[R] β(algebraMap R T) y
[PROOFSTEP]
rw [TensorProduct.smul_tmul, Algebra.algebraMap_eq_smul_one]
[GOAL]
case add
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x y : S β[R] T
ex : β a, βincludeLeftRingHom a = x
ey : β a, βincludeLeftRingHom a = y
β’ β a, βincludeLeftRingHom a = x + y
[PROOFSTEP]
| add x y ex ey => obtain β¨β¨x, rflβ©, β¨y, rflβ©β© := ex, ey; exact β¨x + y, map_add _ x yβ©
[GOAL]
case add
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x y : S β[R] T
ex : β a, βincludeLeftRingHom a = x
ey : β a, βincludeLeftRingHom a = y
β’ β a, βincludeLeftRingHom a = x + y
[PROOFSTEP]
obtain β¨β¨x, rflβ©, β¨y, rflβ©β© := ex, ey
[GOAL]
case add.intro.intro
R S T : Type u_1
instββ΄ : CommRing R
instβΒ³ : CommRing S
instβΒ² : CommRing T
instβΒΉ : Algebra R S
instβ : Algebra R T
h : Function.Surjective β(algebraMap R T)
x y : S
β’ β a, βincludeLeftRingHom a = βincludeLeftRingHom x + βincludeLeftRingHom y
[PROOFSTEP]
exact β¨x + y, map_add _ x yβ©
[GOAL]
β’ OfLocalizationSpan fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf
[PROOFSTEP]
introv R hs H
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
β’ Function.Surjective βf
[PROOFSTEP]
skip
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
β’ Function.Surjective βf
[PROOFSTEP]
letI := f.toAlgebra
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
β’ Function.Surjective βf
[PROOFSTEP]
show Function.Surjective (Algebra.ofId R S)
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
β’ Function.Surjective β(Algebra.ofId R S)
[PROOFSTEP]
rw [β Algebra.range_top_iff_surjective, eq_top_iff]
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
β’ β€ β€ AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
rintro x -
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
obtain β¨l, hlβ© := (Finsupp.mem_span_iff_total R s 1).mp (show _ β Ideal.span s by rw [hs]; trivial)
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
β’ 1 β Ideal.span s
[PROOFSTEP]
rw [hs]
[GOAL]
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
β’ 1 β β€
[PROOFSTEP]
trivial
[GOAL]
case intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
fapply Subalgebra.mem_of_finset_sum_eq_one_of_pow_smul_mem _ l.support (fun x : s => f x) fun x : s => f (l x)
[GOAL]
case intro.e
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ β i in l.support, βf (βl i) * βf βi = 1
[PROOFSTEP]
dsimp only
[GOAL]
case intro.e
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ β i in l.support, βf (βl i) * βf βi = 1
[PROOFSTEP]
simp_rw [β _root_.map_mul, β map_sum, β f.map_one]
[GOAL]
case intro.e
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ βf (β x in l.support, βl x * βx) = βf 1
[PROOFSTEP]
exact f.congr_arg hl
[GOAL]
case intro.hs
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ β (i : βs), βf βi β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
exact fun _ => Set.mem_range_self _
[GOAL]
case intro.hl
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ β (i : βs), βf (βl i) β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
exact fun _ => Set.mem_range_self _
[GOAL]
case intro.H
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
β’ β (i : βs), β n, βf βi ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
intro r
[GOAL]
case intro.H
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
β’ β n, βf βr ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
obtain β¨y, hyβ© := H r (IsLocalization.mk' _ x (1 : Submonoid.powers (f r)))
[GOAL]
case intro.H.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
y : Localization.Away βr
hy : β(Localization.awayMap f βr) y = IsLocalization.mk' (Localization.Away (βf βr)) x 1
β’ β n, βf βr ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
obtain β¨z, β¨_, n, rflβ©, rflβ© := IsLocalization.mk'_surjective (Submonoid.powers (r : R)) y
[GOAL]
case intro.H.intro.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n : β
hy :
β(Localization.awayMap f βr)
(IsLocalization.mk' (Localization.Away βr) z
{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) }) =
IsLocalization.mk' (Localization.Away (βf βr)) x 1
β’ β n, βf βr ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
erw [IsLocalization.map_mk', IsLocalization.eq] at hy
[GOAL]
case intro.H.intro.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n : β
hy :
β c,
βc * (β1 * βf z) =
βc *
(β{
val :=
βf
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) },
property :=
(_ :
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) } β
Submonoid.comap f (Submonoid.powers (βf βr))) } *
x)
β’ β n, βf βr ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
obtain β¨β¨_, m, rflβ©, hmβ© := hy
[GOAL]
case intro.H.intro.intro.intro.mk.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n m : β
hm :
β{ val := (fun x x_1 => x ^ x_1) (βf βr) m,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βf βr) y = (fun x x_1 => x ^ x_1) (βf βr) m) } *
(β1 * βf z) =
β{ val := (fun x x_1 => x ^ x_1) (βf βr) m,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βf βr) y = (fun x x_1 => x ^ x_1) (βf βr) m) } *
(β{
val :=
βf
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) },
property :=
(_ :
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) } β
Submonoid.comap f (Submonoid.powers (βf βr))) } *
x)
β’ β n, βf βr ^ n β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
refine' β¨m + n, _β©
[GOAL]
case intro.H.intro.intro.intro.mk.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n m : β
hm :
β{ val := (fun x x_1 => x ^ x_1) (βf βr) m,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βf βr) y = (fun x x_1 => x ^ x_1) (βf βr) m) } *
(β1 * βf z) =
β{ val := (fun x x_1 => x ^ x_1) (βf βr) m,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βf βr) y = (fun x x_1 => x ^ x_1) (βf βr) m) } *
(β{
val :=
βf
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) },
property :=
(_ :
β{ val := (fun x x_1 => x ^ x_1) (βr) n,
property := (_ : β y, (fun x x_1 => x ^ x_1) (βr) y = (fun x x_1 => x ^ x_1) (βr) n) } β
Submonoid.comap f (Submonoid.powers (βf βr))) } *
x)
β’ βf βr ^ (m + n) β’ x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
dsimp at hm β’
[GOAL]
case intro.H.intro.intro.intro.mk.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n m : β
hm : βf βr ^ m * (1 * βf z) = βf βr ^ m * (βf (βr ^ n) * x)
β’ βf βr ^ (m + n) * x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
simp_rw [_root_.one_mul, β _root_.mul_assoc, β map_pow, β f.map_mul, β pow_add, map_pow] at hm
[GOAL]
case intro.H.intro.intro.intro.mk.intro.intro.mk.intro
R S : Type u_1
instβΒΉ : CommRing R
instβ : CommRing S
f : R β+* S
s : Set R
hs : Ideal.span s = β€
H : β (r : βs), (fun {X Y} [CommRing X] [CommRing Y] f => Function.Surjective βf) (Localization.awayMap f βr)
this : Algebra R S := toAlgebra f
x : S
l : βs ββ R
hl : β(Finsupp.total (βs) R R Subtype.val) l = 1
r : βs
z : R
n m : β
hm : βf (βr ^ m * z) = βf βr ^ (m + n) * x
β’ βf βr ^ (m + n) * x β AlgHom.range (Algebra.ofId R S)
[PROOFSTEP]
exact β¨_, hmβ©
|
A set $S$ is compact if and only if every sequence in $S$ has a convergent subsequence. |
Continuing on from our last post with a list of some blogs to inspire you, we have created another list of really great blogs and podcasts for you to read today.
This article looks at the benefits of remote, unmoderated user interviews, where participants complete pre-determined activities when and where they would like, with the researcher reviewing the recorded session later instead of communicating with the participant in real time.
Getting started in your creative career can be tough so Mitch Goldstein, a professor of design at Rochester Institute of Technology answers readers questions related to beginning a career.
Todayβs chatbots guide users through simple flows and the user research in this article shows that they have a hard time whenever users deviate from those flows.
The companies with the best financial returns have a bold, design-centric vision thatβs clearly embedded in the top teams. Cross-functional talent, analytical leadership, continuous iteration and user experience are included in the guidelines for how to run a company that reaps the benefits of good design.
The podcast explores the process and power of architecture and design and how great design can be all around us, have a huge impact on our lives, and yet it can be unnoticed and almost invisible, hence the name.
Have you found any interesting UX blogs that you think may interest us? Tweet us at @arekibo! |
# Decision Tree Induction with scikit-learn
**CS5483 Data Warehousing and Data Mining**
___
```python
%reset -f
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets, tree
# produce vector inline graphics
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg')
```
## Decision Tree Induction
We first import the [*iris dataset*](https://en.wikipedia.org/wiki/Iris_flower_data_set) from [`sklearn.datasets` package](https://scikit-learn.org/stable/datasets/index.html)
```python
from sklearn import datasets
import pandas as pd
iris = datasets.load_iris()
```
Recall that the classification task is to train a model that can classify the spieces (*target*) automatically based on the lengths and widths of the petals and sepals (*input features*).
To build a decision tree, we simply create a tree using `DecisionTreeClassifier` from `sklearn.tree` and apply its method `fit` on the training set.
```python
clf_gini = tree.DecisionTreeClassifier(random_state=0).fit(iris.data, iris.target)
```
To display the decision tree, we can use the function `plot_tree` from `sklearn.tree`:
```python
# to make the tree look better
options = {'feature_names': iris.feature_names,
'class_names': iris.target_names,
'filled': True,
'node_ids': True,
'rounded': True,
'fontsize': 6}
plt.figure(figsize=(9,6))
tree.plot_tree(clf_gini, **options)
plt.show()
```
For each node:
- `___ <= ___` is the splitting criterion for internal nodes, satisfied only by samples going left.
- `gini = ...` shows the impurity index. By default, the algorithm uses Gini impurity index to find the best binary split. Observe that the index decreases down the tree towards the leafs.
- `value = [_, _, _]` shows the number of examples for each of the three classes, and `class = ...` indicates a majority class, which may be used as the decision for a leaf node. The majority classes are also color coded. Observe that the color gets lighter towards the root, as the class distribution is more impure.
In particular, check that iris setosa is distinguished immediately after checking the petal width/length.
All the information of the decision is stored in the `tree_` attribute of the classifer. For more details:
```python
help(clf_gini.tree_)
```
**Exercise** Assign to `clf_entropy` the decision tree classifier created using *entropy* as the impurity measure. You can do so with the keyword argument `criterion='entropy'` in `DecisionTreeClassifier`. Furthermore, Use `random_state=0` and fit the classifier on the entire iris dataset. Check whether the resulting decision tree same as the one created using the Gini impurity index.
```python
# YOUR CODE HERE
raise NotImplementedError()
plt.figure(figsize=(9, 6))
tree.plot_tree(clf_entropy, **options)
plt.show()
```
YOUR ANSWER HERE
It is important to note that, although one can specify whether to use Gini impurity or entropy, `sklearn` implements neither C4.5 nor CART algorithms. In particular, it supports only binary splits on numeric input attributes, unlike C4.5 which supports multi-way splits using information gain ratio.
(See some [workarounds][categorical].)
[categorical]: https://stackoverflow.com/questions/38108832/passing-categorical-data-to-sklearn-decision-tree
## Compute Splitting Criterion
To understand how the decision tree is generated, we will implements the computation of the splitting criterion.
### Basic data analysis using `pandas`
To have an idea of qualities of the features, create a [`pandas`](https://pandas.pydata.org/docs/user_guide/index.html) [`DataFrame`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html?highlight=dataframe#pandas.DataFrame)
to operate on the dataset.
```python
# write the input features first
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
# append the target values to the last column
iris_df['target'] = iris.target
iris_df.target = iris_df.target.astype('category')
iris_df.target.cat.categories = iris.target_names
iris_df
```
To display some statistics of the input features for different classes:
```python
iris_df.groupby('target').boxplot(rot=90, layout=(1,3))
iris_df.groupby('target').agg(['mean','std']).round(2)
```
**Exercise** Identify good feature(s) based on the above statistics. Does you choice agree with the decision tree generated by `DecisionTreeClassifier`?
YOUR ANSWER HERE
### Compute impurity
Given a distribution $\boldsymbol{p}=(p_1,p_2,\dots)$ where $p_k\in [0,1]$ and $\sum_k p_k =1$, the Gini impurity index is defined as:
\begin{align}
\operatorname{Gini}(\boldsymbol{p}) = \operatorname{Gini}(p_1,p_2,\dots) &:= \sum_k p_k(1-p_k)\\
&= 1- \sum_k p_k^2.
\end{align}
We can represent a distribution simply as a `numpy` array. To return the empirical class distributions of the iris dataset:
```python
def dist(values):
'''Returns the empirical distribution of the given 1D array of values as a
1D array of probabilites.'''
counts = np.unique(values, return_counts=True)[-1]
return counts / counts.sum()
print(f"Distribution of target: {dist(iris.target).round(4)}")
```
The Gini impurity index can be computed as follows:
```python
def gini(p):
'''Returns the Gini impurity of distribution p.'''
return 1 - (p**2).sum()
print(f"Gini impurity of target: {gini(dist(iris.target)):.4g}")
```
**Exercise** Complete the following function to compute the entropy of a distribution:
\begin{align}
h(\boldsymbol{p}) = h(p_1,p_2,\dots) &= \sum_k - p_k \log_2 p_k\\
&= \sum_{k:p_k>0} - p_k \log_2 p_k.
\end{align}
You may use the function `log2` from `numpy` to calculate the logarithm base 2. Note that logarithm of $0$ is undefined, we use the last expression of the entropy to avoid taking the limit $\lim_{p\to 0} p\log p=0$.
You solution should look like:
```Python
def entropy(p):
...
return (p * ___ * ___).sum()
```
```python
def entropy(p):
'''Returns the entropy of distribution p.'''
p = np.array(p)
p = p[(p > 0) & (p < 1)] # 0 log 0 = 1 log 1 = 0
# YOUR CODE HERE
raise NotImplementedError()
```
```python
# tests
assert np.isclose(entropy([1/2, 1/2]), 1)
assert np.isclose(entropy([1, 0]), 0)
```
### Compute drop in impurity and best split
Now, to compute the drop in impurity for given splitting criterion:
\begin{align}
\Delta \operatorname{Gini}_{X\leq s}(Y) = \operatorname{Gini}(P_Y) - \left[\Pr\{X\leq s\} \operatorname{Gini}(P_{Y|X\leq s}) + \Pr\{X> s\}\operatorname{Gini}(P_{Y|X> s})\right]
\end{align}
```python
def drop_in_gini(X, Y, split_pt):
'''Returns the drop in Gini impurity of Y for the split X <= split_pt.
Parameters
----------
X: 1D array the values of a feature for different instances
Y: 1D array of the corresponding target values
split_pt: the value of the split point
'''
S = X <= split_pt
q = S.mean()
return gini(dist(Y)) - q * gini(dist(Y[S])) - (1 - q) * gini(dist(Y[~S]))
X, Y = iris_df['petal width (cm)'], iris_df.target
print(f"Drop in Gini: {drop_in_gini(X, Y, 0.8):.4g}")
```
To compute the best split point for a feature, we check every consecutive mid-points of the possible feature values:
```python
def find_best_split_pt(X, Y, gain_function):
'''Return the best split point s and the maximum gain evaluated using
gain_function for the split X <= s and target Y.
Parameters
----------
X: 1D array the values of a feature for different instances
Y: 1D array of the corresponding target values
gain_function: a function such as drop_in_gini for evaluating a split
Returns
-------
A tuple (s, g) where s is the best split point and g is the maximum gain.
See also
--------
drop_in_gini
'''
values = np.sort(np.unique(X))
split_pts = (values[1:] + values[:-1]) / 2
gain = np.array([gain_function(X, Y, s) for s in split_pts])
max_index = np.argmax(gain)
return split_pts[max_index], gain[max_index]
print('''Best split point: {0:.4g}
Maximum gain: {1:.4g}'''.format(*find_best_split_pt(X, Y, drop_in_gini)))
```
The following ranks the features according to the gains of their best binary splits:
```python
rank_by_gini = pd.DataFrame({
'feature': feature,
**(lambda s, g: {
'split point': s,
'gain': g
})(*find_best_split_pt(iris_df[feature], iris_df.target, drop_in_gini))
} for feature in iris.feature_names).sort_values(by='gain', ascending=False)
rank_by_gini
```
**Exercise** Complete the following function to calculate the *information gain* for a binary split $X\leq s$ and target $Y$:
\begin{align}
\operatorname{Gain}_{X\leq s}(Y) := h(P_Y) - \left[\Pr(X\leq s) h(P_{Y|X\leq s}) + \Pr(X> s) h(P_{Y|X> s})\right].
\end{align}
You may use `dist` and `entropy` defined previously.
```python
def info_gain(X, Y, split_pt):
'''Returns the information Gain of Y for the split X <= split_pt.
Parameters
----------
X: 1D array the values of a feature for different instances
Y: 1D array of the corresponding target values
split_pt: the value of the split point
'''
S = X <= split_pt
q = S.mean()
# YOUR CODE HERE
raise NotImplementedError()
print(f"Information gain: {info_gain(X, Y, 0.8):.4g}")
```
```python
# tests
rank_by_entropy = pd.DataFrame({
'feature':
feature,
**(lambda s, g: {
'split point': s,
'gain': g
})(*find_best_split_pt(iris_df[feature], iris_df.target, info_gain))
} for feature in iris.feature_names).sort_values(by='gain', ascending=False)
rank_by_entropy
```
**Exercise** Complete the following function to calculate the *information gain ratio* for a binary split $X\leq s$ and target $Y$:
\begin{align}
\operatorname{GainRatio}_{X\leq s}(Y) &:= \frac{\operatorname{Gain}_{X\leq s}(Y)}{\operatorname{SplitInfo}(X\leq s)} \qquad\text{where}\\
\operatorname{SplitInfo}(X\leq s) &:= h(\Pr(X\leq s),\Pr(X> s)).
\end{align}
You may use `entropy` and `info_gain` defined previously.
```python
def info_gain_ratio(X, Y, split_pt):
S = X <= split_pt
q = S.mean()
# YOUR CODE HERE
raise NotImplementedError()
```
```python
# tests
rank_by_info_gain_ratio = pd.DataFrame({
'feature':
feature,
**(lambda s, g: {
'split point': s,
'gain': g
})(*find_best_split_pt(iris_df[feature], iris_df.target, info_gain_ratio))
} for feature in iris.feature_names).sort_values(by='gain', ascending=False)
rank_by_info_gain_ratio
```
**Exercise** Does the information gain ratio give a different ranking of the features? Why?
Information gain ratio gives the same ranking as information gain in this case. This is because the split is restricted to be binary and so the normalization by split information has less effect on the ranking.
|
{- Copyright Β© 1992β2002 The University of Glasgow
Copyright Β© 2015 Benjamin Barenblat
Licensed under the Apache License, Version 2.0 (the βLicenseβ); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an βAS ISβ BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License. -}
module B.Prelude.Functor where
import Category.Monad as Monad
import Category.Functor
import Data.List
import Data.Maybe
open import Function using (_β_)
open Category.Functor
using (RawFunctor)
public
open Category.Functor.RawFunctor β¦...β¦
using (_<$>_)
public
instance
Functor-List : β {β} β RawFunctor (Data.List.List {β})
Functor-List = Monad.RawMonad.rawFunctor Data.List.monad
Functor-Maybe : β {β} β RawFunctor (Data.Maybe.Maybe {β})
Functor-Maybe = Monad.RawMonad.rawFunctor Data.Maybe.monad
Functor-Function : β {β} {r : Set β} β RawFunctor {β} (Ξ» s β (r β s))
Functor-Function {r} =
-- I could say _<$>_ = _β_ here, but that makes type checking much more
-- challenging.
record { _<$>_ = Ξ» f g β f β g }
-- TODO: Do proper instance for dependent pairs
|
(* Title: HOL/Metis_Examples/Abstraction.thy
Author: Lawrence C. Paulson, Cambridge University Computer Laboratory
Author: Jasmin Blanchette, TU Muenchen
Example featuring Metis's support for lambda-abstractions.
*)
section \<open>Example Featuring Metis's Support for Lambda-Abstractions\<close>
theory Abstraction
imports "~~/src/HOL/Library/FuncSet"
begin
(* For Christoph BenzmΓΌller *)
lemma "x < 1 \<and> ((op =) = (op =)) \<Longrightarrow> ((op =) = (op =)) \<and> x < (2::nat)"
by (metis nat_1_add_1 trans_less_add2)
lemma "(op = ) = (\<lambda>x y. y = x)"
by metis
consts
monotone :: "['a => 'a, 'a set, ('a *'a)set] => bool"
pset :: "'a set => 'a set"
order :: "'a set => ('a * 'a) set"
lemma "a \<in> {x. P x} \<Longrightarrow> P a"
proof -
assume "a \<in> {x. P x}"
thus "P a" by (metis mem_Collect_eq)
qed
lemma Collect_triv: "a \<in> {x. P x} \<Longrightarrow> P a"
by (metis mem_Collect_eq)
lemma "a \<in> {x. P x --> Q x} \<Longrightarrow> a \<in> {x. P x} \<Longrightarrow> a \<in> {x. Q x}"
by (metis Collect_imp_eq ComplD UnE)
lemma "(a, b) \<in> Sigma A B \<Longrightarrow> a \<in> A \<and> b \<in> B a"
proof -
assume A1: "(a, b) \<in> Sigma A B"
hence F1: "b \<in> B a" by (metis mem_Sigma_iff)
have F2: "a \<in> A" by (metis A1 mem_Sigma_iff)
have "b \<in> B a" by (metis F1)
thus "a \<in> A \<and> b \<in> B a" by (metis F2)
qed
lemma Sigma_triv: "(a, b) \<in> Sigma A B \<Longrightarrow> a \<in> A & b \<in> B a"
by (metis SigmaD1 SigmaD2)
lemma "(a, b) \<in> (SIGMA x:A. {y. x = f y}) \<Longrightarrow> a \<in> A \<and> a = f b"
by (metis (full_types, lifting) CollectD SigmaD1 SigmaD2)
lemma "(a, b) \<in> (SIGMA x:A. {y. x = f y}) \<Longrightarrow> a \<in> A \<and> a = f b"
proof -
assume A1: "(a, b) \<in> (SIGMA x:A. {y. x = f y})"
hence F1: "a \<in> A" by (metis mem_Sigma_iff)
have "b \<in> {R. a = f R}" by (metis A1 mem_Sigma_iff)
hence "a = f b" by (metis (full_types) mem_Collect_eq)
thus "a \<in> A \<and> a = f b" by (metis F1)
qed
lemma "(cl, f) \<in> CLF \<Longrightarrow> CLF = (SIGMA cl: CL.{f. f \<in> pset cl}) \<Longrightarrow> f \<in> pset cl"
by (metis Collect_mem_eq SigmaD2)
lemma "(cl, f) \<in> CLF \<Longrightarrow> CLF = (SIGMA cl: CL.{f. f \<in> pset cl}) \<Longrightarrow> f \<in> pset cl"
proof -
assume A1: "(cl, f) \<in> CLF"
assume A2: "CLF = (SIGMA cl:CL. {f. f \<in> pset cl})"
have "\<forall>v u. (u, v) \<in> CLF \<longrightarrow> v \<in> {R. R \<in> pset u}" by (metis A2 mem_Sigma_iff)
hence "\<forall>v u. (u, v) \<in> CLF \<longrightarrow> v \<in> pset u" by (metis mem_Collect_eq)
thus "f \<in> pset cl" by (metis A1)
qed
lemma
"(cl, f) \<in> (SIGMA cl: CL. {f. f \<in> pset cl \<rightarrow> pset cl}) \<Longrightarrow>
f \<in> pset cl \<rightarrow> pset cl"
by (metis (no_types) Collect_mem_eq Sigma_triv)
lemma
"(cl, f) \<in> (SIGMA cl: CL. {f. f \<in> pset cl \<rightarrow> pset cl}) \<Longrightarrow>
f \<in> pset cl \<rightarrow> pset cl"
proof -
assume A1: "(cl, f) \<in> (SIGMA cl:CL. {f. f \<in> pset cl \<rightarrow> pset cl})"
have "f \<in> {R. R \<in> pset cl \<rightarrow> pset cl}" using A1 by simp
thus "f \<in> pset cl \<rightarrow> pset cl" by (metis mem_Collect_eq)
qed
lemma
"(cl, f) \<in> (SIGMA cl: CL. {f. f \<in> pset cl \<inter> cl}) \<Longrightarrow>
f \<in> pset cl \<inter> cl"
by (metis (no_types) Collect_conj_eq Int_def Sigma_triv inf_idem)
lemma
"(cl, f) \<in> (SIGMA cl: CL. {f. f \<in> pset cl \<inter> cl}) \<Longrightarrow>
f \<in> pset cl \<inter> cl"
proof -
assume A1: "(cl, f) \<in> (SIGMA cl:CL. {f. f \<in> pset cl \<inter> cl})"
have "f \<in> {R. R \<in> pset cl \<inter> cl}" using A1 by simp
hence "f \<in> Id_on cl `` pset cl" by (metis Int_commute Image_Id_on mem_Collect_eq)
hence "f \<in> cl \<inter> pset cl" by (metis Image_Id_on)
thus "f \<in> pset cl \<inter> cl" by (metis Int_commute)
qed
lemma
"(cl, f) \<in> (SIGMA cl: CL. {f. f \<in> pset cl \<rightarrow> pset cl & monotone f (pset cl) (order cl)}) \<Longrightarrow>
(f \<in> pset cl \<rightarrow> pset cl) & (monotone f (pset cl) (order cl))"
by auto
lemma
"(cl, f) \<in> CLF \<Longrightarrow>
CLF \<subseteq> (SIGMA cl: CL. {f. f \<in> pset cl \<inter> cl}) \<Longrightarrow>
f \<in> pset cl \<inter> cl"
by (metis (lifting) CollectD Sigma_triv subsetD)
lemma
"(cl, f) \<in> CLF \<Longrightarrow>
CLF = (SIGMA cl: CL. {f. f \<in> pset cl \<inter> cl}) \<Longrightarrow>
f \<in> pset cl \<inter> cl"
by (metis (lifting) CollectD Sigma_triv)
lemma
"(cl, f) \<in> CLF \<Longrightarrow>
CLF \<subseteq> (SIGMA cl': CL. {f. f \<in> pset cl' \<rightarrow> pset cl'}) \<Longrightarrow>
f \<in> pset cl \<rightarrow> pset cl"
by (metis (lifting) CollectD Sigma_triv subsetD)
lemma
"(cl, f) \<in> CLF \<Longrightarrow>
CLF = (SIGMA cl: CL. {f. f \<in> pset cl \<rightarrow> pset cl}) \<Longrightarrow>
f \<in> pset cl \<rightarrow> pset cl"
by (metis (lifting) CollectD Sigma_triv)
lemma
"(cl, f) \<in> CLF \<Longrightarrow>
CLF = (SIGMA cl: CL. {f. f \<in> pset cl \<rightarrow> pset cl & monotone f (pset cl) (order cl)}) \<Longrightarrow>
(f \<in> pset cl \<rightarrow> pset cl) & (monotone f (pset cl) (order cl))"
by auto
lemma "map (\<lambda>x. (f x, g x)) xs = zip (map f xs) (map g xs)"
apply (induct xs)
apply (metis list.map(1) zip_Nil)
by auto
lemma
"map (\<lambda>w. (w \<rightarrow> w, w \<times> w)) xs =
zip (map (\<lambda>w. w \<rightarrow> w) xs) (map (\<lambda>w. w \<times> w) xs)"
apply (induct xs)
apply (metis list.map(1) zip_Nil)
by auto
lemma "(\<lambda>x. Suc (f x)) ` {x. even x} \<subseteq> A \<Longrightarrow> \<forall>x. even x --> Suc (f x) \<in> A"
by (metis mem_Collect_eq image_eqI subsetD)
lemma
"(\<lambda>x. f (f x)) ` ((\<lambda>x. Suc(f x)) ` {x. even x}) \<subseteq> A \<Longrightarrow>
(\<forall>x. even x --> f (f (Suc(f x))) \<in> A)"
by (metis mem_Collect_eq imageI set_rev_mp)
lemma "f \<in> (\<lambda>u v. b \<times> u \<times> v) ` A \<Longrightarrow> \<forall>u v. P (b \<times> u \<times> v) \<Longrightarrow> P(f y)"
by (metis (lifting) imageE)
lemma image_TimesA: "(\<lambda>(x, y). (f x, g y)) ` (A \<times> B) = (f ` A) \<times> (g ` B)"
by (metis map_prod_def map_prod_surj_on)
lemma image_TimesB:
"(\<lambda>(x, y, z). (f x, g y, h z)) ` (A \<times> B \<times> C) = (f ` A) \<times> (g ` B) \<times> (h ` C)"
by force
lemma image_TimesC:
"(\<lambda>(x, y). (x \<rightarrow> x, y \<times> y)) ` (A \<times> B) =
((\<lambda>x. x \<rightarrow> x) ` A) \<times> ((\<lambda>y. y \<times> y) ` B)"
by (metis image_TimesA)
end
|
A study of a closely related southeast Asian Astraeus species concluded that the fungus contained an abundance of volatile eight @-@ carbon compounds ( including 1 @-@ octanol , 1 @-@ octen @-@ 3 @-@ ol , and 1 @-@ octen @-@ 3 @-@ one ) that imparted a " mushroom @-@ like , earthy , and pungent odor that was evident as an oily and moss @-@ like smell upon opening the caps " . The study 's authors further noted that the fruit bodies after cooking have a " roasted , <unk> , herbal , and oily flavor " . Volatile compounds detected after cooking the mushroom samples included furfural , benzaldehyde , <unk> , and <unk> compounds . The regional differences in opinions on edibility are from sources published before it was known that North American and Asian versions of A. hygrometricus were not always the same ; in some cases Asian specimens have been identified as new species , such as A. asiaticus and A. odoratus .
|
I have a child of a MDI container and I don't want the user to be able to close it, or maximize, or minimize it. But I do want the user to be able to resize it and drag it around and will. So I want to get rid of the close, minimize and maximize buttons but retain the blue strip.
Where "this" is some form, you may find yourself with a control lacking a blue strip to move the form around! The solution to this problem is to enter some text in the text field.
And that seems to be how it's done. Of course there are other ways override the message handler or using PInvoke (yes I tried Google before working this out for myself) but you really don't need to.
You can always add a delegate to listen for the FormClosing event. |
#ifndef BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP
#define BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP
// (C) Copyright 2005 Matthias Troyer
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/strong_typedef.hpp>
#include <boost/serialization/level.hpp>
namespace boost { namespace serialization {
BOOST_STRONG_TYPEDEF(std::size_t, collection_size_type)
} } // end namespace boost::serialization
BOOST_CLASS_IMPLEMENTATION(boost::serialization::collection_size_type, primitive_type)
#endif //BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP
|
(****************************************************************************)
chapter {* Automated Reasoning Course
Jacques Fleuriot
Propositional Logic in Isabelle *}
(****************************************************************************)
theory Prop
imports Main
begin
(****************************************************************************)
section {* Introduction *}
text {* This Isabelle theory file accompanies Lectures 2-4 of the
Automated Reasoning course. By stepping through it you should become
familiar with how to undertake propositional logic proofs in Isabelle. *}
(****************************************************************************)
section {* First theorems *}
theorem K: "A \<longrightarrow> B \<longrightarrow> A"
apply (rule impI)
apply (rule impI)
apply assumption
done
text {* The rules "impI" and "assumption" above are examples of
Isabelle proof methods.
After processing "done" above, the front-end will
display a version of the theorem with the A and B replaced by
?A and ?B. These are schematic or meta
variables that can be freely instantiated if theorem K is used
in some further proof.
Theorems can involve assumptions from the start. For example,
here is the Isabelle version of the natural deduction
derivation of A, B \<turnstile> A \<and> (B \<and> A) *}
theorem a_conj_theorem: "\<lbrakk> A ; B \<rbrakk> \<Longrightarrow> A \<and> (B \<and> A)"
apply (rule conjI)
apply assumption
apply (rule conjI)
apply assumption
apply assumption
done
text {* We can add "+" to the end of a method in order to apply it
more than once. We can also use the keyword "by" instead
of "apply" for the final line of the proof. This allows us
to discard the "done". So, the same theorem can be proved
as follows: *}
theorem a_conj_theorem2: "\<lbrakk> A ; B \<rbrakk> \<Longrightarrow> A \<and> (B \<and> A)"
apply (rule conjI)
apply assumption
apply (rule conjI)
by assumption+
(****************************************************************************)
section {* More On Applying Rules *}
text {* A simple propositional fact is B \<or> A from the
assumption A \<or> B. In Isabelle, this lemma can
be proved as follows: *}
lemma "A \<or> B \<Longrightarrow> B \<or> A"
apply (erule disjE)
apply (rule disjI2)
apply assumption
apply (rule disjI1)
by assumption
text {* It is instructive to see what happens when we apply a rule
backward such that not all of its variables can be immediately
instantiated. Look at what happens below after "rule
disjE". We get schematic variables in both subgoals that then
are instantiated once we apply the assumption method on the
1st subgoal. *}
lemma "A \<or> B \<Longrightarrow> B \<or> A"
apply (rule disjE)
apply assumption
apply (rule disjI2)
apply assumption
apply (rule disjI1)
by assumption
(****************************************************************************)
section {* More Methods *}
text {* Isabelle also provides the methods "drule" and "frule" for
forwards reasoning. These are best used with destruction rules. For
example:
*}
lemma "A \<and> B \<Longrightarrow> A"
apply (drule conjunct1)
by assumption
lemma "A \<and> B \<Longrightarrow> A"
apply (frule conjunct1)
by assumption
(****************************************************************************)
section {* Problems Revisited *}
text{* We can now return to the three problems first posed in Lecture
2. The written proof of Example 1 is shown in Lecture 3. Its
equivalent Isabelle proof is: *}
lemma example1: "(SunnyTomorrow \<or> RainyTomorrow) \<and> \<not>SunnyTomorrow
\<longrightarrow> RainyTomorrow"
apply (rule impI)
apply (erule conjE)
apply (erule disjE)
apply (erule notE)
by assumption+
text{* The proofs of Examples 2 and 3 are: *}
lemma example2: "(Class \<or> Pop) \<and> (Class \<longrightarrow> Soph) \<and> \<not>Pop \<longrightarrow> Soph"
apply (rule impI)
apply (erule conjE)+
apply (erule disjE)
apply (erule impE)
apply assumption+
apply (erule notE)
by assumption
lemma example3: "(M \<or> L) \<and> (M \<or> W) \<and> \<not>(L \<and> W) \<longrightarrow> M \<or> (M \<and> L) \<or> (M \<and> W)"
apply (rule impI)
apply (erule conjE)+
apply (erule disjE)
apply (erule disjE)
apply (rule disjI1)
apply assumption
apply (rule disjI1)
apply assumption
apply (erule disjE)
apply (rule disjI1)
apply assumption
apply (erule notE)
apply (rule conjI)
by assumption+
(*****************************************************************************)
section {* Applying Rules to Correct Assumptions *}
text {* Consider the following lemma and proof: *}
lemma conj_elim1: "\<lbrakk> A \<and> B; C \<and> D \<rbrakk> \<Longrightarrow> D"
apply (erule conjE)
apply (erule conjE)
by assumption
text {* Notice that in this proof we had to apply the rule "conjE"
twice in order to eliminate the conjunction in the second
assumption. We could have avoided writing the extra proof step
by using "+":
*}
lemma conj_elim2: "\<lbrakk> A \<and> B; C \<and> D \<rbrakk> \<Longrightarrow> D"
apply (erule conjE)+
by assumption
text {* Although this new proof is shorter, we have still carried out an
unnecessary step: we do not need to eliminate the
conjunction in the first assumption. If we want to apply "conjE"
to a an assumption different from the first one it matches, then
we can rotate the ordering of our assumptions. To do this Isabelle
provides a tactic called "rotate_tac". An alternative proof is
thus:
*}
lemma conj_elim3: "\<lbrakk> A \<and> B; C \<and> D \<rbrakk> \<Longrightarrow> D"
apply (rotate_tac 1)
apply (erule conjE)
by assumption
text {* If our list of assumptions is very large, we may not want to use
"rotate_tac". A better approach is to explicitly tell Isabelle
what instantiations the variables in a rule should take when we apply
it. To do this we use the methods "rule_tac", "erule_tac",
"drule_tac" and "frule_tac". Our alternative proof of
"conj_elim" is:
*}
lemma conj_elim4: "\<lbrakk> A \<and> B; C \<and> D \<rbrakk> \<Longrightarrow> D"
apply (erule_tac P=C and Q=D in conjE)
by assumption
text {* In the above proof it is not neccessary to tell Isabelle the variable
Q in the rule "conjE" should be instantiated to D.
Isabelle can automatically infer this! So our proof becomes:
*}
lemma conj_elim5: "\<lbrakk> A \<and> B; C \<and> D \<rbrakk> \<Longrightarrow> D"
apply (erule_tac P=C in conjE)
by assumption
(*****************************************************************************)
section{* More Rules of the Game *}
text {* If you start proving a lemma but get stuck, you can always
type the command "oops" to abandon the proof. For example:
*}
lemma A_and_B_imp_B_or_A: "A \<and> B \<longrightarrow> B \<or> A"
oops
text {* Now imagine we want to use A \<and> B \<longrightarrow> B \<or> A to prove
later lemmas and theorems. As it is not a rule (since it does
not have the \<Longrightarrow>) we use it by inserting it as an
assumption in our proof. This is done using
a tactic called "cut_tac". Consider the following lemma and
try uncommenting the "apply" command.
*}
lemma "A \<and> B \<Longrightarrow> B \<or> A"
(* apply (cut_tac A_and_B_imp_B_or_A)*)
(* Isabelle complains! *)
oops
text {* When we try to insert A \<and> B \<longrightarrow> B \<or> A into our proof
Isabelle complains. This is because Isabelle does not know
the theorem. The command "oops" allowed us to abandon our
proof, but it also told Isabelle to forget the lemma completely.
To allow Isabelle to continue checking this theory, comment out
again the "apply" command above.
Instead of using "oops", we could have used the command
"sorry":
*}
lemma A_and_B_imp_B_or_A_take2: "A \<and> B \<longrightarrow> B \<or> A"
sorry
text {* The command "sorry" tells Isabelle to abandon the proof
but pretend that the lemma has been proved. This allows us to use it
in later proofs:
*}
lemma cut_in_action: "A \<and> B \<Longrightarrow> B \<or> A"
apply (cut_tac A_and_B_imp_B_or_A_take2)
apply (erule impE)
apply assumption+
done
text {* A word of warning: "sorry" is a cheat allowing you to make
progress. You should return to the incomplete proof and finish it
to be completely sure the rest of your theory is valid.
*}
(*****************************************************************************)
section {* Automation *}
text{* It may seem tedious having to type in all these commands. Isabelle does
provide a fair amount of automation. The tactics "simp" and "auto" both
use the classical reasoner of Isabelle and can make life a lot easier.
Example:
*}
lemma proved_by_simp: "A \<and> B \<Longrightarrow> B \<or> A"
by simp
lemma proved_by_auto: "A \<and> B \<Longrightarrow> B \<or> A"
by auto
end
|
Formal statement is: lemma continuous_on_ext_cont[continuous_intros]: "continuous_on (cbox a b) f \<Longrightarrow> continuous_on S (ext_cont f a b)" Informal statement is: If $f$ is continuous on the closed interval $[a,b]$, then the extension of $f$ to the whole real line is continuous on any set $S$. |
(*<*)
theory SPRViewNonDet
imports
SPRView
KBPsAuto
begin
(*>*)
subsection{*Perfect Recall in Non-deterministic Broadcast Environments*}
text_raw{*
\begin{figure}[ht]
\begin{isabellebody}%
*}
record ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState =
es :: "'es"
ps :: "'a \<Rightarrow> 'ps"
pubActs :: "'ePubAct \<times> ('a \<Rightarrow> 'pPubAct)"
locale FiniteBroadcastEnvironment =
Environment jkbp envInit envAction envTrans envVal envObs
for jkbp :: "('a :: finite, 'p, ('pPubAct :: finite \<times> 'ps :: finite)) JKBP"
and envInit
:: "('a, 'ePubAct :: finite, 'es :: finite, 'pPubAct, 'ps) BEState list"
and envAction :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState
\<Rightarrow> ('ePubAct \<times> 'ePrivAct) list"
and envTrans :: "('ePubAct \<times> 'ePrivAct)
\<Rightarrow> ('a \<Rightarrow> ('pPubAct \<times> 'ps))
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState"
and envVal :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState \<Rightarrow> 'p \<Rightarrow> bool"
and envObs :: "'a \<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState
\<Rightarrow> ('cobs \<times> 'ps \<times> ('ePubAct \<times> ('a \<Rightarrow> 'pPubAct)))"
+ fixes envObsC :: "'es \<Rightarrow> 'cobs"
and envActionES :: "'es \<Rightarrow> ('ePubAct \<times> ('a \<Rightarrow> 'pPubAct))
\<Rightarrow> ('ePubAct \<times> 'ePrivAct) list"
and envTransES :: "('ePubAct \<times> 'ePrivAct) \<Rightarrow> ('a \<Rightarrow> 'pPubAct)
\<Rightarrow> 'es \<Rightarrow> 'es"
defines envObs_def: "envObs a \<equiv> (\<lambda>s. (envObsC (es s), ps s a, pubActs s))"
and envAction_def: "envAction s \<equiv> envActionES (es s) (pubActs s)"
and envTrans_def:
"envTrans eact aact s \<equiv> \<lparr> es = envTransES eact (fst \<circ> aact) (es s)
, ps = snd \<circ> aact
, pubActs = (fst eact, fst \<circ> aact) \<rparr>"
text_raw{*
\end{isabellebody}%
\caption{Finite broadcast environments with non-deterministic KBPs.}
\label{fig:kbps-theory-broadcast-envs}
\end{figure}
*}
(*<*)
instance BEState_ext :: (finite, finite, finite, finite, finite, finite) finite
proof
let ?U = "UNIV :: ('a, 'b, 'c, 'd, 'e, 'f) BEState_ext set"
{ fix x :: "('a, 'b, 'c, 'd, 'e, 'f) BEState_scheme"
have "\<exists>a b c d. x = BEState_ext a b c d"
by (cases x) simp
} then have U:
"?U = (\<lambda>(((a, b), c), d). BEState_ext a b c d) ` (((UNIV \<times> UNIV) \<times> UNIV) \<times> UNIV)"
by (auto simp add: image_def)
show "finite ?U" by (simp add: U)
qed
(*>*)
text{*
\label{sec:kbps-theory-spr-non-deterministic-protocols}
For completeness we reproduce the results of \citet{Ron:1996}
regarding non-deterministic KBPs in broadcast environments.
The determinism requirement is replaced by the constraint that actions
be split into public and private components, where the private part
influences the agents' private states, and the public part is
broadcast and recorded in the system state. Moreover the protocol of
the environment is only a function of the environment state, and not
the agents' private states. Once again an agent's view consists of the
common observation and their private state. The situation is described
by the locale in Figure~\ref{fig:kbps-theory-broadcast-envs}. Note
that as we do not intend to generate code for this case, we adopt more
transparent but less effective representations.
Our goal in the following is to instantiate the @{term
"SimIncrEnvironment"} locale with respect to the assumptions made in
the @{term "FiniteBroadcastEnvironment"} locale. We begin by defining
similar simulation machinery to the previous section.
*}
context FiniteBroadcastEnvironment
begin
text{*
As for the deterministic variant, we abstract traces using the common
observation. Note that this now includes the public part of the
agents' actions.
*}
definition
tObsC :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> ('cobs \<times> 'ePubAct \<times> ('a \<Rightarrow> 'pPubAct)) Trace"
where
"tObsC \<equiv> tMap (\<lambda>s. (envObsC (es s), pubActs s))"
(*<*)
lemma spr_jview_tObsC:
assumes "spr_jview a t = spr_jview a t'"
shows "tObsC t = tObsC t'"
using SPR.sync[rule_format, OF assms] assms
by (induct rule: trace_induct2) (auto simp: envObs_def tObsC_def)
lemma tObsC_tLength:
"tObsC t = tObsC t' \<Longrightarrow> tLength t = tLength t'"
unfolding tObsC_def by (rule tMap_eq_imp_tLength_eq)
lemma tObsC_tStep_eq_inv:
"tObsC t' = tObsC (t \<leadsto> s) \<Longrightarrow> \<exists>t'' s'. t' = t'' \<leadsto> s'"
unfolding tObsC_def by auto
lemma tObsC_prefix_closed[dest]:
"tObsC (t \<leadsto> s) = tObsC (t' \<leadsto> s') \<Longrightarrow> tObsC t = tObsC t'"
unfolding tObsC_def by simp
lemma tObsC_tLast[iff]:
"tLast (tObsC t) = (envObsC (es (tLast t)), pubActs (tLast t))"
unfolding tObsC_def by simp
lemma tObsC_tStep:
"tObsC (t \<leadsto> s) = tObsC t \<leadsto> (envObsC (es s), pubActs s)"
unfolding tObsC_def by simp
lemma tObsC_initial[iff]:
"tFirst (tObsC t) = (envObsC (es (tFirst t)), pubActs (tFirst t))"
"tObsC (tInit s) = tInit (envObsC (es s), pubActs s)"
"tObsC t = tInit cobs \<longleftrightarrow> (\<exists>s. t = tInit s \<and> envObsC (es s) = fst cobs \<and> pubActs s = snd cobs)"
unfolding tObsC_def by auto
lemma spr_tObsC_trc_aux:
assumes "(t, t') \<in> (\<Union>a. relations SPR.MC a)\<^sup>*"
shows "tObsC t = tObsC t'"
using assms
apply (induct)
apply simp
apply clarsimp
apply (rule_tac a=x in spr_jview_tObsC)
apply simp
done
(*>*)
text{*
Similarly we introduce common and agent-specific abstraction functions:
*}
definition
tObsC_abs :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Relation"
where
"tObsC_abs t \<equiv> { (tFirst t', tLast t')
|t'. t' \<in> SPR.jkbpC \<and> tObsC t' = tObsC t }"
definition
agent_abs :: "'a \<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Relation"
where
"agent_abs a t \<equiv> { (tFirst t', tLast t')
|t'. t' \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t }"
(*<*)
lemma tObsC_abs_jview_eq[dest, intro]:
"spr_jview a t' = spr_jview a t
\<Longrightarrow> tObsC_abs t = tObsC_abs t'"
unfolding tObsC_abs_def by (fastforce dest: spr_jview_tObsC)
lemma tObsC_absI[intro]:
"\<lbrakk> t' \<in> SPR.jkbpC; tObsC t' = tObsC t; u = tFirst t'; v = tLast t' \<rbrakk>
\<Longrightarrow> (u, v) \<in> tObsC_abs t"
unfolding tObsC_abs_def by blast
lemma tObsC_abs_conv:
"(u, v) \<in> tObsC_abs t
\<longleftrightarrow> (\<exists>t'. t' \<in> SPR.jkbpC \<and> tObsC t' = tObsC t \<and> u = tFirst t' \<and> v = tLast t')"
unfolding tObsC_abs_def by blast
lemma agent_absI[elim]:
"\<lbrakk> t' \<in> SPR.jkbpC; spr_jview a t' = spr_jview a t; u = tFirst t'; v = tLast t' \<rbrakk>
\<Longrightarrow> (u, v) \<in> agent_abs a t"
unfolding agent_abs_def by blast
lemma agent_abs_tLastD[simp]:
"(u, v) \<in> agent_abs a t \<Longrightarrow> envObs a v = envObs a (tLast t)"
unfolding agent_abs_def by auto
lemma agent_abs_inv[dest]:
"(u, v) \<in> agent_abs a t
\<Longrightarrow> \<exists>t'. t' \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t
\<and> u = tFirst t' \<and> v = tLast t'"
unfolding agent_abs_def by blast
(*>*)
end (* context FiniteBroadcastEnvironment *)
text{*
The simulation is identical to that in the previous section:
*}
record ('a, 'ePubAct, 'es, 'pPubAct, 'ps) SPRstate =
sprFst :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState"
sprLst :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState"
sprCRel :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Relation"
context FiniteBroadcastEnvironment
begin
definition
spr_sim :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) SPRstate"
where
"spr_sim \<equiv> \<lambda>t. \<lparr> sprFst = tFirst t, sprLst = tLast t, sprCRel = tObsC_abs t \<rparr>"
(*<*)
lemma spr_sim_tFirst_tLast:
"\<lbrakk> spr_sim t = s; t \<in> SPR.jkbpC \<rbrakk> \<Longrightarrow> (sprFst s, sprLst s) \<in> sprCRel s"
unfolding spr_sim_def by auto
(*>*)
text{*
The Kripke structure over simulated traces is also the same:
*}
definition
spr_simRels :: "'a \<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) SPRstate Relation"
where
"spr_simRels \<equiv> \<lambda>a. { (s, s') |s s'.
envObs a (sprFst s) = envObs a (sprFst s')
\<and> envObs a (sprLst s) = envObs a (sprLst s')
\<and> sprCRel s = sprCRel s' }"
definition
spr_simVal :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) SPRstate \<Rightarrow> 'p \<Rightarrow> bool"
where
"spr_simVal \<equiv> envVal \<circ> sprLst"
abbreviation
"spr_simMC \<equiv> mkKripke (spr_sim ` SPR.jkbpC) spr_simRels spr_simVal"
(*<*)
lemma spr_simVal_def2[iff]:
"spr_simVal (spr_sim t) = envVal (tLast t)"
unfolding spr_sim_def spr_simVal_def by simp
(*>*)
text{*
As usual, showing that @{term "spr_sim"} is in fact a simulation is
routine for all properties except for reverse simulation. For that we
use proof techniques similar to those of
\citet{DBLP:journals/tocl/LomuscioMR00}: the goal is to show that,
given @{term "t \<in> jkbpC"}, we can construct a trace @{term "t' \<in>
jkbpC"} indistinguishable from @{term "t"} by agent @{term "a"}, based
on the public actions, the common observation and @{term "a"}'s
private and initial states.
To do this we define a splicing operation:
*}
definition
sSplice :: "'a
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState"
where
"sSplice a s s' \<equiv> s\<lparr> ps := (ps s)(a := ps s' a) \<rparr>"
(*<*)
lemma sSplice_es[simp]:
"es (sSplice a s s') = es s"
unfolding sSplice_def by simp
lemma sSplice_pubActs[simp]:
"pubActs (sSplice a s s') = pubActs s"
unfolding sSplice_def by simp
lemma sSplice_envObs[simp]:
assumes init: "envObs a s = envObs a s'"
shows "sSplice a s s' = s"
proof -
from init have "ps s a = ps s' a"
by (auto simp: envObs_def)
thus ?thesis
unfolding sSplice_def by (simp add: fun_upd_idem_iff)
qed
lemma sSplice_envObs_a:
assumes "envObsC (es s) = envObsC (es s')"
assumes "pubActs s = pubActs s'"
shows "envObs a (sSplice a s s') = envObs a s'"
using assms
unfolding sSplice_def envObs_def by simp
lemma sSplice_envObs_not_a:
assumes "a' \<noteq> a"
shows "envObs a' (sSplice a s s') = envObs a' s"
using assms
unfolding sSplice_def envObs_def by simp
(*>*)
text{*
The effect of @{term "sSplice a s s'"} is to update @{term "s"} with
@{term "a"}'s private state in @{term "s'"}. The key properties are
that provided the common observation on @{term "s"} and @{term "s'"}
are the same, then agent @{term "a"}'s observation on @{term "sSplice
a s s'"} is the same as
at @{term "s'"}, while everyone else's is the
same as at @{term "s"}.
We hoist this operation pointwise to traces:
*}
abbreviation
tSplice :: "('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> 'a
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace
\<Rightarrow> ('a, 'ePubAct, 'es, 'pPubAct, 'ps) BEState Trace"
("_ \<^bsub>\<^esub>\<bowtie>\<^bsub>_\<^esub> _" [55, 1000, 56] 55)
where
"t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t' \<equiv> tZip (sSplice a) t t'"
(*<*)
declare sSplice_envObs_a[simp] sSplice_envObs_not_a[simp]
lemma tSplice_tObsC:
assumes tObsC: "tObsC t = tObsC t'"
shows "tObsC (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') = tObsC t"
using tObsC_tLength[OF tObsC] tObsC
by (induct rule: trace_induct2) (simp_all add: tObsC_tStep)
lemma tSplice_spr_jview_a:
assumes tObsC: "tObsC t = tObsC t'"
shows "spr_jview a (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') = spr_jview a t'"
using tObsC_tLength[OF tObsC] tObsC
by (induct rule: trace_induct2) (simp_all add: tObsC_tStep spr_jview_def)
lemma tSplice_spr_jview_not_a:
assumes tObsC: "tObsC t = tObsC t'"
assumes aa': "a \<noteq> a'"
shows "spr_jview a' (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') = spr_jview a' t"
using tObsC_tLength[OF tObsC] tObsC aa'
by (induct rule: trace_induct2) (simp_all add: tObsC_tStep spr_jview_def)
lemma tSplice_es:
assumes tLen: "tLength t = tLength t'"
shows "es (tLast (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t')) = es (tLast t)"
using tLen by (induct rule: trace_induct2) simp_all
lemma tSplice_pubActs:
assumes tLen: "tLength t = tLength t'"
shows "pubActs (tLast (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t')) = pubActs (tLast t)"
using tLen by (induct rule: trace_induct2) simp_all
lemma tSplice_tFirst[simp]:
assumes tLen: "tLength t = tLength t'"
assumes init: "envObs a (tFirst t) = envObs a (tFirst t')"
shows "tFirst (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') = tFirst t"
using tLen init by (induct rule: trace_induct2) simp_all
lemma tSplice_tLast[simp]:
assumes tLen: "tLength t = tLength t'"
assumes last: "envObs a (tLast t) = envObs a (tLast t')"
shows "tLast (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') = tLast t"
using tLen last
unfolding envObs_def
apply (induct rule: trace_induct2)
apply (auto iff: sSplice_def fun_upd_idem_iff)
done
(*>*)
text{*
The key properties are that after splicing, if @{term "t"} and @{term
"t'"} have the same common observation, then so does @{term "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub>
t'"}, and for all agents @{term "a' \<noteq> a"}, the view @{term "a'"} has
of @{term "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t'"} is the same as it has of @{term "t"}, while for
@{term "a"} it is the same as @{term "t'"}.
We can conclude that provided the two traces are initially
indistinguishable to @{term "a"}, and not commonly distinguishable,
then @{term "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t'"} is a canonical trace:
*}
lemma tSplice_jkbpC:
assumes tt': "{t, t'} \<subseteq> SPR.jkbpC"
assumes init: "envObs a (tFirst t) = envObs a (tFirst t')"
assumes tObsC: "tObsC t = tObsC t'"
shows "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t' \<in> SPR.jkbpC"
(*<*)
using tObsC_tLength[OF tObsC] tt' init tObsC
proof(induct rule: trace_induct2)
case (tInit s s') thus ?case by simp
next
case (tStep s s' t t')
hence tt': "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t' \<in> SPR.jkbpC"
and tLen: "tLength t' = tLength t"
and tObsC: "tObsC (t \<leadsto> s) = tObsC (t' \<leadsto> s')"
by auto
hence tt'n: "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t' \<in> SPR.jkbpCn (tLength t)"
by auto
from tStep
have ts: "t \<leadsto> s \<in> SPR.jkbpCn (Suc (tLength t))"
and t's': "t' \<leadsto> s' \<in> SPR.jkbpCn (Suc (tLength t'))"
apply -
apply ((rule SPR.jkbpC_tLength_inv, simp_all)[1])+
done
from ts obtain eact aact
where eact: "eact \<in> set (envAction (tLast t))"
and aact: "\<forall>a. aact a \<in> set (jAction (SPR.mkM (SPR.jkbpCn (tLength t))) t a)"
and trans: "envTrans eact aact (tLast t) = s"
apply (auto iff: Let_def)
done
from t's' obtain eact' aact'
where eact': "eact' \<in> set (envAction (tLast t'))"
and aact': "\<forall>a. aact' a \<in> set (jAction (SPR.mkM (SPR.jkbpCn (tLength t'))) t' a)"
and trans': "envTrans eact' aact' (tLast t') = s'"
apply (auto iff: Let_def)
done
def aact'' \<equiv> "aact (a := aact' a)"
from tObsC trans trans'
have aact''_fst: "fst \<circ> aact'' = fst \<circ> aact"
unfolding envTrans_def aact''_def
apply -
apply (rule ext)
apply (auto iff: tObsC_tStep)
apply (erule o_eq_elim)
apply simp
done
from tObsC trans trans'
have aact''_snd: "snd \<circ> aact'' = (snd \<circ> aact)(a := ps s' a)"
unfolding envTrans_def aact''_def
apply -
apply (rule ext)
apply auto
done
have "envTrans eact aact'' (tLast (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t'))
= sSplice a (envTrans eact aact (tLast t)) s'"
unfolding envTrans_def sSplice_def
using tSplice_es[OF tLen[symmetric]] aact''_fst aact''_snd
apply clarsimp
done
moreover
{ fix a'
have "aact'' a' \<in> set (jAction (SPR.mkM (SPR.jkbpCn (tLength t))) (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') a')"
proof(cases "a' = a")
case False
with tStep have "jAction (SPR.mkM (SPR.jkbpCn (tLength t))) (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') a'
= jAction (SPR.mkM (SPR.jkbpCn (tLength t))) t a'"
apply -
apply (rule S5n_jAction_eq)
apply simp
unfolding SPR.mkM_def
using tSplice_spr_jview_not_a tt'
apply auto
done
with False aact show ?thesis
unfolding aact''_def by simp
next
case True
with tStep have "jAction (SPR.mkM (SPR.jkbpCn (tLength t))) (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') a
= jAction (SPR.mkM (SPR.jkbpCn (tLength t))) t' a"
apply -
apply (rule S5n_jAction_eq)
apply simp
unfolding SPR.mkM_def
using tSplice_spr_jview_a tt'
apply auto
done
with True aact' tLen show ?thesis
unfolding aact''_def by simp
qed }
moreover
from tStep have "envAction (tLast (t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t')) = envAction (tLast t)"
using tSplice_envAction by blast
moreover note eact trans tt'n
ultimately have "(t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> t') \<leadsto> sSplice a s s' \<in> SPR.jkbpCn (Suc (tLength t))"
apply (simp add: Let_def del: split_paired_Ex)
apply (rule exI[where x="eact"])
apply (rule exI[where x="aact''"])
apply simp
done
thus ?case
apply (simp only: tZip.simps)
apply blast
done
qed
lemma spr_sim_r:
"sim_r SPR.MC spr_simMC spr_sim"
proof(rule sim_rI)
fix a p q'
assume pT: "p \<in> worlds SPR.MC"
and fpq': "(spr_sim p, q') \<in> relations spr_simMC a"
from fpq' obtain uq fq vq
where q': "q' = \<lparr> sprFst = uq, sprLst = vq, sprCRel = tObsC_abs p \<rparr>"
and uq: "envObs a (tFirst p) = envObs a uq"
and vq: "envObs a (tLast p) = envObs a vq"
unfolding mkKripke_def spr_sim_def spr_simRels_def
by fastforce
from fpq' have "q' \<in> worlds spr_simMC" by simp
with q' have "(uq, vq) \<in> tObsC_abs p"
using spr_sim_tFirst_tLast[where s=q']
apply auto
done
then obtain t
where tT: "t \<in> SPR.jkbpC"
and tp: "tObsC t = tObsC p"
and tuq: "tFirst t = uq"
and tvq: "tLast t = vq"
by (auto iff: tObsC_abs_conv)
def q \<equiv> "t \<^bsub>\<^esub>\<bowtie>\<^bsub>a\<^esub> p"
from tp tuq uq
have "spr_jview a p = spr_jview a q"
unfolding q_def by (simp add: tSplice_spr_jview_a)
with pT tT tp tuq uq
have pt: "(p, q) \<in> relations SPR.MC a"
unfolding SPR.mkM_def q_def by (simp add: tSplice_jkbpC)
from q' uq vq tp tuq tvq
have ftq': "spr_sim q = q'"
unfolding spr_sim_def q_def
using tSplice_tObsC[where a=a and t=t and t'=p]
apply clarsimp
apply (intro conjI)
apply (auto dest: tObsC_tLength)[2]
unfolding tObsC_abs_def (* FIXME abstract *)
apply simp
done
from pt ftq'
show "\<exists>q. (p, q) \<in> relations SPR.MC a \<and> spr_sim q = q'"
by blast
qed
(*>*)
text{*
The proof is by induction over @{term "t"} and @{term "t'"}, and
depends crucially on the public actions being recorded in the state
and commonly observed. Showing the reverse simulation property is then
straightforward.
*}
lemma spr_sim: "sim SPR.MC spr_simMC spr_sim"
(*<*)
proof
show "sim_range SPR.MC spr_simMC spr_sim"
by (rule sim_rangeI) (simp_all add: spr_sim_def)
next
show "sim_val SPR.MC spr_simMC spr_sim"
by (rule sim_valI) simp
next
show "sim_f SPR.MC spr_simMC spr_sim"
unfolding spr_simRels_def spr_sim_def mkKripke_def SPR.mkM_def
by (rule sim_fI, auto simp del: split_paired_Ex)
next
show "sim_r SPR.MC spr_simMC spr_sim"
by (rule spr_sim_r)
qed
(*>*)
end (* context FiniteBroadcastEnvironment *)
sublocale FiniteBroadcastEnvironment
< SPR!: SimIncrEnvironment jkbp envInit envAction envTrans envVal
spr_jview envObs spr_jviewInit spr_jviewIncr
spr_sim spr_simRels spr_simVal
(*<*)
by default (simp add: spr_sim)
(*>*)
text{*
The algorithmic representations and machinery of the deterministic
JKBP case suffice for this one too, and so we omit the details.
\FloatBarrier
*}
(*<*)
end
(*>*)
|
lemma (in first_countable_topology) countable_basis_at_decseq: obtains A :: "nat \<Rightarrow> 'a set" where "\<And>i. open (A i)" "\<And>i. x \<in> (A i)" "\<And>S. open S \<Longrightarrow> x \<in> S \<Longrightarrow> eventually (\<lambda>i. A i \<subseteq> S) sequentially" |
using PyPlot
using JLD
function plot_lines()
X = load("../data/sens/solenoid/dJds_s3_K12.jld")
rho = X["s"]
dJds = X["dJds"]
X = load("../data/obj_erg_avg/solenoid/r2_s3.jld")
s3 = X["s3"]
J = X["J"]
fig, ax = subplots(1,1)
ax.plot(s3, J, ".", ms=10.0)
ax.xaxis.set_tick_params(labelsize=28)
ax.yaxis.set_tick_params(labelsize=28)
ax.set_xlabel(L"$s_2$",fontsize=28)
ax.set_ylabel(L"$\langle J\rangle$",fontsize=28)
ax.grid(true)
eps = 1.5e-2
X = load("../data/obj_erg_avg/solenoid/r2_s3_sens.jld")
J = X["J"]
s3 = X["s3"]
n = size(dJds)[1]
J_pts = reshape([J .- eps*dJds J .+ eps*dJds], n,
2)'
s_pts = reshape([s3 .- eps s3 .+ eps], n,
2)'
ax.plot(s_pts[:,1:n-1], J_pts[:,1:n-1], "k",lw=3.0)
ax.plot(s_pts[:,n], J_pts[:,n], "k",lw=4.0,label=L"$d_s\langle J\rangle$ from S3")
ax.legend(fontsize=28)
end
|
theory Pointer_Examples
imports VC_KAD_Examples "$ISABELLE_HOME/src/HOL/Hoare/Heap"
begin
type_synonym 'a state = "string \<Rightarrow> ('a ref + ('a \<Rightarrow> 'a ref))"
lemma list_reversal:
"PRE (\<lambda>s :: 'a state. List (projr (s ''h'')) (projl (s ''p'')) Ps
\<and> List (projr (s ''h'')) (projl (s ''q'')) Qs
\<and> set Ps \<inter> set Qs = {})
(WHILE (\<lambda>s. projl (s ''p'') \<noteq> Null)
INV (\<lambda>s. \<exists>ps qs. List (projr (s ''h'')) (projl (s ''p'')) ps
\<and> List (projr (s ''h'')) (projl (s ''q'')) qs
\<and> set ps \<inter> set qs = {} \<and> rev ps @ qs = rev Ps @ Qs)
DO
(''r'' ::= (\<lambda>s. s ''p''));
(''p'' ::= (\<lambda>s. Inl (projr (s ''h'') (addr (projl (s ''p''))))) );
(''h'' ::= (\<lambda>s. Inr ((projr (s ''h''))(addr (projl (s ''r'')) := projl (s ''q''))) ));
(''q'' ::= (\<lambda>s. s ''r''))
OD)
POST (\<lambda>s. List (projr (s ''h'')) (projl (s ''q'')) (rev Ps @ Qs))"
apply hoare
apply auto
apply(fastforce intro: notin_List_update[THEN iffD2])
done
end |
[GOAL]
C : Type u
instβ : Category.{v, u} C
F G : C β₯€ Discrete PUnit
X : C
β’ F.obj X = G.obj X
[PROOFSTEP]
simp only [eq_iff_true_of_subsingleton]
[GOAL]
C : Type u
instβ : Category.{v, u} C
F G : C β₯€ Discrete PUnit
X : C
β’ F.obj X = G.obj X
[PROOFSTEP]
simp only [eq_iff_true_of_subsingleton]
[GOAL]
C : Type u
instβ : Category.{v, u} C
β’ Nonempty (C β Discrete PUnit) β Nonempty C β§ β (x y : C), Nonempty (Unique (x βΆ y))
[PROOFSTEP]
constructor
[GOAL]
case mp
C : Type u
instβ : Category.{v, u} C
β’ Nonempty (C β Discrete PUnit) β Nonempty C β§ β (x y : C), Nonempty (Unique (x βΆ y))
[PROOFSTEP]
rintro β¨hβ©
[GOAL]
case mp.intro
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
β’ Nonempty C β§ β (x y : C), Nonempty (Unique (x βΆ y))
[PROOFSTEP]
refine' β¨β¨h.inverse.obj β¨β¨β©β©β©, fun x y => Nonempty.intro _β©
[GOAL]
case mp.intro
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
β’ Unique (x βΆ y)
[PROOFSTEP]
let f : x βΆ y := by
have hx : x βΆ h.inverse.obj β¨β¨β©β© := by convert h.unit.app x
have hy : h.inverse.obj β¨β¨β©β© βΆ y := by convert h.unitInv.app y
exact hx β« hy
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
β’ x βΆ y
[PROOFSTEP]
have hx : x βΆ h.inverse.obj β¨β¨β©β© := by convert h.unit.app x
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
β’ x βΆ h.inverse.obj { as := PUnit.unit }
[PROOFSTEP]
convert h.unit.app x
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
hx : x βΆ h.inverse.obj { as := PUnit.unit }
β’ x βΆ y
[PROOFSTEP]
have hy : h.inverse.obj β¨β¨β©β© βΆ y := by convert h.unitInv.app y
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
hx : x βΆ h.inverse.obj { as := PUnit.unit }
β’ h.inverse.obj { as := PUnit.unit } βΆ y
[PROOFSTEP]
convert h.unitInv.app y
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
hx : x βΆ h.inverse.obj { as := PUnit.unit }
hy : h.inverse.obj { as := PUnit.unit } βΆ y
β’ x βΆ y
[PROOFSTEP]
exact hx β« hy
[GOAL]
case mp.intro
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
β’ Unique (x βΆ y)
[PROOFSTEP]
suffices sub : Subsingleton (x βΆ y) from uniqueOfSubsingleton f
[GOAL]
case mp.intro
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
β’ Subsingleton (x βΆ y)
[PROOFSTEP]
have : β z, z = h.unit.app x β« (h.functor β h.inverse).map z β« h.unitInv.app y :=
by
intro z
simp [congrArg (Β· β« h.unitInv.app y) (h.unit.naturality z)]
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
β’ β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
[PROOFSTEP]
intro z
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
z : x βΆ y
β’ z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
[PROOFSTEP]
simp [congrArg (Β· β« h.unitInv.app y) (h.unit.naturality z)]
[GOAL]
case mp.intro
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
β’ Subsingleton (x βΆ y)
[PROOFSTEP]
apply Subsingleton.intro
[GOAL]
case mp.intro.allEq
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
β’ β (a b : x βΆ y), a = b
[PROOFSTEP]
intro a b
[GOAL]
case mp.intro.allEq
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
a b : x βΆ y
β’ a = b
[PROOFSTEP]
rw [this a, this b]
[GOAL]
case mp.intro.allEq
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
a b : x βΆ y
β’ NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map a β« NatTrans.app (Equivalence.unitInv h) y =
NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map b β« NatTrans.app (Equivalence.unitInv h) y
[PROOFSTEP]
simp only [Functor.comp_map]
[GOAL]
case mp.intro.allEq
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
a b : x βΆ y
β’ NatTrans.app (Equivalence.unit h) x β« h.inverse.map (h.functor.map a) β« NatTrans.app (Equivalence.unitInv h) y =
NatTrans.app (Equivalence.unit h) x β« h.inverse.map (h.functor.map b) β« NatTrans.app (Equivalence.unitInv h) y
[PROOFSTEP]
congr 3
[GOAL]
case mp.intro.allEq.e_a.e_a.e_a
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
a b : x βΆ y
β’ h.functor.map a = h.functor.map b
[PROOFSTEP]
apply ULift.ext
[GOAL]
case mp.intro.allEq.e_a.e_a.e_a.h
C : Type u
instβ : Category.{v, u} C
h : C β Discrete PUnit
x y : C
f : x βΆ y :=
let_fun hx :=
Eq.mpr (_ : (x βΆ h.inverse.obj { as := PUnit.unit }) = ((π C).obj x βΆ (h.functor β h.inverse).obj x))
(id (NatTrans.app (Equivalence.unit h) x));
let_fun hy :=
Eq.mpr (_ : (h.inverse.obj { as := PUnit.unit } βΆ y) = ((h.functor β h.inverse).obj y βΆ (π C).obj y))
(id (NatTrans.app (Equivalence.unitInv h) y));
hx β« hy
this :
β (z : x βΆ y),
z = NatTrans.app (Equivalence.unit h) x β« (h.functor β h.inverse).map z β« NatTrans.app (Equivalence.unitInv h) y
a b : x βΆ y
β’ (h.functor.map a).down = (h.functor.map b).down
[PROOFSTEP]
simp
[GOAL]
case mpr
C : Type u
instβ : Category.{v, u} C
β’ (Nonempty C β§ β (x y : C), Nonempty (Unique (x βΆ y))) β Nonempty (C β Discrete PUnit)
[PROOFSTEP]
rintro β¨β¨pβ©, hβ©
[GOAL]
case mpr.intro.intro
C : Type u
instβ : Category.{v, u} C
h : β (x y : C), Nonempty (Unique (x βΆ y))
p : C
β’ Nonempty (C β Discrete PUnit)
[PROOFSTEP]
haveI := fun x y => (h x y).some
[GOAL]
case mpr.intro.intro
C : Type u
instβ : Category.{v, u} C
h : β (x y : C), Nonempty (Unique (x βΆ y))
p : C
this : (x y : C) β Unique (x βΆ y)
β’ Nonempty (C β Discrete PUnit)
[PROOFSTEP]
refine'
Nonempty.intro
(CategoryTheory.Equivalence.mk ((Functor.const _).obj β¨β¨β©β©) ((@Functor.const <| Discrete PUnit).obj p) ?_
(by apply Functor.punitExt))
[GOAL]
C : Type u
instβ : Category.{v, u} C
h : β (x y : C), Nonempty (Unique (x βΆ y))
p : C
this : (x y : C) β Unique (x βΆ y)
β’ (Functor.const (Discrete PUnit)).obj p β (Functor.const C).obj { as := PUnit.unit } β
π (Discrete PUnit)
[PROOFSTEP]
apply Functor.punitExt
[GOAL]
case mpr.intro.intro
C : Type u
instβ : Category.{v, u} C
h : β (x y : C), Nonempty (Unique (x βΆ y))
p : C
this : (x y : C) β Unique (x βΆ y)
β’ π C β
(Functor.const C).obj { as := PUnit.unit } β (Functor.const (Discrete PUnit)).obj p
[PROOFSTEP]
exact
NatIso.ofComponents fun _ =>
{ hom := default
inv := default }
|
lemma degree_eq_length_coeffs [code]: "degree p = length (coeffs p) - 1" |
[STATEMENT]
lemma length_transfer [transfer_rule]:
"(list_all2 A ===> (=)) length length"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (list_all2 A ===> (=)) length length
[PROOF STEP]
unfolding size_list_overloaded_def size_list_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (list_all2 A ===> (=)) (rec_list 0 (\<lambda>x xa xb. 0 + xb + Suc 0)) (rec_list 0 (\<lambda>x xa xb. 0 + xb + Suc 0))
[PROOF STEP]
by transfer_prover |
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.constructions
import Mathlib.topology.algebra.group
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Topology on lists and vectors
-/
protected instance list.topological_space {Ξ± : Type u_1} [topological_space Ξ±] : topological_space (List Ξ±) :=
topological_space.mk_of_nhds (traverse nhds)
theorem nhds_list {Ξ± : Type u_1} [topological_space Ξ±] (as : List Ξ±) : nhds as = traverse nhds as := sorry
@[simp] theorem nhds_nil {Ξ± : Type u_1} [topological_space Ξ±] : nhds [] = pure [] :=
eq.mpr (id (Eq._oldrec (Eq.refl (nhds [] = pure [])) (nhds_list [])))
(eq.mpr (id (Eq._oldrec (Eq.refl (traverse nhds [] = pure [])) (list.traverse_nil nhds))) (Eq.refl (pure [])))
theorem nhds_cons {Ξ± : Type u_1} [topological_space Ξ±] (a : Ξ±) (l : List Ξ±) : nhds (a :: l) = List.cons <$> nhds a <*> nhds l := sorry
theorem list.tendsto_cons {Ξ± : Type u_1} [topological_space Ξ±] {a : Ξ±} {l : List Ξ±} : filter.tendsto (fun (p : Ξ± Γ List Ξ±) => prod.fst p :: prod.snd p) (filter.prod (nhds a) (nhds l)) (nhds (a :: l)) := sorry
theorem filter.tendsto.cons {Ξ² : Type u_2} [topological_space Ξ²] {Ξ± : Type u_1} {f : Ξ± β Ξ²} {g : Ξ± β List Ξ²} {a : filter Ξ±} {b : Ξ²} {l : List Ξ²} (hf : filter.tendsto f a (nhds b)) (hg : filter.tendsto g a (nhds l)) : filter.tendsto (fun (a : Ξ±) => f a :: g a) a (nhds (b :: l)) :=
filter.tendsto.comp list.tendsto_cons (filter.tendsto.prod_mk hf hg)
namespace list
theorem tendsto_cons_iff {Ξ± : Type u_1} [topological_space Ξ±] {Ξ² : Type u_2} {f : List Ξ± β Ξ²} {b : filter Ξ²} {a : Ξ±} {l : List Ξ±} : filter.tendsto f (nhds (a :: l)) b β
filter.tendsto (fun (p : Ξ± Γ List Ξ±) => f (prod.fst p :: prod.snd p)) (filter.prod (nhds a) (nhds l)) b := sorry
theorem continuous_cons {Ξ± : Type u_1} [topological_space Ξ±] : continuous fun (x : Ξ± Γ List Ξ±) => prod.fst x :: prod.snd x := sorry
theorem tendsto_nhds {Ξ± : Type u_1} [topological_space Ξ±] {Ξ² : Type u_2} {f : List Ξ± β Ξ²} {r : List Ξ± β filter Ξ²} (h_nil : filter.tendsto f (pure []) (r [])) (h_cons : β (l : List Ξ±) (a : Ξ±),
filter.tendsto f (nhds l) (r l) β
filter.tendsto (fun (p : Ξ± Γ List Ξ±) => f (prod.fst p :: prod.snd p)) (filter.prod (nhds a) (nhds l)) (r (a :: l))) (l : List Ξ±) : filter.tendsto f (nhds l) (r l) := sorry
theorem continuous_at_length {Ξ± : Type u_1} [topological_space Ξ±] (l : List Ξ±) : continuous_at length l := sorry
theorem tendsto_insert_nth' {Ξ± : Type u_1} [topological_space Ξ±] {a : Ξ±} {n : β} {l : List Ξ±} : filter.tendsto (fun (p : Ξ± Γ List Ξ±) => insert_nth n (prod.fst p) (prod.snd p)) (filter.prod (nhds a) (nhds l))
(nhds (insert_nth n a l)) := sorry
theorem tendsto_insert_nth {Ξ± : Type u_1} [topological_space Ξ±] {Ξ² : Type u_2} {n : β} {a : Ξ±} {l : List Ξ±} {f : Ξ² β Ξ±} {g : Ξ² β List Ξ±} {b : filter Ξ²} (hf : filter.tendsto f b (nhds a)) (hg : filter.tendsto g b (nhds l)) : filter.tendsto (fun (b : Ξ²) => insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) :=
filter.tendsto.comp tendsto_insert_nth' (filter.tendsto.prod_mk hf hg)
theorem continuous_insert_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} : continuous fun (p : Ξ± Γ List Ξ±) => insert_nth n (prod.fst p) (prod.snd p) := sorry
theorem tendsto_remove_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {l : List Ξ±} : filter.tendsto (fun (l : List Ξ±) => remove_nth l n) (nhds l) (nhds (remove_nth l n)) := sorry
theorem continuous_remove_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} : continuous fun (l : List Ξ±) => remove_nth l n :=
iff.mpr continuous_iff_continuous_at fun (a : List Ξ±) => tendsto_remove_nth
theorem tendsto_sum {Ξ± : Type u_1} [topological_space Ξ±] [add_monoid Ξ±] [has_continuous_add Ξ±] {l : List Ξ±} : filter.tendsto sum (nhds l) (nhds (sum l)) := sorry
theorem continuous_sum {Ξ± : Type u_1} [topological_space Ξ±] [add_monoid Ξ±] [has_continuous_add Ξ±] : continuous sum :=
iff.mpr continuous_iff_continuous_at fun (l : List Ξ±) => tendsto_sum
end list
namespace vector
protected instance topological_space {Ξ± : Type u_1} [topological_space Ξ±] (n : β) : topological_space (vector Ξ± n) :=
eq.mpr sorry subtype.topological_space
theorem tendsto_cons {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {a : Ξ±} {l : vector Ξ± n} : filter.tendsto (fun (p : Ξ± Γ vector Ξ± n) => prod.fst p::α΅₯prod.snd p) (filter.prod (nhds a) (nhds l)) (nhds (a::α΅₯l)) := sorry
theorem tendsto_insert_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {i : fin (n + 1)} {a : Ξ±} {l : vector Ξ± n} : filter.tendsto (fun (p : Ξ± Γ vector Ξ± n) => insert_nth (prod.fst p) i (prod.snd p)) (filter.prod (nhds a) (nhds l))
(nhds (insert_nth a i l)) := sorry
theorem continuous_insert_nth' {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {i : fin (n + 1)} : continuous fun (p : Ξ± Γ vector Ξ± n) => insert_nth (prod.fst p) i (prod.snd p) := sorry
theorem continuous_insert_nth {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {n : β} {i : fin (n + 1)} {f : Ξ² β Ξ±} {g : Ξ² β vector Ξ± n} (hf : continuous f) (hg : continuous g) : continuous fun (b : Ξ²) => insert_nth (f b) i (g b) :=
continuous.comp continuous_insert_nth' (continuous.prod_mk hf hg)
theorem continuous_at_remove_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {i : fin (n + 1)} {l : vector Ξ± (n + 1)} : continuous_at (remove_nth i) l := sorry
-- β{l:vector Ξ± (n+1)}, tendsto (remove_nth i) (π l) (π (remove_nth i l))
--| β¨l, hlβ© :=
theorem continuous_remove_nth {Ξ± : Type u_1} [topological_space Ξ±] {n : β} {i : fin (n + 1)} : continuous (remove_nth i) := sorry
|
**==brems.spg processed by SPAG 4.50J at 14:49 on 30 Jun 1995
SUBROUTINE BREMS(T,N)
IMPLICIT NONE
C*** Start of declarations inserted by SPAG
REAL ABUnd , ABUnj , BINmin , BINsyz , BRMev , chrgsm , CONce ,
& DNE , ebk , en1 , en2 , exprod , FBG , GNDrec , hc , HENeut ,
& HEPlus , PCOol , PM , POT
REAL POU , POWer , q , RE , RECev , RHY , T , t6 , TU , TUF , x ,
& y , z
INTEGER i , i2 , j , j1 , j2 , N , NBIn , NJ
C*** End of declarations inserted by SPAG
REAL kt
INCLUDE 'rayspec.inc'
COMMON /RESULT/ CONce(30) , GNDrec(30) , POWer(220) , RHY ,
& HENeut , HEPlus , DNE , PCOol , POU , POT , RE ,
& TU , PM(4)
COMMON /PARAMS/ NJ(12) , ABUnj(12) , ABUnd , BINmin , BINsyz ,
& NBIn
COMMON /CONTIN/ BRMev(MXBINS) , RECev(MXBINS) , TUF(MXBINS)
DIMENSION x(30)
hc = 12399.
j2 = N + 1
j1 = 2
t6 = T/1.E6
kt = 86.17*t6
ebk = EXP(BINsyz/kt)
q = 10.**(ABUnd-12.)*86.17*SQRT(t6)*20.4*(ebk-1.)*EXP(-BINmin/kt)
& /hc
ebk = 1./ebk
DO 100 j = j1 , j2
x(j) = 0.
IF ( CONce(j).GT.1.E-5 ) x(j) = CONce(j)*q*(j-1)**2
100 CONTINUE
i2 = MIN0(NBIn,INT(46.*kt/BINsyz)+1)
exprod = 1.
DO 200 i = 1 , i2
en2 = BINsyz*i + BINmin
en1 = en2 - BINsyz
y = (en2+en1)*.5/kt
chrgsm = 0.
DO 150 j = j1 , j2
IF ( x(j).NE.0. ) THEN
z = (j-1)**2*.158/t6
chrgsm = chrgsm + x(j)*FBG(y,z)
ENDIF
150 CONTINUE
exprod = exprod*ebk
BRMev(i) = BRMev(i) + chrgsm*exprod
200 CONTINUE
RETURN
END
|
(* Exercise 3: DefiniΘi o funcΘie care returneazΔ ziua urmΔtoare. (0.25 puncte) *)
(* Define the 'Day' data type. *)
Inductive Day :=
| Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday.
(* Define the 'nextDay' function. *)
Definition nextDay (currentDay : Day) : Day :=
match currentDay with
| Monday => Tuesday
| Tuesday => Wednesday
| Wednesday => Thursday
| Thursday => Friday
| Friday => Saturday
| Saturday => Sunday
| Sunday => Monday
end.
(* Test the 'nextDay' function. *)
Compute nextDay Monday.
Compute nextDay Tuesday.
Compute nextDay Wednesday.
Compute nextDay Thursday.
Compute nextDay Friday.
Compute nextDay Saturday.
Compute nextDay Sunday. |
theory ExF015
imports Main
begin
lemma "\<not>(\<forall>x. P x) \<longleftrightarrow> (\<exists>x. \<not>P x)"
proof -
{
assume a:"\<not>(\<forall>x. P x)"
{
assume b:"\<not>(\<exists>x. \<not>P x)"
{
fix aa
{
assume "\<not>P aa"
hence "\<exists>x. \<not>P x" by (rule exI)
with b have False by contradiction
}
hence "\<not>\<not>P aa" by (rule notI)
hence "P aa" by (rule notnotD)
}
hence "\<forall>x. P x" by (rule allI)
with a have False by contradiction
}
hence "\<not>\<not>(\<exists>x. \<not>P x)" by (rule notI)
hence "\<exists>x. \<not>P x" by (rule notnotD)
}
moreover
{
assume a:"\<exists>x. \<not>P x"
{
assume b:"\<forall>x. P x"
{
fix aa
assume c:"\<not>P aa"
from b have "P aa" by (rule allE)
with c have False by contradiction
}
with a have False by (rule exE)
}
hence "\<not>(\<forall>x. P x)" by (rule notI)
}
ultimately show ?thesis by (rule iffI)
qed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.