text
stringlengths 0
3.34M
|
---|
(* Title: HOL/Library/Stirling.thy
Author: Amine Chaieb
Author: Florian Haftmann
Author: Lukas Bulwahn
Author: Manuel Eberl
*)
section \<open>Stirling numbers of first and second kind\<close>
theory Stirling
imports Main
begin
subsection \<open>Stirling numbers of the second kind\<close>
fun Stirling :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
"Stirling 0 0 = 1"
| "Stirling 0 (Suc k) = 0"
| "Stirling (Suc n) 0 = 0"
| "Stirling (Suc n) (Suc k) = Suc k * Stirling n (Suc k) + Stirling n k"
lemma Stirling_1 [simp]: "Stirling (Suc n) (Suc 0) = 1"
by (induct n) simp_all
lemma Stirling_less [simp]: "n < k \<Longrightarrow> Stirling n k = 0"
by (induct n k rule: Stirling.induct) simp_all
lemma Stirling_same [simp]: "Stirling n n = 1"
by (induct n) simp_all
lemma Stirling_2_2: "Stirling (Suc (Suc n)) (Suc (Suc 0)) = 2 ^ Suc n - 1"
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
have "Stirling (Suc (Suc (Suc n))) (Suc (Suc 0)) =
2 * Stirling (Suc (Suc n)) (Suc (Suc 0)) + Stirling (Suc (Suc n)) (Suc 0)"
by simp
also have "\<dots> = 2 * (2 ^ Suc n - 1) + 1"
by (simp only: Suc Stirling_1)
also have "\<dots> = 2 ^ Suc (Suc n) - 1"
proof -
have "(2::nat) ^ Suc n - 1 > 0"
by (induct n) simp_all
then have "2 * ((2::nat) ^ Suc n - 1) > 0"
by simp
then have "2 \<le> 2 * ((2::nat) ^ Suc n)"
by simp
with add_diff_assoc2 [of 2 "2 * 2 ^ Suc n" 1]
have "2 * 2 ^ Suc n - 2 + (1::nat) = 2 * 2 ^ Suc n + 1 - 2" .
then show ?thesis
by (simp add: nat_distrib)
qed
finally show ?case by simp
qed
lemma Stirling_2: "Stirling (Suc n) (Suc (Suc 0)) = 2 ^ n - 1"
using Stirling_2_2 by (cases n) simp_all
subsection \<open>Stirling numbers of the first kind\<close>
fun stirling :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
"stirling 0 0 = 1"
| "stirling 0 (Suc k) = 0"
| "stirling (Suc n) 0 = 0"
| "stirling (Suc n) (Suc k) = n * stirling n (Suc k) + stirling n k"
lemma stirling_0 [simp]: "n > 0 \<Longrightarrow> stirling n 0 = 0"
by (cases n) simp_all
lemma stirling_less [simp]: "n < k \<Longrightarrow> stirling n k = 0"
by (induct n k rule: stirling.induct) simp_all
lemma stirling_same [simp]: "stirling n n = 1"
by (induct n) simp_all
lemma stirling_Suc_n_1: "stirling (Suc n) (Suc 0) = fact n"
by (induct n) auto
lemma stirling_Suc_n_n: "stirling (Suc n) n = Suc n choose 2"
by (induct n) (auto simp add: numerals(2))
lemma stirling_Suc_n_2:
assumes "n \<ge> Suc 0"
shows "stirling (Suc n) 2 = (\<Sum>k=1..n. fact n div k)"
using assms
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
show ?case
proof (cases n)
case 0
then show ?thesis
by (simp add: numerals(2))
next
case Suc
then have geq1: "Suc 0 \<le> n"
by simp
have "stirling (Suc (Suc n)) 2 = Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0)"
by (simp only: stirling.simps(4)[of "Suc n"] numerals(2))
also have "\<dots> = Suc n * (\<Sum>k=1..n. fact n div k) + fact n"
using Suc.hyps[OF geq1]
by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)
also have "\<dots> = Suc n * (\<Sum>k=1..n. fact n div k) + Suc n * fact n div Suc n"
by (metis nat.distinct(1) nonzero_mult_div_cancel_left)
also have "\<dots> = (\<Sum>k=1..n. fact (Suc n) div k) + fact (Suc n) div Suc n"
by (simp add: sum_distrib_left div_mult_swap dvd_fact)
also have "\<dots> = (\<Sum>k=1..Suc n. fact (Suc n) div k)"
by simp
finally show ?thesis .
qed
qed
lemma of_nat_stirling_Suc_n_2:
assumes "n \<ge> Suc 0"
shows "(of_nat (stirling (Suc n) 2)::'a::field_char_0) = fact n * (\<Sum>k=1..n. (1 / of_nat k))"
using assms
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
show ?case
proof (cases n)
case 0
then show ?thesis
by (auto simp add: numerals(2))
next
case Suc
then have geq1: "Suc 0 \<le> n"
by simp
have "(of_nat (stirling (Suc (Suc n)) 2)::'a) =
of_nat (Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0))"
by (simp only: stirling.simps(4)[of "Suc n"] numerals(2))
also have "\<dots> = of_nat (Suc n) * (fact n * (\<Sum>k = 1..n. 1 / of_nat k)) + fact n"
using Suc.hyps[OF geq1]
by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)
also have "\<dots> = fact (Suc n) * (\<Sum>k = 1..n. 1 / of_nat k) + fact (Suc n) * (1 / of_nat (Suc n))"
using of_nat_neq_0 by auto
also have "\<dots> = fact (Suc n) * (\<Sum>k = 1..Suc n. 1 / of_nat k)"
by (simp add: distrib_left)
finally show ?thesis .
qed
qed
lemma sum_stirling: "(\<Sum>k\<le>n. stirling n k) = fact n"
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
have "(\<Sum>k\<le>Suc n. stirling (Suc n) k) = stirling (Suc n) 0 + (\<Sum>k\<le>n. stirling (Suc n) (Suc k))"
by (simp only: sum.atMost_Suc_shift)
also have "\<dots> = (\<Sum>k\<le>n. stirling (Suc n) (Suc k))"
by simp
also have "\<dots> = (\<Sum>k\<le>n. n * stirling n (Suc k) + stirling n k)"
by simp
also have "\<dots> = n * (\<Sum>k\<le>n. stirling n (Suc k)) + (\<Sum>k\<le>n. stirling n k)"
by (simp add: sum.distrib sum_distrib_left)
also have "\<dots> = n * fact n + fact n"
proof -
have "n * (\<Sum>k\<le>n. stirling n (Suc k)) = n * ((\<Sum>k\<le>Suc n. stirling n k) - stirling n 0)"
by (metis add_diff_cancel_left' sum.atMost_Suc_shift)
also have "\<dots> = n * (\<Sum>k\<le>n. stirling n k)"
by (cases n) simp_all
also have "\<dots> = n * fact n"
using Suc.hyps by simp
finally have "n * (\<Sum>k\<le>n. stirling n (Suc k)) = n * fact n" .
moreover have "(\<Sum>k\<le>n. stirling n k) = fact n"
using Suc.hyps .
ultimately show ?thesis by simp
qed
also have "\<dots> = fact (Suc n)" by simp
finally show ?case .
qed
lemma stirling_pochhammer:
"(\<Sum>k\<le>n. of_nat (stirling n k) * x ^ k) = (pochhammer x n :: 'a::comm_semiring_1)"
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
have "of_nat (n * stirling n 0) = (0 :: 'a)" by (cases n) simp_all
then have "(\<Sum>k\<le>Suc n. of_nat (stirling (Suc n) k) * x ^ k) =
(of_nat (n * stirling n 0) * x ^ 0 +
(\<Sum>i\<le>n. of_nat (n * stirling n (Suc i)) * (x ^ Suc i))) +
(\<Sum>i\<le>n. of_nat (stirling n i) * (x ^ Suc i))"
by (subst sum.atMost_Suc_shift) (simp add: sum.distrib ring_distribs)
also have "\<dots> = pochhammer x (Suc n)"
by (subst sum.atMost_Suc_shift [symmetric])
(simp add: algebra_simps sum.distrib sum_distrib_left pochhammer_Suc flip: Suc)
finally show ?case .
qed
text \<open>A row of the Stirling number triangle\<close>
definition stirling_row :: "nat \<Rightarrow> nat list"
where "stirling_row n = [stirling n k. k \<leftarrow> [0..<Suc n]]"
lemma nth_stirling_row: "k \<le> n \<Longrightarrow> stirling_row n ! k = stirling n k"
by (simp add: stirling_row_def del: upt_Suc)
lemma length_stirling_row [simp]: "length (stirling_row n) = Suc n"
by (simp add: stirling_row_def)
lemma stirling_row_nonempty [simp]: "stirling_row n \<noteq> []"
using length_stirling_row[of n] by (auto simp del: length_stirling_row)
subsubsection \<open>Efficient code\<close>
text \<open>
Naively using the defining equations of the Stirling numbers of the first
kind to compute them leads to exponential run time due to repeated
computations. We can use memoisation to compute them row by row without
repeating computations, at the cost of computing a few unneeded values.
As a bonus, this is very efficient for applications where an entire row of
Stirling numbers is needed.
\<close>
definition zip_with_prev :: "('a \<Rightarrow> 'a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'b list"
where "zip_with_prev f x xs = map2 f (x # xs) xs"
lemma zip_with_prev_altdef:
"zip_with_prev f x xs =
(if xs = [] then [] else f x (hd xs) # [f (xs!i) (xs!(i+1)). i \<leftarrow> [0..<length xs - 1]])"
proof (cases xs)
case Nil
then show ?thesis
by (simp add: zip_with_prev_def)
next
case (Cons y ys)
then have "zip_with_prev f x xs = f x (hd xs) # zip_with_prev f y ys"
by (simp add: zip_with_prev_def)
also have "zip_with_prev f y ys = map (\<lambda>i. f (xs ! i) (xs ! (i + 1))) [0..<length xs - 1]"
unfolding Cons
by (induct ys arbitrary: y)
(simp_all add: zip_with_prev_def upt_conv_Cons flip: map_Suc_upt del: upt_Suc)
finally show ?thesis
using Cons by simp
qed
primrec stirling_row_aux
where
"stirling_row_aux n y [] = [1]"
| "stirling_row_aux n y (x#xs) = (y + n * x) # stirling_row_aux n x xs"
lemma stirling_row_aux_correct:
"stirling_row_aux n y xs = zip_with_prev (\<lambda>a b. a + n * b) y xs @ [1]"
by (induct xs arbitrary: y) (simp_all add: zip_with_prev_def)
lemma stirling_row_code [code]:
"stirling_row 0 = [1]"
"stirling_row (Suc n) = stirling_row_aux n 0 (stirling_row n)"
proof goal_cases
case 1
show ?case by (simp add: stirling_row_def)
next
case 2
have "stirling_row (Suc n) =
0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \<leftarrow> [0..<n]] @ [1]"
proof (rule nth_equalityI, goal_cases length nth)
case (nth i)
from nth have "i \<le> Suc n"
by simp
then consider "i = 0 \<or> i = Suc n" | "i > 0" "i \<le> n"
by linarith
then show ?case
proof cases
case 1
then show ?thesis
by (auto simp: nth_stirling_row nth_append)
next
case 2
then show ?thesis
by (cases i) (simp_all add: nth_append nth_stirling_row)
qed
next
case length
then show ?case by simp
qed
also have "0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \<leftarrow> [0..<n]] @ [1] =
zip_with_prev (\<lambda>a b. a + n * b) 0 (stirling_row n) @ [1]"
by (cases n) (auto simp add: zip_with_prev_altdef stirling_row_def hd_map simp del: upt_Suc)
also have "\<dots> = stirling_row_aux n 0 (stirling_row n)"
by (simp add: stirling_row_aux_correct)
finally show ?case .
qed
lemma stirling_code [code]:
"stirling n k =
(if k = 0 then (if n = 0 then 1 else 0)
else if k > n then 0
else if k = n then 1
else stirling_row n ! k)"
by (simp add: nth_stirling_row)
end
|
open import Coinduction using ( ∞ ; ♯_ ; ♭ )
open import Data.Bool using ( Bool ; true ; false ; if_then_else_ )
open import Data.Empty using ( ⊥ )
open import Data.Maybe using ( Maybe ; just ; nothing )
open import Data.Sum using ( _⊎_ ; inj₁ ; inj₂ )
open import Data.Unit using ( ⊤ ; tt )
open import Data.Natural using ( Natural ; # )
open import Data.String using ( String )
open import Data.ByteString using ( ByteString ; strict ; length )
open import Relation.Binary.PropositionalEquality using ( _≡_ ; refl )
module System.IO.Transducers.Session where
-- Unidirectional sessions. These can be viewed as trees,
-- where each node is labelled by a set A, and has a child
-- for each element of A.
-- These are a lot like session types, but are unidirectional,
-- not bidirectional, and are not designed to support session
-- mobility.
-- They are also a lot like arenas in game semantics, but again
-- are unidirectional.
-- They're a lot like the container types from Ghani, Hancock
-- and Pattison's "Continuous functions on final coalgebras".
-- Note that we are supporting weighted sets, similar to theirs,
-- in order to support induction over weights of input,
-- e.g. on bytestring input we can do induction over the length
-- of the bytestring.
-- Finally, they are a lot like automata: states are sessions,
-- acceptors are leaves, transitions correspond to children.
infixr 4 _∼_
infixr 6 _⊕_
infixr 7 _&_ _&*_
-- Weighting for a set
Weighted : Set → Set
Weighted A = A → Natural
-- Discrete weighting function
δ : ∀ {A} → (Weighted A)
δ a = # 1
-- Sessions are trees of weighted sets
data Session : Set₁ where
I : Session
Σ : {A : Set} → (W : Weighted A) → (F : ∞ (A → Session)) → Session
-- Equivalence of sessions
data _∼_ : Session → Session → Set₁ where
I : I ∼ I
Σ : {A : Set} → (W : Weighted A) → {F₁ F₂ : ∞ (A → Session)} →
∞ (∀ a → ♭ F₁ a ∼ ♭ F₂ a) → (Σ W F₁ ∼ Σ W F₂)
∼-refl : ∀ {S} → (S ∼ S)
∼-refl {I} = I
∼-refl {Σ V F} = Σ V (♯ λ a → ∼-refl {♭ F a})
∼-sym : ∀ {S T} → (S ∼ T) → (T ∼ S)
∼-sym I = I
∼-sym (Σ V F) = Σ V (♯ λ a → ∼-sym (♭ F a))
∼-trans : ∀ {S T U} → (S ∼ T) → (T ∼ U) → (S ∼ U)
∼-trans I I = I
∼-trans (Σ V F) (Σ .V G) = Σ V (♯ λ a → ∼-trans (♭ F a) (♭ G a))
-- Inital alphabet
Γ : Session → Set
Γ I = ⊥
Γ (Σ {A} W F) = A
Δ : ∀ S → (Weighted (Γ S))
Δ I ()
Δ (Σ W F) a = W a
_/_ : ∀ S → (Γ S) → Session
I / ()
(Σ W F) / a = ♭ F a
-- IsI S is inhabited whenever S ≡ I
IsI : Session → Set
IsI I = ⊤
IsI (Σ V F) = ⊥
-- IsΣ S is inhabited whenever S is of the form Σ V F
IsΣ : Session → Set
IsΣ I = ⊥
IsΣ (Σ V F) = ⊤
-- IsΣ respects ≡.
IsΣ-≡ : ∀ {S} {isΣ : IsΣ S} {T} → (S ≡ T) → (IsΣ T)
IsΣ-≡ {Σ V F} refl = tt
IsΣ-≡ {I} {} refl
-- Singletons
⟨_w/_⟩ : (A : Set) → (Weighted A) → Session
⟨ A w/ W ⟩ = Σ W (♯ λ a → I)
⟨_⟩ : Set → Session
⟨ A ⟩ = ⟨ A w/ δ ⟩
-- Sequencing
_&_ : Session → Session → Session
I & T = T
(Σ V F) & T = Σ V (♯ λ a → ♭ F a & T)
-- Units and associativity
unit₁ : ∀ {S} → (I & S ∼ S)
unit₁ = ∼-refl
unit₂ : ∀ {S} → (S & I ∼ S)
unit₂ {I} = I
unit₂ {Σ V F} = Σ V (♯ λ a → unit₂ {♭ F a})
assoc : ∀ {S T U} → (S & (T & U) ∼ (S & T) & U)
assoc {I} = ∼-refl
assoc {Σ V F} = Σ V (♯ λ a → assoc {♭ F a})
-- Lazy choice
_+_ : Session → Session → Session
S + T = Σ δ (♯ λ b → if b then S else T)
-- Strict choice
_⊕_ : Session → Session → Session
I ⊕ T = I
S ⊕ I = I
S ⊕ T = S + T
-- Lazy option
¿ : Session → Session
¿ S = S + I
-- Lazy Kleene star
-- It would be nice if I could just define * S = ¿ (S & * S),
-- but that doesn't pass the termination checker, so I have
-- to expand out the definition.
hd : Session → Set
hd I = Bool
hd (Σ {A} W F) = A
wt : ∀ S → (Weighted (hd S))
wt I = δ
wt (Σ W F) = W
mutual
tl : ∀ S T → (hd S) → Session
tl I T true = T &* T
tl I T false = I
tl (Σ W F) T a = (♭ F a) &* T
_&*_ : Session → Session → Session
S &* T = Σ (wt S) (♯ tl S T)
* : Session → Session
* S = I &* S
+ : Session → Session
+ S = S &* S
-- Bytes
Bytes' : Session
Bytes' = + ⟨ ByteString strict w/ length ⟩
Bytes : Session
Bytes = * ⟨ ByteString strict w/ length ⟩
-- TODO: weight strings by their length?
Strings' : Session
Strings' = + ⟨ String ⟩
Strings : Session
Strings = * ⟨ String ⟩
|
[STATEMENT]
lemma differentiable_inner [simp]:
"f differentiable (at x within s) \<Longrightarrow> g differentiable at x within s \<Longrightarrow> (\<lambda>x. inner (f x) (g x)) differentiable at x within s"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>f differentiable at x within s; g differentiable at x within s\<rbrakk> \<Longrightarrow> (\<lambda>x. inner (f x) (g x)) differentiable at x within s
[PROOF STEP]
unfolding differentiable_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<exists>D. (f has_derivative D) (at x within s); \<exists>D. (g has_derivative D) (at x within s)\<rbrakk> \<Longrightarrow> \<exists>D. ((\<lambda>x. inner (f x) (g x)) has_derivative D) (at x within s)
[PROOF STEP]
by (blast intro: has_derivative_inner) |
% SIGNAL SYNTHESIS
%
% Estimates the time-domain signal from a given time-frequency distribution.
%
%
% The signal synthesis routine is limited to the following
% time-frequency distributions:
%
% (i) Short-Time Fourier Transform (STFT)
% (ii) Spectrogram
% (iii) Wigner-Ville Distribution
%
% PARAMETERS:
%
% TIME-FREQUENCY MATRIX
%
% Input matrix containing the time-frequency distribution.
%
% SIGNAL
%
% Output synthesised (complex) signal from given time-frequency distribution.
%
% WINDOW LENGTH
%
% Length of the smoothing window used in the given distribution (or in the case of
% of the WVD the lag window length).
%
% ANALYSIS TYPE
%
% Specifies which type of signal synthesis will be applied to the given TFD
% matrix. The following analysis types are valid:
%
% (i) STFT:
%
% (a) Inverse Discrete Fourier Transform method.
% (b) Overlap-Add method.
% (c) Modified Short-Time Fourier Transform method.
%
% (ii) Spectrogram:
%
% Modified Spectrogram method
%
% (iii) Wigner Ville Distribution:
%
% Wigner Ville Distribution method. The original signal can be
% specified to correct the phase of the synthesised signal.
%
%
%
% See Also: wvd, spec
|
{-# LANGUAGE FlexibleContexts #-}
module FourierPinwheel.Filtering 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 Numeric.GSL.Special.Bessel
import Utils.List
{-# INLINE idealLowPassFilter #-}
idealLowPassFilter ::
(VG.Vector vector (Complex Double))
=> Double
-> Double
-> Int
-> Int
-> vector (Complex Double)
idealLowPassFilter radius period numRhoFreqs numRFreqs =
let centerRhoFreq = div numRhoFreqs 2
centerRFreq = div numRFreqs 2
sinc x =
if x == 0
then 1
else sin (pi * x) / (pi * x)
in VG.convert .
toUnboxed . computeS . fromFunction (Z :. numRFreqs :. numRhoFreqs) $ \(Z :. i' :. j') ->
let i = i' - centerRFreq
j = j' - centerRhoFreq
in -- if i == (j)
-- then
(2 * radius) / period *
sinc (fromIntegral j / period * (2 * radius)) :+
0
-- else 0
{-# INLINE applyFilterRho #-}
applyFilterRho ::
DFTPlan
-> VU.Vector (Complex Double)
-> R.Array U DIM4 (Complex Double)
-> IO (R.Array U DIM4 (Complex Double))
applyFilterRho plan filterF arr' = do
let (Z :. numRFreqs :. numThetaFreqs :. numRhoFreqs :. numPhiFreqs) =
extent arr'
arr =
computeUnboxedS $
R.backpermute
(Z :. numRFreqs :. numRhoFreqs :. numThetaFreqs :. numPhiFreqs)
(\(Z :. r :. rho :. theta :. phi) -> (Z :. r :. theta :. rho :. phi))
arr'
arrF <-
fmap (fromUnboxed (extent arr) . VG.convert) .
dftExecute
plan
(DFTPlanID
DFT1DG
[numRFreqs, numRhoFreqs, numThetaFreqs, numPhiFreqs]
[0, 1]) .
VG.convert . toUnboxed $
arr
let convolvedArrF =
computeUnboxedS .
R.traverse2
arrF
(fromUnboxed (Z :. numRFreqs :. numRhoFreqs) filterF)
const $ \fArr fFilter idx@(Z :. r :. rho :. theta :. phi) ->
fArr idx * fFilter (Z :. r :. rho)
fmap
(computeS .
R.backpermute
(Z :. numRFreqs :. numThetaFreqs :. numRhoFreqs :. numPhiFreqs)
(\(Z :. r :. theta :. rho :. phi) -> (Z :. r :. rho :. theta :. phi)) .
fromUnboxed (extent arr) . VG.convert) .
dftExecute
plan
(DFTPlanID
IDFT1DG
[numRFreqs, numRhoFreqs, numThetaFreqs, numPhiFreqs]
[0, 1]) .
VG.convert . toUnboxed $
convolvedArrF
hollowCoefficients ::
DFTPlan
-> Double
-> Double
-> R.Array U DIM4 (Complex Double)
-> IO (R.Array U DIM4 (Complex Double))
hollowCoefficients plan radius period coefficients = do
let (Z :. numRFreqs :. _ :. numRhoFreqs :. _) = extent coefficients
lpf = idealLowPassFilter (log radius) (log period) numRhoFreqs numRFreqs
filter =
VG.convert .
toUnboxed .
computeS . makeFilter2D . fromUnboxed (Z :. numRFreqs :. numRhoFreqs) $
lpf
filterF <-
VG.convert <$>
dftExecute plan (DFTPlanID DFT1DG [numRFreqs, numRhoFreqs] [0, 1]) filter
-- computeS . R.zipWith (-) coefficients <$>
applyFilterRho plan filterF coefficients
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Julia 1.4.0
# language: julia
# name: julia-1.4
# ---
# # 情報幾何学のお勉強のぉと
# ## 導入
#
# $p$,$q$ を正の実数とする. $y=px^2$, $x=qy^2$ という $xy$ - 平面上の曲線を考える.この二つの曲線は原点ともう一つの点 $P=(x_0,y_0)$ と交わる.簡単な計算によってそれは $p$, $q$ を用いると $P = (x_0,y_0) = (p^{-2/3}q^{-1/3}, p^{-1/3}q^{-2/3})$ で与えられることがわかる.これをプログラミング言語 Julia を用いて確認する.
using Plots
using Interact
function vis_crosspoint(p::Float64,q::Float64)
x = range(0,3,length=30) |> collect
y = range(0,3,length=30) |> collect
plot!(x,p*x.^2,color=:blue)
plot!(q*y.^2,y,color=:orange)
scatter!([p^(-2/3)*q^(-1/3)],[p^(-1/3)*q^(-2/3)])
end
# ## 試しに描画
plot(xlim=(0.,3.), ylim=(0.,3.), legend=:false)
vis_crosspoint(1.,2.4)
# ## Interact.jl で $p$ と $q$ を変動させた様子を描画
# +
p_slider = slider(0.001:0.1:3,label="p")
q_slider = slider(0.001:0.1:3,label="q")
plot(xlim=(0.,3.), ylim=(0.,3.), legend=:false)
cross_pt = map(
(p,q)->vis_crosspoint(p,q),
map(observe,[p_slider,q_slider])...,
)
[p_slider,q_slider,cross_pt] .|> display
# -
# ## $q$ を固定して $p$ だけ動かす
# +
plot(xlim=(0.,3.), ylim=(0.,3.), legend=:false)
anim = @animate for p in range(0.1,1,length=10)
p=vis_crosspoint(p,1.4)
plot!(p)
end
gif(anim, "/tmp/anim_fps15.gif", fps = 3)
|
Formal statement is: lemma divide_poly_main_list_simp [simp]: "divide_poly_main_list lc q r d (Suc n) = (let cr = hd r; a = cr div lc; qq = cCons a q; rr = minus_poly_rev_list r (map ((*) a) d) in if hd rr = 0 then divide_poly_main_list lc qq (tl rr) d n else [])" Informal statement is: If $r$ is the remainder of the division of a polynomial $p$ by a polynomial $q$, then the remainder of the division of $p$ by $q^2$ is the remainder of the division of $r$ by $q$. |
module Crypto.ECDH
import Crypto.Random
import Crypto.Curve.XCurves
import Crypto.Curve
import Data.Vect
import Utils.Misc
import Utils.Bytes
public export
interface ECDHCyclicGroup (0 a : Type) where
Scalar : Type
Element : Type
diffie_hellman : Scalar -> Element -> Maybe (List Bits8)
generate_key_pair : MonadRandom m => m (Scalar,Element)
deserialize_pk : List Bits8 -> Maybe Element
serialize_pk : Element -> List Bits8
public export
deserialize_then_dh : ECDHCyclicGroup dh => Scalar {a=dh} -> List Bits8 -> Maybe (List Bits8)
deserialize_then_dh sk pk = (deserialize_pk {a=dh} pk) >>= (diffie_hellman sk)
public export
data X25519_DH : Type where
public export
ECDHCyclicGroup X25519_DH where
Scalar = Vect 32 Bits8
Element = Vect 32 Bits8
diffie_hellman sk pk = map toList (XCurves.mul x25519 sk pk)
generate_key_pair = do
sk <- random_bytes 32
let Just pk = derive_public_key x25519 sk
| Nothing => generate_key_pair {a=X25519_DH}
pure (sk,pk)
deserialize_pk content = exactLength 32 $ fromList content
serialize_pk = toList
public export
data X448_DH : Type where
public export
ECDHCyclicGroup X448_DH where
Scalar = Vect 56 Bits8
Element = Vect 56 Bits8
diffie_hellman sk pk = map toList (XCurves.mul x448 sk pk)
generate_key_pair = do
sk <- random_bytes 56
let Just pk = derive_public_key x448 sk
| Nothing => generate_key_pair {a=X448_DH}
pure (sk,pk)
deserialize_pk content = exactLength 56 $ fromList content
serialize_pk = toList
public export
{p : _} -> Point p => ECDHCyclicGroup p where
Scalar = Integer
Element = p
diffie_hellman sk pk =
let (x, _) = to_affine $ mul sk pk
bytes = divCeilNZ (bits {p=p}) 8 SIsNonZero
in Just $ toList $ integer_to_be bytes x
generate_key_pair = do
sk <- uniform_random' 2 (order {p=p} - 1)
let pk = mul sk $ generator {p=p}
pure (sk,pk)
deserialize_pk = decode {p=p}
serialize_pk = encode {p=p}
|
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_histogram.h>
int
main (int argc, char **argv)
{
double a, b;
size_t n;
if (argc != 4)
{
printf ("Usage: gsl-histogram xmin xmax n\n"
"Computes a histogram of the data "
"on stdin using n bins from xmin "
"to xmax\n");
exit (0);
}
a = atof (argv[1]);
b = atof (argv[2]);
n = atoi (argv[3]);
{
double x;
gsl_histogram * h = gsl_histogram_alloc (n);
gsl_histogram_set_ranges_uniform (h, a, b);
while (fscanf (stdin, "%lg", &x) == 1)
{
gsl_histogram_increment (h, x);
}
gsl_histogram_fprintf (stdout, h, "%g", "%g");
gsl_histogram_free (h);
}
exit (0);
}
|
##CTE534_Índices=group
##Imagen=raster
##Green=number 2
##SWIR1=number 8
##MNDWI=output raster
##showplots
MNDWI <- raster::overlay(Imagen[[Green]],
Imagen[[SWIR1]],
fun=function(x,y){(x-y)/(x+y)})
plot(MNDWI)
|
Require Import CSPEC.
Require Import FSAPI.
Require Extraction.
Import ListNotations.
Require Import String.
Extraction Language Haskell.
Module FS <: FSAPI.
Definition pathname := FSAPI.pathname.
Axiom init : proc InitResult.
Axiom create : pathname -> string -> proc nat.
Axiom mkdir : pathname -> string -> proc nat.
Axiom delete : pathname -> proc unit.
Axiom rmdir : pathname -> proc unit.
Axiom rename_file : pathname -> pathname -> string -> proc unit.
Axiom read : pathname -> proc string.
Axiom write_logged : pathname -> string -> proc unit.
Axiom write_bypass : pathname -> string -> proc unit.
Axiom stat : pathname -> string -> proc FSAPI.stat_result.
Axiom readdir : pathname -> proc (list string).
Axiom recover : proc unit.
Axiom find_available_name : pathname -> proc string.
Axiom debug: string -> proc unit.
Axiom abstr : Abstraction State.
Axiom init_ok : init_abstraction init recover abstr inited.
Axiom create_ok : forall tid dir name, proc_spec (create_spec tid dir name) (create dir name) recover abstr.
Axiom mkdir_ok : forall tid dir name, proc_spec (mkdir_spec tid dir name) (mkdir dir name) recover abstr.
Axiom delete_ok : forall tid pn, proc_spec (delete_spec tid pn) (delete pn) recover abstr.
Axiom rmdir_ok : forall tid pn, proc_spec (rmdir_spec tid pn) (rmdir pn) recover abstr.
Axiom rename_file_ok : forall pn newdir newname, proc_spec (rename_file_spec pn newdir newname) (rename_file pn newdir newname) recover abstr.
Axiom read_ok : forall pn, proc_spec (read_spec pn) (read pn) recover abstr.
Axiom write_logged_ok : forall pn f, proc_spec (write_logged_spec pn f) (write_logged pn f) recover abstr.
Axiom write_bypass_ok : forall pn f, proc_spec (write_bypass_spec pn f) (write_bypass pn f) recover abstr.
Axiom stat_ok : forall pn n, proc_spec (stat_spec pn n) (stat pn n) recover abstr.
Axiom readdir_ok : forall pn, proc_spec (readdir_spec pn) (readdir pn) recover abstr.
Axiom recover_noop : rec_noop recover abstr no_crash.
Axiom find_available_name_ok : forall tid dirpn,
proc_spec (find_available_name_spec tid dirpn) (find_available_name dirpn) recover abstr.
Axiom debug_ok : forall s, proc_spec (debug_spec) (debug s) recover abstr.
End FS.
Extract Constant FS.init => "FS.Ops.init".
Extract Constant FS.create => "FS.Ops.create".
Extract Constant FS.mkdir => "FS.Ops.mkdir".
Extract Constant FS.write_logged => "FS.Ops.write_logged".
Extract Constant FS.debug => "FS.Ops.debug".
(* XXX should be split: it should call find_avaialbe_name, but we should check
* in Gallina that the name returned is indeed available and proof the check
* correct. For now completely trusted. *)
Extract Constant FS.find_available_name => "FS.Ops.find_available_name".
|
! 2. Write a program that asks the user for their name and greets them with their name.
program Exercises
implicit none
character(len=16) :: name
print *, 'Please enter your name.'
read(*, '(a)') name
print *, 'Hello, ', name
end program Exercises
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import algebraic_geometry.locally_ringed_space
import algebraic_geometry.structure_sheaf
import data.equiv.transfer_instance
import topology.sheaves.sheaf_condition.sites
import topology.sheaves.functors
/-!
# $Spec$ as a functor to locally ringed spaces.
We define the functor $Spec$ from commutative rings to locally ringed spaces.
## Implementation notes
We define $Spec$ in three consecutive steps, each with more structure than the last:
1. `Spec.to_Top`, valued in the category of topological spaces,
2. `Spec.to_SheafedSpace`, valued in the category of sheafed spaces and
3. `Spec.to_LocallyRingedSpace`, valued in the category of locally ringed spaces.
Additionally, we provide `Spec.to_PresheafedSpace` as a composition of `Spec.to_SheafedSpace` with
a forgetful functor.
## Related results
The adjunction `Γ ⊣ Spec` is constructed in `algebraic_geometry/Gamma_Spec_adjunction.lean`.
-/
noncomputable theory
universes u v
namespace algebraic_geometry
open opposite
open category_theory
open structure_sheaf
/--
The spectrum of a commutative ring, as a topological space.
-/
def Spec.Top_obj (R : CommRing) : Top := Top.of (prime_spectrum R)
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of topological spaces.
-/
def Spec.Top_map {R S : CommRing} (f : R ⟶ S) :
Spec.Top_obj S ⟶ Spec.Top_obj R :=
prime_spectrum.comap f
@[simp] lemma Spec.Top_map_id (R : CommRing) :
Spec.Top_map (𝟙 R) = 𝟙 (Spec.Top_obj R) :=
prime_spectrum.comap_id
lemma Spec.Top_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.Top_map (f ≫ g) = Spec.Top_map g ≫ Spec.Top_map f :=
prime_spectrum.comap_comp _ _
/--
The spectrum, as a contravariant functor from commutative rings to topological spaces.
-/
@[simps] def Spec.to_Top : CommRingᵒᵖ ⥤ Top :=
{ obj := λ R, Spec.Top_obj (unop R),
map := λ R S f, Spec.Top_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.Top_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.Top_map_comp] }
/--
The spectrum of a commutative ring, as a `SheafedSpace`.
-/
@[simps] def Spec.SheafedSpace_obj (R : CommRing) : SheafedSpace CommRing :=
{ carrier := Spec.Top_obj R,
presheaf := (structure_sheaf R).1,
is_sheaf := (structure_sheaf R).2 }
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of sheafed spaces.
-/
@[simps] def Spec.SheafedSpace_map {R S : CommRing.{u}} (f : R ⟶ S) :
Spec.SheafedSpace_obj S ⟶ Spec.SheafedSpace_obj R :=
{ base := Spec.Top_map f,
c :=
{ app := λ U, comap f (unop U) ((topological_space.opens.map (Spec.Top_map f)).obj (unop U))
(λ p, id),
naturality' := λ U V i, ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, rfl } }
@[simp] lemma Spec.SheafedSpace_map_id {R : CommRing} :
Spec.SheafedSpace_map (𝟙 R) = 𝟙 (Spec.SheafedSpace_obj R) :=
PresheafedSpace.ext _ _ (Spec.Top_map_id R) $ nat_trans.ext _ _ $ funext $ λ U,
begin
dsimp,
erw [PresheafedSpace.id_c_app, comap_id], swap,
{ rw [Spec.Top_map_id, topological_space.opens.map_id_obj_unop] },
simpa,
end
lemma Spec.SheafedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.SheafedSpace_map (f ≫ g) = Spec.SheafedSpace_map g ≫ Spec.SheafedSpace_map f :=
PresheafedSpace.ext _ _ (Spec.Top_map_comp f g) $ nat_trans.ext _ _ $ funext $ λ U,
by { dsimp, rw category_theory.functor.map_id, rw category.comp_id, erw comap_comp f g, refl }
/--
Spec, as a contravariant functor from commutative rings to sheafed spaces.
-/
@[simps] def Spec.to_SheafedSpace : CommRingᵒᵖ ⥤ SheafedSpace CommRing :=
{ obj := λ R, Spec.SheafedSpace_obj (unop R),
map := λ R S f, Spec.SheafedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.SheafedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.SheafedSpace_map_comp] }
/--
Spec, as a contravariant functor from commutative rings to presheafed spaces.
-/
def Spec.to_PresheafedSpace : CommRingᵒᵖ ⥤ PresheafedSpace CommRing :=
Spec.to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace
@[simp] lemma Spec.to_PresheafedSpace_obj (R : CommRingᵒᵖ) :
Spec.to_PresheafedSpace.obj R = (Spec.SheafedSpace_obj (unop R)).to_PresheafedSpace := rfl
lemma Spec.to_PresheafedSpace_obj_op (R : CommRing) :
Spec.to_PresheafedSpace.obj (op R) = (Spec.SheafedSpace_obj R).to_PresheafedSpace := rfl
@[simp] lemma Spec.to_PresheafedSpace_map (R S : CommRingᵒᵖ) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f = Spec.SheafedSpace_map f.unop := rfl
lemma Spec.to_PresheafedSpace_map_op (R S : CommRing) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f.op = Spec.SheafedSpace_map f := rfl
lemma Spec.basic_open_hom_ext {X : RingedSpace} {R : CommRing} {α β : X ⟶ Spec.SheafedSpace_obj R}
(w : α.base = β.base) (h : ∀ r : R, let U := prime_spectrum.basic_open r in
(to_open R U ≫ α.c.app (op U)) ≫ X.presheaf.map (eq_to_hom (by rw w)) =
to_open R U ≫ β.c.app (op U)) : α = β :=
begin
ext1,
{ apply ((Top.sheaf.pushforward β.base).obj X.sheaf).hom_ext _
prime_spectrum.is_basis_basic_opens,
intro r,
apply (structure_sheaf.to_basic_open_epi R r).1,
simpa using h r },
exact w,
end
/--
The spectrum of a commutative ring, as a `LocallyRingedSpace`.
-/
@[simps] def Spec.LocallyRingedSpace_obj (R : CommRing) : LocallyRingedSpace :=
{ local_ring := λ x, @@ring_equiv.local_ring _
(show local_ring (localization.at_prime _), by apply_instance) _
(iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm,
.. Spec.SheafedSpace_obj R }
@[elementwise]
lemma stalk_map_to_stalk {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
to_stalk R (prime_spectrum.comap f p) ≫
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p =
f ≫ to_stalk S p :=
begin
erw [← to_open_germ S ⊤ ⟨p, trivial⟩, ← to_open_germ R ⊤ ⟨prime_spectrum.comap f p, trivial⟩,
category.assoc, PresheafedSpace.stalk_map_germ (Spec.SheafedSpace_map f) ⊤ ⟨p, trivial⟩,
Spec.SheafedSpace_map_c_app, to_open_comp_comap_assoc],
refl
end
/--
Under the isomorphisms `stalk_iso`, the map `stalk_map (Spec.SheafedSpace_map f) p` corresponds
to the induced local ring homomorphism `localization.local_ring_hom`.
-/
@[elementwise]
lemma local_ring_hom_comp_stalk_iso {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
(stalk_iso R (prime_spectrum.comap f p)).hom ≫
@category_struct.comp _ _
(CommRing.of (localization.at_prime (prime_spectrum.comap f p).as_ideal))
(CommRing.of (localization.at_prime p.as_ideal)) _
(localization.local_ring_hom (prime_spectrum.comap f p).as_ideal p.as_ideal f rfl)
(stalk_iso S p).inv =
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p :=
(stalk_iso R (prime_spectrum.comap f p)).eq_inv_comp.mp $ (stalk_iso S p).comp_inv_eq.mpr $
localization.local_ring_hom_unique _ _ _ _ $ λ x, by
rw [stalk_iso_hom, stalk_iso_inv, comp_apply, comp_apply, localization_to_stalk_of,
stalk_map_to_stalk_apply, stalk_to_fiber_ring_hom_to_stalk]
/--
The induced map of a ring homomorphism on the prime spectra, as a morphism of locally ringed spaces.
-/
@[simps] def Spec.LocallyRingedSpace_map {R S : CommRing} (f : R ⟶ S) :
Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R :=
subtype.mk (Spec.SheafedSpace_map f) $ λ p, is_local_ring_hom.mk $ λ a ha,
begin
-- Here, we are showing that the map on prime spectra induced by `f` is really a morphism of
-- *locally* ringed spaces, i.e. that the induced map on the stalks is a local ring homomorphism.
rw ← local_ring_hom_comp_stalk_iso_apply at ha,
replace ha := (stalk_iso S p).hom.is_unit_map ha,
rw coe_inv_hom_id at ha,
replace ha := is_local_ring_hom.map_nonunit _ ha,
convert ring_hom.is_unit_map (stalk_iso R (prime_spectrum.comap f p)).inv ha,
rw coe_hom_inv_id,
end
@[simp] lemma Spec.LocallyRingedSpace_map_id (R : CommRing) :
Spec.LocallyRingedSpace_map (𝟙 R) = 𝟙 (Spec.LocallyRingedSpace_obj R) :=
subtype.ext $ by { rw [Spec.LocallyRingedSpace_map_coe, Spec.SheafedSpace_map_id], refl }
lemma Spec.LocallyRingedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.LocallyRingedSpace_map (f ≫ g) =
Spec.LocallyRingedSpace_map g ≫ Spec.LocallyRingedSpace_map f :=
subtype.ext $ by { rw [Spec.LocallyRingedSpace_map_coe, Spec.SheafedSpace_map_comp], refl }
/--
Spec, as a contravariant functor from commutative rings to locally ringed spaces.
-/
@[simps] def Spec.to_LocallyRingedSpace : CommRingᵒᵖ ⥤ LocallyRingedSpace :=
{ obj := λ R, Spec.LocallyRingedSpace_obj (unop R),
map := λ R S f, Spec.LocallyRingedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.LocallyRingedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.LocallyRingedSpace_map_comp] }
section Spec_Γ
open algebraic_geometry.LocallyRingedSpace
/-- The counit morphism `R ⟶ Γ(Spec R)` given by `algebraic_geometry.structure_sheaf.to_open`. -/
@[simps] def to_Spec_Γ (R : CommRing) : R ⟶ Γ.obj (op (Spec.to_LocallyRingedSpace.obj (op R))) :=
structure_sheaf.to_open R ⊤
instance is_iso_to_Spec_Γ (R : CommRing) : is_iso (to_Spec_Γ R) :=
by { cases R, apply structure_sheaf.is_iso_to_global }
@[reassoc]
lemma Spec_Γ_naturality {R S : CommRing} (f : R ⟶ S) :
f ≫ to_Spec_Γ S = to_Spec_Γ R ≫ Γ.map (Spec.to_LocallyRingedSpace.map f.op).op :=
by { ext, symmetry, apply localization.local_ring_hom_to_map }
/-- The counit (`Spec_Γ_identity.inv.op`) of the adjunction `Γ ⊣ Spec` is an isomorphism. -/
@[simps hom_app inv_app] def Spec_Γ_identity : Spec.to_LocallyRingedSpace.right_op ⋙ Γ ≅ 𝟭 _ :=
iso.symm $ nat_iso.of_components (λ R, as_iso (to_Spec_Γ R) : _) (λ _ _, Spec_Γ_naturality)
end Spec_Γ
/-- The stalk map of `Spec M⁻¹R ⟶ Spec R` is an iso for each `p : Spec M⁻¹R`. -/
lemma Spec_map_localization_is_iso (R : CommRing) (M : submonoid R)
(x : prime_spectrum (localization M)) :
is_iso (PresheafedSpace.stalk_map (Spec.to_PresheafedSpace.map
(CommRing.of_hom (algebra_map R (localization M))).op) x) :=
begin
erw ← local_ring_hom_comp_stalk_iso,
apply_with is_iso.comp_is_iso { instances := ff },
apply_instance,
apply_with is_iso.comp_is_iso { instances := ff },
/- I do not know why this is defeq to the goal, but I'm happy to accept that it is. -/
exact (show is_iso (is_localization.localization_localization_at_prime_iso_localization
M x.as_ideal).to_ring_equiv.to_CommRing_iso.hom, by apply_instance),
apply_instance
end
end algebraic_geometry
|
! ##################################################################################################################################
! Begin MIT license text.
! _______________________________________________________________________________________________________
! Copyright 2019 Dr William R Case, Jr ([email protected])
! Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
! associated documentation files (the "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be included in all copies or substantial
! portions of the Software and documentation.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
! THE SOFTWARE.
! _______________________________________________________________________________________________________
! End MIT license text.
SUBROUTINE BSMIN3 ( XI, A, B, AREA, MESSAG, WRT_BUG_THIS_TIME, BS )
! Calculate BS shear strain/displacement matrix for MIN3 triangle. Called by subr TPLT2
USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE
USE IOUNT1, ONLY : BUG, F04, WRT_BUG, WRT_LOG
USE SCONTR, ONLY : BLNK_SUB_NAM, ELDT_BUG_BMAT_BIT, ELDT_BUG_BCHK_BIT, MIN4T_QUAD4_TRIA_NO
USE TIMDAT, ONLY : TSEC
USE SUBR_BEGEND_LEVELS, ONLY : BSMIN3_BEGEND
USE CONSTANTS_1, ONLY : ZERO, TWO
USE MODEL_STUF, ONLY : EID, TYPE, XTB, XTL
USE DEBUG_PARAMETERS, ONLY : DEBUG
USE BSMIN3_USE_IFs
IMPLICIT NONE
CHARACTER(LEN=LEN(BLNK_SUB_NAM)):: SUBR_NAME = 'BSMIN3'
CHARACTER(LEN=*), INTENT(IN) :: MESSAG ! Message to print out if BCHECK is run
CHARACTER( 1*BYTE), INTENT(IN) :: WRT_BUG_THIS_TIME ! If 'Y' then write to BUG file if WRT_BUG array says to
INTEGER(LONG) :: I,J ! DO loop indices
INTEGER(LONG) :: ID(9) ! An input to subr BCHECK, called herein
INTEGER(LONG), PARAMETER :: NR = 2 ! An input to subr BCHECK, called herein
INTEGER(LONG), PARAMETER :: NC = 9 ! An input to subr BCHECK, called herein
INTEGER(LONG), PARAMETER :: SUBR_BEGEND = BSMIN3_BEGEND
REAL(DOUBLE) , INTENT(IN) :: A(3) ! Vector of x coord differences
REAL(DOUBLE) , INTENT(IN) :: AREA ! Elem area
REAL(DOUBLE) , INTENT(IN) :: B(3) ! Vector of y coord differences
REAL(DOUBLE) , INTENT(IN) :: XI(3) ! Vector of area coordinates
REAL(DOUBLE) , INTENT(OUT) :: BS(2,9) ! Output strain-displ matrix for this elem
REAL(DOUBLE) :: A4 ! Constant for this elem
REAL(DOUBLE) :: BW(2,14) ! Output from subr BCHECK (matrix of 2 elem strains for 14 various elem
! rigid body motions/constant strain distortions)
! **********************************************************************************************************************************
IF (WRT_LOG >= SUBR_BEGEND) THEN
CALL OURTIM
WRITE(F04,9001) SUBR_NAME,TSEC, WRT_BUG_THIS_TIME, WRT_BUG(7), WRT_BUG(8), WRT_BUG(9)
9001 FORMAT(1X,A,' BEGN ',F10.3, 3X, A1, 3(I3))
ENDIF
! **********************************************************************************************************************************
! Initialize outputs
DO I=1,2
DO J=1,9
BS(I,J) = ZERO
ENDDO
ENDDO
! Calc outputs
A4 = 4*AREA
DO J=1,3
BS(1,J) = B(J)/(TWO*AREA)
BS(2,J) = A(J)/(TWO*AREA)
ENDDO
BS(1,4) = -(B(1)*( XI(2)*B(3) - XI(3)*B(2))/A4)
BS(1,5) = -(B(2)*(-XI(1)*B(3) + XI(3)*B(1))/A4)
BS(1,6) = -(B(3)*( XI(1)*B(2) - XI(2)*B(1))/A4)
BS(1,7) = (XI(1)*(A4 - B(2)*A(3) + B(3)*A(2)) + B(1)*(-XI(2)*A(3) + XI(3)*A(2)))/A4
BS(1,8) = (XI(2)*(A4 + B(1)*A(3) - B(3)*A(1)) + B(2)*( XI(1)*A(3) - XI(3)*A(1)))/A4
BS(1,9) = (XI(3)*(A4 + B(2)*A(1) - B(1)*A(2)) + B(3)*(-XI(1)*A(2) + XI(2)*A(1)))/A4
BS(2,4) = -(XI(1)*(A4 + A(2)*B(3) - A(3)*B(2)) + A(1)*( XI(2)*B(3) - XI(3)*B(2)))/A4
BS(2,5) = -(XI(2)*(A4 - A(1)*B(3) + A(3)*B(1)) + A(2)*(-XI(1)*B(3) + XI(3)*B(1)))/A4
BS(2,6) = -(XI(3)*(A4 - A(2)*B(1) + A(1)*B(2)) + A(3)*( XI(1)*B(2) - XI(2)*B(1)))/A4
BS(2,7) = A(1)*(-XI(2)*A(3) + XI(3)*A(2))/A4
BS(2,8) = A(2)*( XI(1)*A(3) - XI(3)*A(1))/A4
BS(2,9) = A(3)*(-XI(1)*A(2) + XI(2)*A(1))/A4
IF ((WRT_BUG_THIS_TIME == 'Y') .AND. (WRT_BUG(8) > 0)) THEN
WRITE(BUG,1101) ELDT_BUG_BMAT_BIT, TYPE, EID, MIN4T_QUAD4_TRIA_NO
WRITE(BUG,8901) SUBR_NAME
DO I=1,2
WRITE(BUG,8902) I,(BS(I,J),J=1,9)
WRITE(BUG,*)
ENDDO
WRITE(BUG,*)
ENDIF
! xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
! As of 03/07/2020 there is some error in the calculation of the check on strain displ matrices for constant strain modes
! of displacement. Therefore, this check is temporarily suspended
IF ((WRT_BUG_THIS_TIME == 'Y') .AND. (WRT_BUG(9) > 0)) THEN
IF (DEBUG(202) > 0) THEN
ID(1) = 3
ID(2) = 9
ID(3) = 15
ID(4) = 4
ID(5) = 10
ID(6) = 16
ID(7) = 5
ID(8) = 11
ID(9) = 17
WRITE(BUG,1101) ELDT_BUG_BCHK_BIT, TYPE, EID, MIN4T_QUAD4_TRIA_NO
WRITE(BUG,9100)
WRITE(BUG,9101) MESSAG
WRITE(BUG,9102)
WRITE(BUG,9103)
WRITE(BUG,9104)
CALL BCHECK_2D ( BS, 'S', ID, NR, NC, 3, XTL, XTB, BW )
ENDIF
ENDIF
! **********************************************************************************************************************************
IF (WRT_LOG >= SUBR_BEGEND) THEN
CALL OURTIM
WRITE(F04,9002) SUBR_NAME,TSEC
9002 FORMAT(1X,A,' END ',F10.3)
ENDIF
RETURN
! **********************************************************************************************************************************
1101 FORMAT(' ------------------------------------------------------------------------------------------------------------------',&
'-----------------',/, &
' ELDATA(',I2,',PRINT) requests for ',A,' element number ',I8, ' (triangle number ',I1,' of 4 for the QUAD4 elem)'/, &
' ==============================================================',/)
8901 FORMAT(' Strain-displacement matrix BS for transverse shear portion of element in subr ',A,/)
8902 FORMAT(' Row ',I2,/,9(1ES14.6))
9100 FORMAT(14X,'Check on strain-displacement matrix BS for transverse shear portion of the element in subr BCHECK'/)
9101 FORMAT(56X,'S T R A I N S'/,50X,A)
9102 FORMAT(54X,'Gxz Gyz')
9103 FORMAT(7X,'Element displacements consistent with:')
9104 FORMAT(7X,'---------------------------------------')
90003 FORMAT(1X,3(1ES19.11))
! **********************************************************************************************************************************
END SUBROUTINE BSMIN3
|
## [Problem 41](https://projecteuler.net/problem=41)
Pandigital prime
```python
import itertools
from sympy import isprime
seq = [7,6,5,4,3,2,1]
```
```python
def list2num(permutated_list):
num = 0
for i in range(7):
num += permutated_list[i]*10**(7-i)
```
```python
list7 = list(itertools.permutations(seq))
int7 = [int(''.join([str(_) for _ in __])) for __ in list7]
```
```python
for i in int7:
if isprime(i):
print(i)
break
```
7652413
## [Problem 42](https://projecteuler.net/problem=42)
Coded triangle numbers
```python
import csv,string
f = open('./data/p042.txt', "r")
file = list(csv.reader(f))[0]
```
```python
def word2num(word):
counter = 0
for alphabet in word:
counter += string.ascii_uppercase.index(alphabet)+1
return counter
```
```python
num_list = [word2num(word) for word in file]
```
```python
triangle_list = [int(n*(n+1)/2) for n in range(1,20)]
```
```python
counter = 0
for num in num_list:
if [num] == list(set([num]) & set(triangle_list)):
counter += 1
counter
```
162
## [Problem 43](https://projecteuler.net/problem=43)
Sub-string divisibility
```python
import copy
ten_str={str(i) for i in range(10)}
```
```python
pandigital_numbers=[]
tmps=[]
for i in range(1,59):
num=str(i*17).zfill(3)
if len(set(num))==3:
pandigital_numbers.append(num)
for x in [13,11,7,5,3,2]:
tmps=[]
for num in pandigital_numbers:
for i in ten_str-set(num):
tmp=str(i)+num
if int(tmp[:3])%x==0:
tmps.append(tmp)
pandigital_numbers=copy.copy(tmps)
pandigital_numbers=[str(list(ten_str-set(num))[0])+num for num in pandigital_numbers]
```
```python
sum_pandigital=0
for num in pandigital_numbers:
sum_pandigital+=int(num)
print(sum_pandigital)
```
16695334890
## [Problem 44](https://projecteuler.net/problem=44)
Pentagon numbers
```python
import numpy as np
from tqdm import tqdm
```
```python
def p(n):
return int(n*(3*n-1)/2)
def factorize(n):
answer=[]
max_factor=int(np.sqrt(n))
for i in range(1,max_factor+1):
if n%i==0:
answer.append([i,n//i])
return answer
def check_squred(n):
m=int(np.sqrt(n))
if m-n/m==0.0:
return True
else:
return False
def jk_list_from_m(m):
jk_list=[]
n=3*m*m-m
factors=factorize(n)
for factor in factors:
q,p=factor
j,k=int(((p+1)/3+q)/2),int(((p+1)/3-q)/2)
if 3*(j*j-k*k)-j+k==n and k>0:
jk_list.append([j,k])
return jk_list
def check_valid_jk(jk):
j,k=jk
n=3*(j*j+k*k)-j-k
l=int((1+np.sqrt(1+12*n))/6)
if 3*l*l-l-n==0:
return True
else:
return False
```
```python
max_m=5000
for m in tqdm(range(1,max_m)):
jk_list=jk_list_from_m(m)
for jk in jk_list:
if check_valid_jk(jk):
print(m,p(m))
```
46%|████▌ | 2287/4999 [00:00<00:00, 3221.80it/s]
1912 5482660
100%|██████████| 4999/4999 [00:02<00:00, 2133.62it/s]
## [Problem 45](https://projecteuler.net/problem=45)
Triangular, pentagonal, and hexagonal
```python
import numpy as np
from tqdm import tqdm
```
```python
def check_valid_n(n):
n=4*n*n-2*n
m=int((1+np.sqrt(1+12*n))/6)
if 3*m*m-m-n==0:
l=int((-1+np.sqrt(1+4*n))/2)
if l*l+l-n==0:
return True
else:
return False
else:
return False
```
```python
max_n=100000
for n in tqdm(range(1,max_n)):
if check_valid_n(n):
print(n,2*n*n-n)
```
37%|███▋ | 36701/99999 [00:00<00:00, 180175.55it/s]
1 1
143 40755
27693 1533776805
100%|██████████| 99999/99999 [00:00<00:00, 199493.64it/s]
## [Problem 46](https://projecteuler.net/problem=46)
Goldbach's other conjecture
```python
from sympy import sieve
import numpy as np
from itertools import product
from tqdm import tqdm
```
```python
max_num=10**5
goldbach_conjecture_list=[i for i in tqdm(range(2,max_num)) if i not in sieve and i%2==1]
```
100%|██████████| 99998/99998 [00:06<00:00, 15029.80it/s]
```python
for goldbach_conjecture in tqdm(goldbach_conjecture_list):
max_square_root=int(np.sqrt(goldbach_conjecture/2))
check_prime_list=[goldbach_conjecture-2*i*i for i in range(1,max_square_root+1)]
check_list=[num in sieve for num in check_prime_list]
check={False}==set(check_list)
if check:
print(goldbach_conjecture)
break
```
5%|▌ | 2104/40408 [00:02<01:44, 365.06it/s]
5777
## [Problem 47](https://projecteuler.net/problem=47)
Distinct primes factors
```python
from sympy import factorint
```
```python
def len_factor(n):
return len(list(factorint(n).keys()))
```
```python
n=210
flag=True
while flag:
four_nums=[n,n+1,n+2,n+3]
prime_nums=[len_factor(n) for n in four_nums]
flag=False
for i in range(4):
if prime_nums[i]!=4:
flag=True
n=four_nums[i]+1
continue
```
```python
n,prime_nums
```
(134043, [4, 4, 4, 4])
## [Problem 48](https://projecteuler.net/problem=48)
Self powers
```python
from scipy.special import comb
```
```python
answer=0
for i in range(1,11):
answer+=i**i
for i in range(11,1001):
x=i-10
for k in range(10):
answer+=(10**k)*(x**(i-k))*comb(i,k,True)
```
```python
answer%10**10
```
9110846700
## [Problem 49](https://projecteuler.net/problem=49)
Prime permutations
```python
from sympy import sieve
from itertools import permutations
from itertools import combinations
from tqdm import tqdm
import numpy as np
from copy import copy
```
```python
def permutate_num(n):
nums=[]
for xs in permutations(str(n)):
num=''
for x in xs:
num+=x
nums.append(int(num))
return nums
def increases(num_list):
n=len(num_list)
for i,j,k in combinations(range(n),3):
if num_list[k]-num_list[j]==num_list[j]-num_list[i]:
print(str(num_list[i])+str(num_list[j])+str(num_list[k]))
```
```python
prime_list=list(sieve.primerange(10**3,10**4))
prime_set=set(prime_list)
```
```python
possibly_permutation=[]
for prime in tqdm(prime_list):
permutate_list=permutate_num(prime)
permutate_prime_list=list(sorted(list(set([x for x in permutate_list if x in set(prime_list)]))))
if len(permutate_prime_list)>2:
possibly_permutation.append(permutate_prime_list)
```
100%|██████████| 1061/1061 [00:00<00:00, 1143.42it/s]
```python
permutation_list=[]
for nums in possibly_permutation:
if nums not in permutation_list:
permutation_list.append(nums)
```
```python
for permutation in tqdm(permutation_list):
increases(permutation)
```
100%|██████████| 174/174 [00:00<00:00, 20055.20it/s]
148748178147
296962999629
## [Problem 50](https://projecteuler.net/problem=50)
Consecutive prime sum
```python
from sympy import sieve
import numpy as np
from tqdm import tqdm
```
```python
prime_list=[i for i in sieve.primerange(1,10**6)]
dp=[set(prime_list)]
```
```python
newArray=prime_list.copy()
for i in tqdm(range(600)):
newArray=np.array(prime_list[i+1:])+np.array(newArray[:-1])
dp.append(set(newArray))
```
100%|██████████| 600/600 [00:08<00:00, 69.36it/s]
```python
for i in range(600):
intersection=dp[600-i-1] & dp[0]
if len(intersection)>0:
print(intersection)
break
```
{997651}
```python
```
|
H.F.&PH.F. Reemtsma GmbH & Co.
Philine von Sell’s films have won 28 national and international awards and accolades (1989-2009).
Her photographic works and multimedia installations have been shown in solo exhibitions in museums and galleries in Cape Town, Johannesburg, Berlin and Cologne (Collection of the German Bundestag, collection of Count Faber-Castell and various private collections).
Former professor (C4) HFF HOCHSCHULE FÜR FILM UND FERNSEHEN, München.
LIFETIME FOUNDATION, in rual areas in South Africa: Gauteng, Western Cape, Venda.
Many workshops, seminars and lectures in companies, universities.
children from the Nazareth House, Cape Town, South Africa.
German/English. 108 pages, 70 colour illustrations.
Special limited edition, numbered print run: 700.
realization, editing, cover design and typesetting.
University of Television and Film Munich HFF München 2008.
Philine von Sell’s photographic works and multimedia installations have been shown in solo exhibitions in museums and galleries in Cape Town, Johannesburg, Berlin and Cologne (Collection of the German Bundestag, collection of Count Faber-Castell and various private collections).
Goethe Institute, Daimler Chrysler AG, Faber-Castell.
In cooperation with the German Aids Foundation and the Foreign Ministry. |
module Matrixes
import Data.Vect
sum : Num numType => Vect rows (Vect cols numType) ->
Vect rows (Vect cols numType) ->
Vect rows (Vect cols numType)
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import data.nat.choose.basic
import data.nat.prime
/-!
# Divisibility properties of binomial coefficients
-/
namespace nat
open_locale nat
namespace prime
lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b)
(hp : prime p) : p ∣ choose (a + b) a :=
have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h,
have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap),
have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp),
by
rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul,
add_tsub_cancel_left a b] at h₁;
exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩)
lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) :
p ∣ choose p k :=
begin
have r : k + (p - k) = p,
by rw [← add_tsub_assoc_of_le (nat.le_of_lt hkp) k, add_tsub_cancel_left],
have e : p ∣ choose (k + (p - k)) k,
by exact dvd_choose_add hkp (nat.sub_lt (hk.trans hkp) hk) (by rw r) hp,
rwa r at e,
end
end prime
end nat
|
import analysis.normed_space.banach
import analysis.normed_space.basic
import linear_algebra.basic
import linear_algebra.basis
import linear_algebra.dimension
import linear_algebra.finite_dimensional
import topology.subset_properties
import set_theory.cardinal
import data.real.basic
import topology.sequences
import order.bounded_lattice
import analysis.specific_limits
import analysis.normed_space.finite_dimension
noncomputable theory
open_locale classical
local attribute [instance, priority 20000] nat.has_zero nat.has_one real.domain
local attribute [instance, priority 10000] mul_action.to_has_scalar distrib_mul_action.to_mul_action
semimodule.to_distrib_mul_action module.to_semimodule vector_space.to_module normed_space.to_vector_space
ring.to_monoid normed_ring.to_ring normed_field.to_normed_ring add_group.to_add_monoid
add_comm_group.to_add_group normed_group.to_add_comm_group ring.to_semiring add_comm_group.to_add_comm_monoid
normed_field.to_discrete_field normed_field.to_has_norm nondiscrete_normed_field.to_normed_field
zero_ne_one_class.to_has_zero zero_ne_one_class.to_has_one domain.to_zero_ne_one_class
division_ring.to_domain field.to_division_ring discrete_field.to_field
set_option class.instance_max_depth 100
open metric set
universe u
-- completeness of k is only assumed so we can use the library to prove that
-- the span of a finite set is closed.
-- This is indeed necessary since as Sebastian Gouezel has pointed out,
-- Q in R is not closed but it is the span of the finite set {1}!
variables
{k : Type} [nondiscrete_normed_field k] [complete_space k]
{V : Type} [normed_group V] [normed_space k V]
lemma nontrivial_norm_gt_one: ∃ x : k, x ≠ 0 ∧ norm x > 1 :=
begin
cases normed_field.exists_one_lt_norm k with x hx,
refine ⟨x, _, hx⟩,
intro hzero,
rw [hzero, norm_zero] at hx,
linarith,
end
lemma nontrivial_arbitrarily_small_norm
{e : ℝ} (he : e > 0) : ∃ x : k, x ≠ 0 ∧ norm x < e :=
begin
rcases normed_field.exists_norm_lt k he with ⟨x, hx₁, hx₂⟩,
refine ⟨x, _, hx₂⟩,
intro xzero,
rw [xzero, norm_zero] at hx₁,
linarith
end
lemma nontrivial_norm_lt_one: ∃ x : k, x ≠ 0 ∧ norm x < 1 :=
nontrivial_arbitrarily_small_norm (by linarith)
lemma ball_span_ash {A : set V}
(hyp : ∀ v : V, norm v ≤ 1 → v ∈ submodule.span k A) (v : V) :
v ∈ submodule.span k A :=
begin
by_cases v0 : v = 0,
{ rw v0,
exact submodule.zero_mem _ },
{ have norm_pos : 0 < norm v, from (norm_pos_iff v).mpr v0,
obtain ⟨x, hx₁, hx₂⟩ : ∃ x : k, x ≠ 0 ∧ norm x < 1 / norm v,
from nontrivial_arbitrarily_small_norm (one_div_pos_of_pos norm_pos),
rw ← submodule.smul_mem_iff (submodule.span k A) hx₁,
apply hyp (x • v),
rw [norm_smul],
exact le_of_lt (mul_lt_of_lt_div norm_pos hx₂) }
end
/-- If A spans the closed unit ball then it spans all of V -/
lemma ball_span {A : set V} (H : (closed_ball 0 1 : set V) ⊆ submodule.span k A) : ∀ v : V, v ∈ submodule.span k A :=
begin
apply ball_span_ash,
intros v hv,
rw ← dist_zero_right at hv,
exact H hv,
end
theorem finite_dimensional_span_of_finite {A : set V} (hA : finite A) :
finite_dimensional k ↥(submodule.span k A) :=
begin
apply is_noetherian_of_fg_of_noetherian,
exact submodule.fg_def.2 ⟨A, hA, rfl⟩,
end
-- the span of a finite set is (sequentially) closed
lemma finite_span_seq_closed
(A : set V) : finite A → is_seq_closed (↑(submodule.span k A) : set V) :=
begin
intro h_fin,
apply is_seq_closed_of_is_closed,
haveI : finite_dimensional k ↥(submodule.span k A) := finite_dimensional_span_of_finite h_fin,
exact submodule.closed_of_finite_dimensional _,
end
--turns cover into a choice function
lemma cover_to_func (A X : set V) {r : ℝ} (hX : X ⊆ (⋃a ∈ A, ball a r))
(a : V) (ha : a ∈ A) :
∃(f : V → V), ∀x, f x ∈ A ∧ (x ∈ X → x ∈ ball (f x) r) :=
begin
classical,
have : ∀(x : V), ∃a, a ∈ A ∧ (x ∈ X → x ∈ ball a r) :=
begin
assume x,
by_cases h : x ∈ X,
{ simpa [h] using hX h },
{ exact ⟨a, ha, by simp [h]⟩ }
end,
choose f hf using this,
exact ⟨f, λx, hf x⟩
end
-- if the closed unit ball is compact, then there is
-- a function which selects the center of a ball of radius 1/2 close to it
lemma compact_choice_func (hc : compact (closed_ball 0 1 : set V))
{r : k} (hr : norm r > 0) :
∃ A : set V, A ⊆ (closed_ball 0 1 : set V) ∧ finite A ∧
∃ f : V → V, ∀ x : V, f x ∈ A ∧ (x ∈ (closed_ball 0 1 : set V)
→ x ∈ ball (f x) (1/norm r)) :=
begin
let B : set V := closed_ball 0 1,
have cover : B ⊆ ⋃ a ∈ B, ball a (1 / norm r),
{
intros x hx,
simp,
use x,
rw dist_self,
split,
simp at hx,
exact hx,
norm_num,
exact hr,
},
obtain ⟨A, A_sub, A_fin, HcoverA⟩ :
∃ A ⊆ B, finite A ∧ B ⊆ ⋃ a ∈ A, ball a (1/ norm r) :=
compact_elim_finite_subcover_image hc (by simp[is_open_ball]) cover,
-- need that A is non-empty to construct a choice function!
have x_in : (0 : V) ∈ B,
simp,
norm_num,
obtain ⟨a, a_in, ha⟩ : ∃ a ∈ A, dist (0 : V) a < 1/ norm r,
by simpa using HcoverA x_in,
have hfunc := cover_to_func A B HcoverA a a_in,
existsi A,
split,
exact A_sub,
split,
exact A_fin,
exact hfunc,
end
def aux_seq (v : V) (x : k) (f : V → V) : ℕ → V
| 0 := v
| (n + 1) := x • (aux_seq n - f (aux_seq n))
def partial_sum (f : ℕ → V) : ℕ → V
| 0 := f 0
| (n + 1) := f (n + 1) + partial_sum n
def approx_seq (v : V) (x : k) (f : V → V) : ℕ → V :=
partial_sum (λ n : ℕ, (1/x)^n • f(aux_seq v x f n))
-- if a sequence w n satisfies the bound |v - w n| < e^(n+1), where 0 < e < 1
-- then w n converges to v
lemma bound_power_convergence (w : ℕ → V) {v : V}
{x : k} (hx : norm x > 1)
(h : ∀ n : ℕ, norm (v - w n) ≤ (1 / norm x)^(n + 1)) :
filter.tendsto w filter.at_top (nhds v) :=
begin
have hlt1 : 1 / norm x < 1,
{
rw div_lt_one_iff_lt,
exact hx,
apply lt_trans zero_lt_one,
exact hx,
},
have hpos : 1 / norm x > 0,
{
norm_num,
apply lt_trans zero_lt_one,
exact hx,
},
have H : ∀ n : ℕ, norm (w n - v) ≤ (1 / norm x)^n,
intro n,
rw <- dist_eq_norm,
rw dist_comm,
rw dist_eq_norm,
apply le_trans,
exact h n,
rw pow_succ,
have h1 : (1 / norm x) * (1 / norm x)^n ≤ 1 * (1 / norm x)^n,
rw mul_le_mul_right,
rw le_iff_eq_or_lt,
right,
exact hlt1,
apply pow_pos,
exact hpos,
rw one_mul at h1,
exact h1,
rw tendsto_iff_norm_tendsto_zero,
apply squeeze_zero,
intro t,
exact norm_nonneg (w t - v),
exact H,
apply tendsto_pow_at_top_nhds_0_of_lt_1,
rw le_iff_eq_or_lt,
right,
exact hpos,
exact hlt1,
end
-- the approximation sequence (w n below) is contained in the span of A
-- this is true since by construction w n is a linear combination
-- of the elements in A
lemma approx_in_span (A : set V) (v : V) (x : k) (f : V → V)
(hf : ∀ x : V, f x ∈ A):
∀ n : ℕ, approx_seq v x f n ∈ submodule.span k A :=
begin
let w := approx_seq v x f,
have hw : w = approx_seq v x f,
refl,
intro n,
rw submodule.mem_span,
intros p hp,
induction n with n hn,
{
have h1 : w 0 = (1/x)^0 • f(v), refl,
simp at h1,
rw <- hw,
rw h1,
have h2 : f v ∈ A := hf v,
exact hp h2,
},{
have h1 : w (n+1) = (1/x)^(n+1) • f(aux_seq v x f (n+1)) + w(n),
refl,
rw <- hw,
rw h1,
have h2 := hp (hf (aux_seq v x f (n+1))),
have h3 := submodule.smul_mem p ((1/x)^(n+1)) h2,
apply submodule.add_mem p,
exact h3,
exact hn,
},
end
theorem compact_unit_ball_implies_finite_dim
(Hcomp : compact (closed_ball 0 1 : set V)) : finite_dimensional k V :=
begin
-- there is an x in k such that norm x > 1
have hbignum : ∃ x : k, x ≠ 0 ∧ norm x > 1,
exact nontrivial_norm_gt_one,
cases hbignum with x hx,
have hxpos : norm x > 0,
{
have h : (1:ℝ) > 0,
norm_num,
exact gt_trans hx.2 h,
},
-- use compactness to find a finite set A
-- and function f : V -> A such that for every
-- v in closed_ball 0 1, |f v - v| < 1/ norm x
obtain ⟨A, A_sub, A_fin, Hexistsf⟩ := compact_choice_func Hcomp hxpos,
obtain ⟨f, hf⟩ := Hexistsf,
-- suffices to show closed_ball 0 1 is spanned by A
apply finite_dimensional.of_fg,
rw submodule.fg_def,
existsi A,
split,
exact A_fin,
rw submodule.eq_top_iff',
apply ball_span,
-- let v in closed_ball 0 1 and show that it is in the span of A
-- to do so we construct a sequence w n such that
-- w n -> v and w n in span A for all n
-- for this we do a kind of 'dyadic approximation' of v using the set A
-- then we use that the span of a finite set is closed to conclude
intros v hv,
let u : ℕ → V := aux_seq v x f,
let w : ℕ → V := partial_sum (λ n : ℕ, (1/x)^n • f(u(n))),
-- show that w n is in the span of A
have hw : ∀ n, w n ∈ submodule.span k A,
{
have hf' : ∀ x : V, f x ∈ A,
intro x,
exact (hf x).1,
exact approx_in_span A v x f hf',
},
-- this is just some algebraic manipulation
have hdist : ∀ n : ℕ, v - w n = (1/x)^(n+1) • u (n+1),
{
intro n,
induction n with n hn,
{
have h1 : w 0 = (1/x)^0 • f(v), refl,
rw zero_add,
rw pow_one,
rw pow_zero at h1,
rw one_smul at h1,
rw h1,
have h2 : u 1 = x • (v - f(v)), refl,
rw h2,
rw smul_smul,
rw one_div_mul_cancel,
rw one_smul,
exact hx.1,
}, {
have h1 : w (n+1) = (1/x)^(n+1) • f(u (n+1)) + w(n), refl,
have h2 : u (n+2) = x • (u (n+1) - f (u (n+1))), refl,
rw h2,
rw pow_succ,
rw smul_smul,
rw mul_comm,
rw <- mul_assoc,
rw mul_one_div_cancel,
rw one_mul,
rw smul_sub,
rw <- hn,
rw h1,
rw add_comm _ (w n),
rw sub_sub v (w n) _,
exact hx.1,
},
},
-- main bound for convergence using the expression hdist
have hbound : ∀ n : ℕ, norm (v - w n) ≤ (1/norm x)^(n+1),
{
intro n,
rw hdist n,
rw norm_smul,
have hu : u(n+1) = x • (u(n) - f(u(n))), refl,
rw hu,
have husmall : norm (u n) ≤ 1,
{
induction n with n hn,
have h0 : u 0 = v, refl,
rw h0,
rw <- dist_zero_right,
exact hv,
have hu' : u(n + 1) = x • (u(n) - f(u(n))), refl,
rw hu',
have h2 := (hf (u n)).2,
rw norm_smul,
rw <- dist_eq_norm,
have h3 := hn hu',
rw <- dist_zero_right at h3,
have h4 : dist (u n) (f (u n)) < 1/ norm x,
exact h2 h3,
rw le_iff_eq_or_lt,
right,
rw <- mul_lt_mul_left hxpos at h4,
rw mul_one_div_cancel at h4,
exact h4,
exact mt (norm_eq_zero x).1 hx.1,
},
have h2 : 0 < (1/norm x),
norm_num,
exact hxpos,
have h1 : 0 < (1/ norm x)^(n+1),
exact pow_pos h2 (n+1),
have h3 : norm ((1/ x)^(n+1)) * norm (x • (u n - f(u n))) ≤ norm ((1/ x)^(n+1)) * 1 →
(1/norm x)^(n+1) * norm (x • (u n - f(u n))) ≤ (1/norm x)^(n+1),
intro h,
rw mul_one at h,
rw normed_field.norm_pow at h,
rw normed_field.norm_div at h,
rw normed_field.norm_one at h,
exact h,
rw normed_field.norm_pow,
rw normed_field.norm_div,
rw normed_field.norm_one,
apply h3,
rw normed_field.norm_pow,
rw normed_field.norm_div,
rw normed_field.norm_one,
rw mul_le_mul_left h1,
rw norm_smul,
rw <- dist_zero_right at husmall,
have h4 := (hf (u n)).2 husmall,
rw <- dist_eq_norm,
rw <- mul_le_mul_left h2,
rw <- mul_assoc,
rw mul_one,
rw one_div_mul_cancel,
rw one_mul,
rw le_iff_eq_or_lt,
right,
exact h4,
exact mt (norm_eq_zero x).1 hx.1,
},
-- w n -> v as n -> infty
have hlim : filter.tendsto w filter.at_top (nhds v : filter V)
:= bound_power_convergence w hx.2 hbound,
-- the span of a finite set is (sequentially) closed
let S : set V := ↑(submodule.span k A),
have hspan_closed : is_seq_closed S := finite_span_seq_closed A A_fin,
have hw' : ∀ n, w n ∈ S,
exact hw,
-- since S is closed, the limit v of w n is in S, as required.
have hinS: v ∈ S,
exact mem_of_is_seq_closed hspan_closed hw' hlim,
exact hinS,
end
|
Contemporary critics of Keats enjoyed the poem , and it was heavily quoted in their reviews . An anonymous review of Keats 's poetry that ran in the August and October 1820 Scots Magazine stated : " Amongst the minor poems we prefer the ' Ode to the Nightingale . ' Indeed , we are inclined to prefer it beyond every other poem in the book ; but let the reader judge . The third and seventh stanzas have a charm for us which we should find it difficult to explain . We have read this ode over and over again , and every time with increased delight . " At the same time , Leigh Hunt wrote a review of Keats 's poem for the 2 August and 9 August 1820 The Indicator : " As a specimen of the Poems , which are all lyrical , we must indulge ourselves in quoting entire the ' Ode to a Nightingale ' . There is that mixture in it of real melancholy and imaginative relief , which poetry alone presents us in her ' charmed cup , ' and which some over @-@ rational critics have undertaken to find wrong because it is not true . It does not follow that what is not true to them , is not true to others . If the relief is real , the mixture is good and sufficing . "
|
import numpy as np
import glob
f = glob.glob('/')
print(f)
# get all .npz files in the folder 'training data'
training_data = glob.glob('training_data/*.npz')
X = np.zeros((1, 38400))
y = np.zeros((1, 3), 'float')
print("input_data_path: ", training_data)
for input_file in training_data:
with np.load(input_file) as data:
X_temp = data['train']
y_temp = data['train_label']
X = np.vstack((X, X_temp))
y = np.vstack((y, y_temp))
# Get rid of the first rows in both matrices that only contain zeros
X = X[1:, :]
y = y[1:, :]
print(X)
print(" |||")
print(y)
|
data InfIO : Type where
Do : IO a
-> (a -> Inf InfIO)
-> InfIO
{-loopPrint : String -> InfIO
loopPrint msg = Do (putStrLn msg)
(\_ => loopPrint msg)-}
{-run : InfIO -> IO ()
run (Do action cont) = do res <- action
run (cont res)-}
{-data Fuel = Dry | More Fuel-}
data Fuel = Dry | More (Lazy Fuel)
forever : Fuel
forever = More forever
tank : Nat -> Fuel
tank Z = Dry
tank (S k) = More (tank k)
run : Fuel -> InfIO -> IO ()
run Dry y = putStrLn "Out of fuel"
run (More fuel) (Do c f) = do res <- c
run fuel (f res)
(>>=) : IO a -> (a -> Inf InfIO) -> InfIO
(>>=) = Do
loopPrint : String -> InfIO
loopPrint msg = do putStrLn msg
loopPrint msg
|
{-# OPTIONS --without-K --safe #-}
module Categories.Functor.Instance.StrictCore where
-- The 'strict' core functor (from StrictCats to StrictGroupoids).
-- This is the right-adjoint of the forgetful functor from
-- StrictGroupoids to StrictCats
-- (see Categories.Functor.Adjoint.Instance.StrictCore)
open import Data.Product
open import Level using (_⊔_)
open import Function using (_on_; _$_) renaming (id to idf)
open import Relation.Binary.PropositionalEquality as ≡ using (cong; cong-id)
open import Categories.Category
import Categories.Category.Construction.Core as C
open import Categories.Category.Instance.StrictCats
open import Categories.Category.Instance.StrictGroupoids
open import Categories.Functor
open import Categories.Functor.Equivalence
open import Categories.Functor.Instance.Core renaming (Core to WeakCore)
open import Categories.Functor.Properties using ([_]-resp-≅)
import Categories.Morphism as Morphism
import Categories.Morphism.Reasoning as MR
import Categories.Morphism.HeterogeneousIdentity as HId
import Categories.Morphism.HeterogeneousIdentity.Properties as HIdProps
open import Categories.Morphism.IsoEquiv using (⌞_⌟)
Core : ∀ {o ℓ e} → Functor (Cats o ℓ e) (Groupoids o (ℓ ⊔ e) e)
Core {o} {ℓ} {e} = record
{ F₀ = F₀
; F₁ = F₁
; identity = λ {A} →
record { eq₀ = λ _ → ≡.refl ; eq₁ = λ _ → ⌞ MR.id-comm-sym A ⌟ }
; homomorphism = λ {A B C} →
record { eq₀ = λ _ → ≡.refl ; eq₁ = λ _ → ⌞ MR.id-comm-sym C ⌟ }
; F-resp-≈ = λ {A B F G} → CoreRespFEq {A} {B} {F} {G}
}
where
open Functor WeakCore
CoreRespFEq : {A B : Category o ℓ e} {F G : Functor A B} →
F ≡F G → F₁ F ≡F F₁ G
CoreRespFEq {A} {B} {F} {G} F≡G = record
{ eq₀ = eq₀
; eq₁ = λ {X} {Y} f → ⌞ begin
(from $ hid BC $ eq₀ Y) ∘ F.F₁ (from f)
≈⟨ ∘-resp-≈ˡ (hid-identity BC B from Equiv.refl (eq₀ Y)) ⟩
(hid B $ ≡.cong idf $ eq₀ Y) ∘ F.F₁ (from f)
≡⟨ cong (λ p → hid B p ∘ _) (cong-id (eq₀ Y)) ⟩
hid B (eq₀ Y) ∘ F.F₁ (from f)
≈⟨ eq₁ (from f) ⟩
G.F₁ (from f) ∘ hid B (eq₀ X)
≡˘⟨ cong (λ p → _ ∘ hid B p) (cong-id (eq₀ X)) ⟩
G.F₁ (from f) ∘ (hid B $ cong idf $ eq₀ X)
≈˘⟨ ∘-resp-≈ʳ (hid-identity BC B from Equiv.refl (eq₀ X)) ⟩
G.F₁ (from f) ∘ (from $ hid BC $ eq₀ X)
∎ ⌟
}
where
BC = C.Core B
module F = Functor F
module G = Functor G
open Category B
open HomReasoning hiding (refl)
open HId
open HIdProps
open _≡F_ F≡G
open Morphism._≅_
|
###########################################################################
#CoxRegression
#This will load our input files into variables so we can run the cox regression.
###########################################################################
LineGraph.loader <- function(
input.filename,
output.file="LineGraph",
graphType=""
)
{
######################################################
#We need this package for a str_extract when we take text out of the concept.
library(stringr)
library(plyr)
library(ggplot2)
library(Cairo)
######################################################
######################################################
#Read the line graph data.
line.data<-read.delim(input.filename,header=T)
#We need to convert the value column from a factor to a numeric.
#finalData$VALUE <- as.numeric(levels(finalData$VALUE))[as.integer(finalData$VALUE)]
#Aggregate the data to get rid of patient numbers. We add a standard error column so we can use it in the error bars.
dataOutput <- ddply(line.data, .(CONCEPT_PATH,GROUP_VAR),
summarise,
MEAN = mean(VALUE),
SD = sd(VALUE),
SE = sd(VALUE)/sqrt(length(VALUE)),
MEDIAN = median(VALUE)
)
#Adjust the column names.
colnames(dataOutput) <- c('TIMEPOINT','GROUP','MEAN','SD','SE','MEDIAN')
#Use a regular expression trim out the timepoint from the concept.
#dataOutput$TIMEPOINT <- str_extract(dataOutput$TIMEPOINT,"Week [0-9]+")
dataOutput$TIMEPOINT <- str_extract(dataOutput$TIMEPOINT,"(\\\\.+\\\\.+\\\\)+?$")
#Convert the timepoint field to a factor.
dataOutput$TIMEPOINT <- factor(dataOutput$TIMEPOINT)
#Convert the group field to a factor.
dataOutput$GROUP <- factor(dataOutput$GROUP)
######################################################
######################################################
#Plotting the line.
#Depending on the graph type, we create a different graph.
if(graphType=="MERR")
{
limits <- aes(ymax = MEAN + SE, ymin = MEAN - SE)
p <- ggplot(
data=dataOutput,
aes(x=TIMEPOINT,
y=MEAN,
group=GROUP,
colour=GROUP
)
)
}
if(graphType=="MSTD")
{
limits <- aes(ymax = MEAN + SD, ymin = MEAN - SD)
p <- ggplot(
data=dataOutput,
aes(x=TIMEPOINT,
y=MEAN,
group=GROUP,
colour=GROUP
)
)
}
if(graphType=="MEDER")
{
limits <- aes(ymax = MEDIAN + SE, ymin = MEDIAN - SE)
p <- ggplot(
data=dataOutput,
aes(x=TIMEPOINT,
y=MEDIAN,
group=GROUP,
colour=GROUP
)
)
}
p <- p + geom_line(size=1.5) + geom_errorbar(limits,width=0.2) + scale_colour_brewer()
#This sets the color theme of the background/grid.
p <- p + theme_bw();
#Set the text options for the axis.
p <- p + theme(axis.text.x = theme_text(size = 17,face="bold",angle=5));
p <- p + theme(axis.text.y = theme_text(size = 17,face="bold"));
#Set the text options for the title.
p <- p + theme(axis.title.x = theme_text(vjust = -.5,size = 20,face="bold"));
p <- p + theme(axis.title.y = theme_text(vjust = .35,size = 20,face="bold",angle=90));
#Set the legend attributes.
p <- p + theme(legend.title = theme_text(size = 20,face="bold"));
p <- p + theme(legend.text = theme_text(size = 15,face="bold"));
p <- p + theme(legend.title=theme_blank())
p <- p + geom_point(size=4);
#This is the name of the output image file.
imageFileName <- paste(output.file,".png",sep="")
#This initializes our image capture object.
CairoPNG(file=imageFileName, width=1200, height=600,units = "px")
#Printing actually puts the plot in the image.
print(p)
#Turn of the graphics device to save the image.
dev.off()
######################################################
}
|
State Before: ι : Type u_1
𝕜 : Type u_2
inst✝⁴ : IsROrC 𝕜
E : Type u_3
inst✝³ : NormedAddCommGroup E
inst✝² : InnerProductSpace 𝕜 E
cplt : CompleteSpace E
G : ι → Type u_4
inst✝¹ : (i : ι) → NormedAddCommGroup (G i)
inst✝ : (i : ι) → InnerProductSpace 𝕜 (G i)
V : (i : ι) → G i →ₗᵢ[𝕜] E
F : ι → Submodule 𝕜 E
hV : IsHilbertSum 𝕜 G V
i : ι
x : G i
⊢ ↑(LinearIsometryEquiv.symm (linearIsometryEquiv hV)) (lp.single 2 i x) = ↑(V i) x State After: no goals Tactic: simp [IsHilbertSum.linearIsometryEquiv, OrthogonalFamily.linearIsometry_apply_single] |
% Converts a frequency to some scale and back again
%
% Copyright (c) 2018 Department of Computer Science,
% University of Toronto, Canada,
% Vector Institute, Canada
%
% License
% This file is under the LGPL license, you can
% redistribute it and/or modify it under the terms of the GNU Lesser General
% Public License as published by the Free Software Foundation, either version 3
% of the License, or (at your option) any later version. This file 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 Lesser General Public License for more
% details.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Author
% Yingxue Wang <[email protected]>
% Sean Robertson <[email protected]>
%
classdef ScalingFunction < handle
methods (Abstract)
scale_to_hertz(obj, scale)
hertz_to_scale(obj, hertz)
end
end |
Require Import Coq.Lists.List.
(* there are some things to keep in mind when programming in Ltac
Variable names must be prefixed by a '?'
Ltac length ls := (* does not work *)
match ls with
| nil => O
| _ :: ls' => S (length ls')
end.
*)
(* constructors must be prefixed by 'constr:' *)
Ltac length ls := (* does not work *)
match ls with
| nil => O
| (_ :: ?ls') => constr:(S (length ls')) (* this is the Gallina length not recursion *)
end.
(* the pose tactic extends the proof context with a new variable that is set
equal to a particular term, could have also have used idtac n to print the
result without changing the context*)
Goal False.
let n := eval simpl in (length ( 1 :: 2 :: 3 :: nil)) in (* only unrolls once *)
pose n. Abort.
Reset length.
Ltac length ls :=
match ls with
| nil => O
| _ :: ?ls' =>
let ls'' := length ls' in
constr:(S ls'')
end.
(* weird way you have to test Ltac functions *)
Goal False.
let n := length ( 1 :: 2 :: 3 :: nil ) in
pose n.
Abort.
(*
Ltac map T f :=
let rec map' ls :=
match ls with
| nil => constr:(@nil T)
| ?x :: ?ls' =>
let x' := f x in
let ls'' := map' ls' in
constr:(x' :: ls'')
end in
map'.
*)
(*
context[ ] search for a subterm
used in a match statement *)
Ltac map f :=
match goal with
| [H : _ |- _ ] => f H
end.
Goal False.
let ls := map (nat * nat)%type ltac:(fun x => constr:((x,x))) (1 :: 2 :: 3 :: nil)
in
pose ls.
Abort.
Reset length.
(* use of a continuation allows side effects *)
(* this program prints each one step eval *)
Ltac length ls k :=
idtac ls;
match ls with
| nil => k O
| _ :: ?ls' => length ls' ltac:(fun n => k (S n))
end.
Goal False.
length (1 :: 2 :: 3 :: nil) ltac:(fun n => pose n).
Abort.
Ltac le_S_star := apply le_n || (apply le_S; le_S_star).
Section RecursiveLtac.
Theorem le_5_25 : 5 <= 25.
Proof.
le_S_star.
Qed.
End RecursiveLtac.
Section Primes.
Definition divides (n m : nat) := exists p : nat, p * n = m.
Hypotheses
(divides_0 : forall n : nat, divides n 0)
(divides_plus : forall n m : nat, divides n m -> divides n (n + m))
(not_divides_plus : forall n m : nat, ~ divides n m -> ~divides n (n+m))
(not_divides_lt : forall n m : nat, 0 < m -> m < n -> ~ divides n m)
(not_lt_2_divides : forall n m : nat, n <> 1 -> n < 2 -> 0 < m -> ~divides n m)
(le_plus_minus : forall n m : nat, le n m -> m = n + (m - n))
(lt_lt_or_eq : forall n m : nat, n < S m -> n < m \/ n = m).
Ltac check_not_divides :=
match goal with
| [ |- (~divides ?X1 ?X2) ] =>
cut (X1 <= X2); [ idtac | le_S_star ]; intros Hle;
rewrite (le_plus_minus _ _ Hle); apply not_divides_plus;
simpl; clear Hle; check_not_divides
| [ |- _ ] => apply not_divides_lt; unfold lt; le_S_star
end.
Theorem three_div_six : ~(divides 7 12).
Proof. check_not_divides. Qed.
Print three_div_six.
End Primes.
Section section_for_cut_example.
Variable P Q R T : Prop.
Hypotheses (H : P -> Q)
(H0 : Q -> R)
(H1 : (P -> R) -> T -> Q)
(H2 : (P -> R) -> T).
Theorem cut_example : Q.
Proof.
cut (P -> R). intro H3. apply H1; [ assumption | apply H2; assumption].
intro. apply H0. apply H. assumption. Qed.
Print cut_example.
Theorem cut_example' : Q.
Proof. apply H1 in H2; [apply H2 | |];
intros H3; apply H in H3; apply H0; apply H3. Qed.
Print cut_example'.
End section_for_cut_example. |
enthal <- function(tdb, w) {
.Call('biometeoR_enthal', PACKAGE = 'biometeoR', tdb, w)
}
|
-- |
-- Module : Southpaw.Picasso.Shapes
-- Description : Various functions for creating mathematical shapes
-- Copyright : (c) Jonatan H Sundqvist, year
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created date year
-- TODO | -
-- -
-- SPEC | -
-- -
---------------------------------------------------------------------------------------------------
-- API
---------------------------------------------------------------------------------------------------
module Southpaw.Picasso.Shapes where
---------------------------------------------------------------------------------------------------
-- We'll need these
---------------------------------------------------------------------------------------------------
import Data.Complex
import Southpaw.Math.Constants
---------------------------------------------------------------------------------------------------
-- Function
---------------------------------------------------------------------------------------------------
-- Geometry ---------------------------------------------------------------------------------------
-- |
-- TODO: Start angle
-- TODO: Invalid arguments (eg. sides < 3) (use Maybe?)
-- TODO: Make polymorphic
-- TODO: Move to geometry section
-- polygon :: (Floating f, RealFloat f) => Int -> f -> Complex f -> [Complex f]
polygon :: Integral int => int -> Double -> Complex Double -> [Complex Double]
polygon sides radius origin = [ let θ = arg n in origin + ((radius * cos θ):+(radius * sin θ)) | n <- [1..sides]]
where arg n = fromIntegral n * (2*π)/fromIntegral sides
-- |
-- TODO: Simplify and expound comments
arrow :: Complex Double -> Complex Double -> Double -> Double -> Double -> [Complex Double]
arrow from to sl sw hw = [from + straight (sw/2), --
shaftEnd + straight (sw/2), --
shaftEnd + straight (hw/2), --
to, --
shaftEnd - straight (hw/2), --
shaftEnd - straight (sw/2), --
from - straight (sw/2)] --
where along a b distance = (a +) . mkPolar distance . snd . polar $ b-a -- Walk distance along the from a to b
normal a b = let (mag, arg) = polar (b-a) in mkPolar mag (arg+π/2)
shaftEnd = along from to sl --
straight = along (0:+0) (normal from to) -- Vector perpendicular to the centre line
|
section \<open>Connecting Nondeterministic Generalized Büchi Automata to CAVA Automata Structures\<close>
theory NGBA_Graphs
imports
NGBA
CAVA_Automata.Automata_Impl
begin
no_notation build (infixr "##" 65)
subsection \<open>Regular Graphs\<close>
definition ngba_g :: "('label, 'state) ngba \<Rightarrow> 'state graph_rec" where
"ngba_g A \<equiv> \<lparr> g_V = UNIV, g_E = E_of_succ (successors A), g_V0 = initial A \<rparr>"
lemma ngba_g_graph[simp]: "graph (ngba_g A)" unfolding ngba_g_def graph_def by simp
lemma ngba_g_V0: "g_V0 (ngba_g A) = initial A" unfolding ngba_g_def by simp
lemma ngba_g_E_rtrancl: "(g_E (ngba_g A))\<^sup>* = {(p, q). q \<in> reachable A p}"
unfolding ngba_g_def graph_rec.simps E_of_succ_def
proof safe
show "(p, q) \<in> {(p, q). q \<in> successors A p}\<^sup>*" if "q \<in> reachable A p" for p q
using that by (induct) (auto intro: rtrancl_into_rtrancl)
show "q \<in> reachable A p" if "(p, q) \<in> {(p, q). q \<in> successors A p}\<^sup>*" for p q
using that by induct auto
qed
lemma ngba_g_rtrancl_path: "(g_E (ngba_g A))\<^sup>* = {(p, target r p) |r p. NGBA.path A r p}"
unfolding ngba_g_E_rtrancl by blast
lemma ngba_g_trancl_path: "(g_E (ngba_g A))\<^sup>+ = {(p, target r p) |r p. NGBA.path A r p \<and> r \<noteq> []}"
unfolding ngba_g_def graph_rec.simps E_of_succ_def
proof safe
show "\<exists> r p. (x, y) = (p, target r p) \<and> NGBA.path A r p \<and> r \<noteq> []"
if "(x, y) \<in> {(p, q). q \<in> successors A p}\<^sup>+" for x y
using that
proof induct
case (base y)
obtain a where 1: "a \<in> alphabet A" "y \<in> transition A a x" using base by auto
show ?case
proof (intro exI conjI)
show "(x, y) = (x, target [(a, y)] x)" by simp
show "NGBA.path A [(a, y)] x" using 1 by auto
show "[(a, y)] \<noteq> []" by simp
qed
next
case (step y z)
obtain r where 1: "y = target r x" "NGBA.path A r x" "r \<noteq> []" using step(3) by auto
obtain a where 2: "a \<in> alphabet A" "z \<in> transition A a y" using step(2) by auto
show ?case
proof (intro exI conjI)
show "(x, z) = (x, target (r @ [(a, z)]) x)" by simp
show "NGBA.path A (r @ [(a, z)]) x" using 1 2 by auto
show "r @ [(a, z)] \<noteq> []" by simp
qed
qed
show "(p, target r p) \<in> {(u, v). v \<in> successors A u}\<^sup>+" if "NGBA.path A r p" "r \<noteq> []" for r p
using that by (induct) (fastforce intro: trancl_into_trancl2)+
qed
lemma ngba_g_ipath_run:
assumes "ipath (g_E (ngba_g A)) r"
obtains w
where "run A (w ||| smap (r \<circ> Suc) nats) (r 0)"
proof -
have 1: "\<exists> a \<in> alphabet A. r (Suc i) \<in> transition A a (r i)" for i
using assms unfolding ipath_def ngba_g_def E_of_succ_def by auto
obtain wr where 2: "run A wr (r 0)" "\<And> i. target (stake i wr) (r 0) = r i"
proof (rule ngba.invariant_run_index)
show "\<exists> aq. (fst aq \<in> alphabet A \<and> snd aq \<in> transition A (fst aq) p) \<and> snd aq = r (Suc i) \<and> True"
if "p = r i" for i p using that 1 by auto
show "r 0 = r 0" by rule
qed auto
have 3: "smap (r \<circ> Suc) nats = smap snd wr"
proof (rule eqI_snth)
fix i
have "smap (r \<circ> Suc) nats !! i = r (Suc i)" by simp
also have "\<dots> = target (stake (Suc i) wr) (r 0)" unfolding 2(2) by rule
also have "\<dots> = (r 0 ## trace wr (r 0)) !! Suc i" by simp
also have "\<dots> = smap snd wr !! i" unfolding ngba.trace_alt_def by simp
finally show "smap (r \<circ> Suc) nats !! i = smap snd wr !! i" by this
qed
show ?thesis
proof
show "run A (smap fst wr ||| smap (r \<circ> Suc) nats) (r 0)" using 2(1) unfolding 3 by auto
qed
qed
lemma ngba_g_run_ipath:
assumes "run A (w ||| r) p"
shows "ipath (g_E (ngba_g A)) (snth (p ## r))"
proof
fix i
have 1: "w !! i \<in> alphabet A" "r !! i \<in> transition A (w !! i) (target (stake i (w ||| r)) p)"
using assms by (auto dest: ngba.run_snth)
have 2: "r !! i \<in> successors A ((p ## r) !! i)"
using 1 unfolding sscan_scons_snth[symmetric] ngba.trace_alt_def by auto
show "((p ## r) !! i, (p ## r) !! Suc i) \<in> g_E (ngba_g A)"
using 2 unfolding ngba_g_def graph_rec.simps E_of_succ_def by simp
qed
subsection \<open>Indexed Generalized Büchi Graphs\<close>
definition ngba_acc :: "'state pred gen \<Rightarrow> 'state \<Rightarrow> nat set" where
"ngba_acc cs p \<equiv> {k \<in> {0 ..< length cs}. (cs ! k) p}"
lemma ngba_acc_param[param]: "(ngba_acc, ngba_acc) \<in> \<langle>S \<rightarrow> bool_rel\<rangle> list_rel \<rightarrow> S \<rightarrow> \<langle>nat_rel\<rangle> set_rel"
unfolding ngba_acc_def list_rel_def list_all2_conv_all_nth fun_rel_def by auto
definition ngba_igbg :: "('label, 'state) ngba \<Rightarrow> 'state igb_graph_rec" where
"ngba_igbg A \<equiv> graph_rec.extend (ngba_g A) \<lparr> igbg_num_acc = length (accepting A), igbg_acc = ngba_acc (accepting A) \<rparr>"
lemma acc_run_language:
assumes "igb_graph (ngba_igbg A)"
shows "Ex (igb_graph.is_acc_run (ngba_igbg A)) \<longleftrightarrow> language A \<noteq> {}"
proof
interpret igb_graph "ngba_igbg A" using assms by this
have [simp]: "V0 = g_V0 (ngba_g A)" "E = g_E (ngba_g A)" "num_acc = length (accepting A)"
"k \<in> acc p \<longleftrightarrow> k < length (accepting A) \<and> (accepting A ! k) p" for p k
unfolding ngba_igbg_def ngba_acc_def graph_rec.defs by simp+
show "language A \<noteq> {}" if run: "Ex is_acc_run"
proof -
obtain r where 1: "is_acc_run r" using run by rule
have 2: "r 0 \<in> V0" "ipath E r" "is_acc r"
using 1 unfolding is_acc_run_def graph_defs.is_run_def by auto
obtain w where 3: "run A (w ||| smap (r \<circ> Suc) nats) (r 0)" using ngba_g_ipath_run 2(2) by auto
have 4: "r 0 ## smap (r \<circ> Suc) nats = smap r nats" by (simp) (metis stream.map_comp smap_siterate)
have 5: "infs (accepting A ! k) (r 0 ## smap (r \<circ> Suc) nats)" if "k < length (accepting A)" for k
using 2(3) that unfolding infs_infm is_acc_def 4 by simp
have "w \<in> language A"
proof
show "r 0 \<in> initial A" using ngba_g_V0 2(1) by force
show "run A (w ||| smap (r \<circ> Suc) nats) (r 0)" using 3 by this
show "gen infs (accepting A) (r 0 ## smap (r \<circ> Suc) nats)"
unfolding gen_def all_set_conv_all_nth using 5 by simp
qed
then show ?thesis by auto
qed
show "Ex is_acc_run" if language: "language A \<noteq> {}"
proof -
obtain w where 1: "w \<in> language A" using language by auto
obtain r p where 2: "p \<in> initial A" "run A (w ||| r) p" "gen infs (accepting A) (p ## r)" using 1 by rule
have "is_acc_run (snth (p ## r))"
unfolding is_acc_run_def graph_defs.is_run_def
proof safe
show "(p ## r) !! 0 \<in> V0" using ngba_g_V0 2(1) by force
show "ipath E (snth (p ## r))" using ngba_g_run_ipath 2(2) by force
show "is_acc (snth (p ## r))" using 2(3) unfolding gen_def infs_infm is_acc_def by simp
qed
then show ?thesis by auto
qed
qed
end |
(* Title: ZF/Perm.thy
Author: Lawrence C Paulson, Cambridge University Computer Laboratory
Copyright 1991 University of Cambridge
The theory underlying permutation groups
-- Composition of relations, the identity relation
-- Injections, surjections, bijections
-- Lemmas for the Schroeder-Bernstein Theorem
*)
section\<open>Injections, Surjections, Bijections, Composition\<close>
theory Perm imports func begin
definition
(*composition of relations and functions; NOT Suppes's relative product*)
comp :: "[i,i]=>i" (infixr \<open>O\<close> 60) where
"r O s == {xz \<in> domain(s)*range(r) .
\<exists>x y z. xz=<x,z> & <x,y>:s & <y,z>:r}"
definition
(*the identity function for A*)
id :: "i=>i" where
"id(A) == (\<lambda>x\<in>A. x)"
definition
(*one-to-one functions from A to B*)
inj :: "[i,i]=>i" where
"inj(A,B) == { f \<in> A->B. \<forall>w\<in>A. \<forall>x\<in>A. f`w=f`x \<longrightarrow> w=x}"
definition
(*onto functions from A to B*)
surj :: "[i,i]=>i" where
"surj(A,B) == { f \<in> A->B . \<forall>y\<in>B. \<exists>x\<in>A. f`x=y}"
definition
(*one-to-one and onto functions*)
bij :: "[i,i]=>i" where
"bij(A,B) == inj(A,B) \<inter> surj(A,B)"
subsection\<open>Surjective Function Space\<close>
lemma surj_is_fun: "f \<in> surj(A,B) ==> f \<in> A->B"
apply (unfold surj_def)
apply (erule CollectD1)
done
lemma fun_is_surj: "f \<in> Pi(A,B) ==> f \<in> surj(A,range(f))"
apply (unfold surj_def)
apply (blast intro: apply_equality range_of_fun domain_type)
done
lemma surj_range: "f \<in> surj(A,B) ==> range(f)=B"
apply (unfold surj_def)
apply (best intro: apply_Pair elim: range_type)
done
text\<open>A function with a right inverse is a surjection\<close>
lemma f_imp_surjective:
"[| f \<in> A->B; !!y. y \<in> B ==> d(y): A; !!y. y \<in> B ==> f`d(y) = y |]
==> f \<in> surj(A,B)"
by (simp add: surj_def, blast)
lemma lam_surjective:
"[| !!x. x \<in> A ==> c(x): B;
!!y. y \<in> B ==> d(y): A;
!!y. y \<in> B ==> c(d(y)) = y
|] ==> (\<lambda>x\<in>A. c(x)) \<in> surj(A,B)"
apply (rule_tac d = d in f_imp_surjective)
apply (simp_all add: lam_type)
done
text\<open>Cantor's theorem revisited\<close>
lemma cantor_surj: "f \<notin> surj(A,Pow(A))"
apply (unfold surj_def, safe)
apply (cut_tac cantor)
apply (best del: subsetI)
done
subsection\<open>Injective Function Space\<close>
lemma inj_is_fun: "f \<in> inj(A,B) ==> f \<in> A->B"
apply (unfold inj_def)
apply (erule CollectD1)
done
text\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\<close>
lemma inj_equality:
"[| <a,b>:f; <c,b>:f; f \<in> inj(A,B) |] ==> a=c"
apply (unfold inj_def)
apply (blast dest: Pair_mem_PiD)
done
lemma inj_apply_equality: "[| f \<in> inj(A,B); f`a=f`b; a \<in> A; b \<in> A |] ==> a=b"
by (unfold inj_def, blast)
text\<open>A function with a left inverse is an injection\<close>
lemma f_imp_injective: "[| f \<in> A->B; \<forall>x\<in>A. d(f`x)=x |] ==> f \<in> inj(A,B)"
apply (simp (no_asm_simp) add: inj_def)
apply (blast intro: subst_context [THEN box_equals])
done
lemma lam_injective:
"[| !!x. x \<in> A ==> c(x): B;
!!x. x \<in> A ==> d(c(x)) = x |]
==> (\<lambda>x\<in>A. c(x)) \<in> inj(A,B)"
apply (rule_tac d = d in f_imp_injective)
apply (simp_all add: lam_type)
done
subsection\<open>Bijections\<close>
lemma bij_is_inj: "f \<in> bij(A,B) ==> f \<in> inj(A,B)"
apply (unfold bij_def)
apply (erule IntD1)
done
lemma bij_is_surj: "f \<in> bij(A,B) ==> f \<in> surj(A,B)"
apply (unfold bij_def)
apply (erule IntD2)
done
lemma bij_is_fun: "f \<in> bij(A,B) ==> f \<in> A->B"
by (rule bij_is_inj [THEN inj_is_fun])
lemma lam_bijective:
"[| !!x. x \<in> A ==> c(x): B;
!!y. y \<in> B ==> d(y): A;
!!x. x \<in> A ==> d(c(x)) = x;
!!y. y \<in> B ==> c(d(y)) = y
|] ==> (\<lambda>x\<in>A. c(x)) \<in> bij(A,B)"
apply (unfold bij_def)
apply (blast intro!: lam_injective lam_surjective)
done
lemma RepFun_bijective: "(\<forall>y\<in>x. \<exists>!y'. f(y') = f(y))
==> (\<lambda>z\<in>{f(y). y \<in> x}. THE y. f(y) = z) \<in> bij({f(y). y \<in> x}, x)"
apply (rule_tac d = f in lam_bijective)
apply (auto simp add: the_equality2)
done
subsection\<open>Identity Function\<close>
lemma idI [intro!]: "a \<in> A ==> <a,a> \<in> id(A)"
apply (unfold id_def)
apply (erule lamI)
done
lemma idE [elim!]: "[| p \<in> id(A); !!x.[| x \<in> A; p=<x,x> |] ==> P |] ==> P"
by (simp add: id_def lam_def, blast)
lemma id_type: "id(A) \<in> A->A"
apply (unfold id_def)
apply (rule lam_type, assumption)
done
lemma id_conv [simp]: "x \<in> A ==> id(A)`x = x"
apply (unfold id_def)
apply (simp (no_asm_simp))
done
lemma id_mono: "A<=B ==> id(A) \<subseteq> id(B)"
apply (unfold id_def)
apply (erule lam_mono)
done
lemma id_subset_inj: "A<=B ==> id(A): inj(A,B)"
apply (simp add: inj_def id_def)
apply (blast intro: lam_type)
done
lemmas id_inj = subset_refl [THEN id_subset_inj]
lemma id_surj: "id(A): surj(A,A)"
apply (unfold id_def surj_def)
apply (simp (no_asm_simp))
done
lemma id_bij: "id(A): bij(A,A)"
apply (unfold bij_def)
apply (blast intro: id_inj id_surj)
done
lemma subset_iff_id: "A \<subseteq> B \<longleftrightarrow> id(A) \<in> A->B"
apply (unfold id_def)
apply (force intro!: lam_type dest: apply_type)
done
text\<open>\<^term>\<open>id\<close> as the identity relation\<close>
lemma id_iff [simp]: "<x,y> \<in> id(A) \<longleftrightarrow> x=y & y \<in> A"
by auto
subsection\<open>Converse of a Function\<close>
lemma inj_converse_fun: "f \<in> inj(A,B) ==> converse(f) \<in> range(f)->A"
apply (unfold inj_def)
apply (simp (no_asm_simp) add: Pi_iff function_def)
apply (erule CollectE)
apply (simp (no_asm_simp) add: apply_iff)
apply (blast dest: fun_is_rel)
done
text\<open>Equations for converse(f)\<close>
text\<open>The premises are equivalent to saying that f is injective...\<close>
lemma left_inverse_lemma:
"[| f \<in> A->B; converse(f): C->A; a \<in> A |] ==> converse(f)`(f`a) = a"
by (blast intro: apply_Pair apply_equality converseI)
lemma left_inverse [simp]: "[| f \<in> inj(A,B); a \<in> A |] ==> converse(f)`(f`a) = a"
by (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)
lemma left_inverse_eq:
"[|f \<in> inj(A,B); f ` x = y; x \<in> A|] ==> converse(f) ` y = x"
by auto
lemmas left_inverse_bij = bij_is_inj [THEN left_inverse]
lemma right_inverse_lemma:
"[| f \<in> A->B; converse(f): C->A; b \<in> C |] ==> f`(converse(f)`b) = b"
by (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)
(*Should the premises be f \<in> surj(A,B), b \<in> B for symmetry with left_inverse?
No: they would not imply that converse(f) was a function! *)
lemma right_inverse [simp]:
"[| f \<in> inj(A,B); b \<in> range(f) |] ==> f`(converse(f)`b) = b"
by (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)
lemma right_inverse_bij: "[| f \<in> bij(A,B); b \<in> B |] ==> f`(converse(f)`b) = b"
by (force simp add: bij_def surj_range)
subsection\<open>Converses of Injections, Surjections, Bijections\<close>
lemma inj_converse_inj: "f \<in> inj(A,B) ==> converse(f): inj(range(f), A)"
apply (rule f_imp_injective)
apply (erule inj_converse_fun, clarify)
apply (rule right_inverse)
apply assumption
apply blast
done
lemma inj_converse_surj: "f \<in> inj(A,B) ==> converse(f): surj(range(f), A)"
by (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun
range_of_fun [THEN apply_type])
text\<open>Adding this as an intro! rule seems to cause looping\<close>
lemma bij_converse_bij [TC]: "f \<in> bij(A,B) ==> converse(f): bij(B,A)"
apply (unfold bij_def)
apply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)
done
subsection\<open>Composition of Two Relations\<close>
text\<open>The inductive definition package could derive these theorems for \<^term>\<open>r O s\<close>\<close>
lemma compI [intro]: "[| <a,b>:s; <b,c>:r |] ==> <a,c> \<in> r O s"
by (unfold comp_def, blast)
lemma compE [elim!]:
"[| xz \<in> r O s;
!!x y z. [| xz=<x,z>; <x,y>:s; <y,z>:r |] ==> P |]
==> P"
by (unfold comp_def, blast)
lemma compEpair:
"[| <a,c> \<in> r O s;
!!y. [| <a,y>:s; <y,c>:r |] ==> P |]
==> P"
by (erule compE, simp)
lemma converse_comp: "converse(R O S) = converse(S) O converse(R)"
by blast
subsection\<open>Domain and Range -- see Suppes, Section 3.1\<close>
text\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\<close>
lemma range_comp: "range(r O s) \<subseteq> range(r)"
by blast
lemma range_comp_eq: "domain(r) \<subseteq> range(s) ==> range(r O s) = range(r)"
by (rule range_comp [THEN equalityI], blast)
lemma domain_comp: "domain(r O s) \<subseteq> domain(s)"
by blast
lemma domain_comp_eq: "range(s) \<subseteq> domain(r) ==> domain(r O s) = domain(s)"
by (rule domain_comp [THEN equalityI], blast)
lemma image_comp: "(r O s)``A = r``(s``A)"
by blast
lemma inj_inj_range: "f \<in> inj(A,B) ==> f \<in> inj(A,range(f))"
by (auto simp add: inj_def Pi_iff function_def)
lemma inj_bij_range: "f \<in> inj(A,B) ==> f \<in> bij(A,range(f))"
by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)
subsection\<open>Other Results\<close>
lemma comp_mono: "[| r'<=r; s'<=s |] ==> (r' O s') \<subseteq> (r O s)"
by blast
text\<open>composition preserves relations\<close>
lemma comp_rel: "[| s<=A*B; r<=B*C |] ==> (r O s) \<subseteq> A*C"
by blast
text\<open>associative law for composition\<close>
lemma comp_assoc: "(r O s) O t = r O (s O t)"
by blast
(*left identity of composition; provable inclusions are
id(A) O r \<subseteq> r
and [| r<=A*B; B<=C |] ==> r \<subseteq> id(C) O r *)
lemma left_comp_id: "r<=A*B ==> id(B) O r = r"
by blast
(*right identity of composition; provable inclusions are
r O id(A) \<subseteq> r
and [| r<=A*B; A<=C |] ==> r \<subseteq> r O id(C) *)
lemma right_comp_id: "r<=A*B ==> r O id(A) = r"
by blast
subsection\<open>Composition Preserves Functions, Injections, and Surjections\<close>
lemma comp_function: "[| function(g); function(f) |] ==> function(f O g)"
by (unfold function_def, blast)
text\<open>Don't think the premises can be weakened much\<close>
lemma comp_fun: "[| g \<in> A->B; f \<in> B->C |] ==> (f O g) \<in> A->C"
apply (auto simp add: Pi_def comp_function Pow_iff comp_rel)
apply (subst range_rel_subset [THEN domain_comp_eq], auto)
done
(*Thanks to the new definition of "apply", the premise f \<in> B->C is gone!*)
lemma comp_fun_apply [simp]:
"[| g \<in> A->B; a \<in> A |] ==> (f O g)`a = f`(g`a)"
apply (frule apply_Pair, assumption)
apply (simp add: apply_def image_comp)
apply (blast dest: apply_equality)
done
text\<open>Simplifies compositions of lambda-abstractions\<close>
lemma comp_lam:
"[| !!x. x \<in> A ==> b(x): B |]
==> (\<lambda>y\<in>B. c(y)) O (\<lambda>x\<in>A. b(x)) = (\<lambda>x\<in>A. c(b(x)))"
apply (subgoal_tac "(\<lambda>x\<in>A. b(x)) \<in> A -> B")
apply (rule fun_extension)
apply (blast intro: comp_fun lam_funtype)
apply (rule lam_funtype)
apply simp
apply (simp add: lam_type)
done
lemma comp_inj:
"[| g \<in> inj(A,B); f \<in> inj(B,C) |] ==> (f O g) \<in> inj(A,C)"
apply (frule inj_is_fun [of g])
apply (frule inj_is_fun [of f])
apply (rule_tac d = "%y. converse (g) ` (converse (f) ` y)" in f_imp_injective)
apply (blast intro: comp_fun, simp)
done
lemma comp_surj:
"[| g \<in> surj(A,B); f \<in> surj(B,C) |] ==> (f O g) \<in> surj(A,C)"
apply (unfold surj_def)
apply (blast intro!: comp_fun comp_fun_apply)
done
lemma comp_bij:
"[| g \<in> bij(A,B); f \<in> bij(B,C) |] ==> (f O g) \<in> bij(A,C)"
apply (unfold bij_def)
apply (blast intro: comp_inj comp_surj)
done
subsection\<open>Dual Properties of \<^term>\<open>inj\<close> and \<^term>\<open>surj\<close>\<close>
text\<open>Useful for proofs from
D Pastre. Automatic theorem proving in set theory.
Artificial Intelligence, 10:1--27, 1978.\<close>
lemma comp_mem_injD1:
"[| (f O g): inj(A,C); g \<in> A->B; f \<in> B->C |] ==> g \<in> inj(A,B)"
by (unfold inj_def, force)
lemma comp_mem_injD2:
"[| (f O g): inj(A,C); g \<in> surj(A,B); f \<in> B->C |] ==> f \<in> inj(B,C)"
apply (unfold inj_def surj_def, safe)
apply (rule_tac x1 = x in bspec [THEN bexE])
apply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)
apply (rule_tac t = "(`) (g) " in subst_context)
apply (erule asm_rl bspec [THEN bspec, THEN mp])+
apply (simp (no_asm_simp))
done
lemma comp_mem_surjD1:
"[| (f O g): surj(A,C); g \<in> A->B; f \<in> B->C |] ==> f \<in> surj(B,C)"
apply (unfold surj_def)
apply (blast intro!: comp_fun_apply [symmetric] apply_funtype)
done
lemma comp_mem_surjD2:
"[| (f O g): surj(A,C); g \<in> A->B; f \<in> inj(B,C) |] ==> g \<in> surj(A,B)"
apply (unfold inj_def surj_def, safe)
apply (drule_tac x = "f`y" in bspec, auto)
apply (blast intro: apply_funtype)
done
subsubsection\<open>Inverses of Composition\<close>
text\<open>left inverse of composition; one inclusion is
\<^term>\<open>f \<in> A->B ==> id(A) \<subseteq> converse(f) O f\<close>\<close>
lemma left_comp_inverse: "f \<in> inj(A,B) ==> converse(f) O f = id(A)"
apply (unfold inj_def, clarify)
apply (rule equalityI)
apply (auto simp add: apply_iff, blast)
done
text\<open>right inverse of composition; one inclusion is
\<^term>\<open>f \<in> A->B ==> f O converse(f) \<subseteq> id(B)\<close>\<close>
lemma right_comp_inverse:
"f \<in> surj(A,B) ==> f O converse(f) = id(B)"
apply (simp add: surj_def, clarify)
apply (rule equalityI)
apply (best elim: domain_type range_type dest: apply_equality2)
apply (blast intro: apply_Pair)
done
subsubsection\<open>Proving that a Function is a Bijection\<close>
lemma comp_eq_id_iff:
"[| f \<in> A->B; g \<in> B->A |] ==> f O g = id(B) \<longleftrightarrow> (\<forall>y\<in>B. f`(g`y)=y)"
apply (unfold id_def, safe)
apply (drule_tac t = "%h. h`y " in subst_context)
apply simp
apply (rule fun_extension)
apply (blast intro: comp_fun lam_type)
apply auto
done
lemma fg_imp_bijective:
"[| f \<in> A->B; g \<in> B->A; f O g = id(B); g O f = id(A) |] ==> f \<in> bij(A,B)"
apply (unfold bij_def)
apply (simp add: comp_eq_id_iff)
apply (blast intro: f_imp_injective f_imp_surjective apply_funtype)
done
lemma nilpotent_imp_bijective: "[| f \<in> A->A; f O f = id(A) |] ==> f \<in> bij(A,A)"
by (blast intro: fg_imp_bijective)
lemma invertible_imp_bijective:
"[| converse(f): B->A; f \<in> A->B |] ==> f \<in> bij(A,B)"
by (simp add: fg_imp_bijective comp_eq_id_iff
left_inverse_lemma right_inverse_lemma)
subsubsection\<open>Unions of Functions\<close>
text\<open>See similar theorems in func.thy\<close>
text\<open>Theorem by KG, proof by LCP\<close>
lemma inj_disjoint_Un:
"[| f \<in> inj(A,B); g \<in> inj(C,D); B \<inter> D = 0 |]
==> (\<lambda>a\<in>A \<union> C. if a \<in> A then f`a else g`a) \<in> inj(A \<union> C, B \<union> D)"
apply (rule_tac d = "%z. if z \<in> B then converse (f) `z else converse (g) `z"
in lam_injective)
apply (auto simp add: inj_is_fun [THEN apply_type])
done
lemma surj_disjoint_Un:
"[| f \<in> surj(A,B); g \<in> surj(C,D); A \<inter> C = 0 |]
==> (f \<union> g) \<in> surj(A \<union> C, B \<union> D)"
apply (simp add: surj_def fun_disjoint_Un)
apply (blast dest!: domain_of_fun
intro!: fun_disjoint_apply1 fun_disjoint_apply2)
done
text\<open>A simple, high-level proof; the version for injections follows from it,
using \<^term>\<open>f \<in> inj(A,B) \<longleftrightarrow> f \<in> bij(A,range(f))\<close>\<close>
lemma bij_disjoint_Un:
"[| f \<in> bij(A,B); g \<in> bij(C,D); A \<inter> C = 0; B \<inter> D = 0 |]
==> (f \<union> g) \<in> bij(A \<union> C, B \<union> D)"
apply (rule invertible_imp_bijective)
apply (subst converse_Un)
apply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)
done
subsubsection\<open>Restrictions as Surjections and Bijections\<close>
lemma surj_image:
"f \<in> Pi(A,B) ==> f \<in> surj(A, f``A)"
apply (simp add: surj_def)
apply (blast intro: apply_equality apply_Pair Pi_type)
done
lemma surj_image_eq: "f \<in> surj(A, B) ==> f``A = B"
by (auto simp add: surj_def image_fun) (blast dest: apply_type)
lemma restrict_image [simp]: "restrict(f,A) `` B = f `` (A \<inter> B)"
by (auto simp add: restrict_def)
lemma restrict_inj:
"[| f \<in> inj(A,B); C<=A |] ==> restrict(f,C): inj(C,B)"
apply (unfold inj_def)
apply (safe elim!: restrict_type2, auto)
done
lemma restrict_surj: "[| f \<in> Pi(A,B); C<=A |] ==> restrict(f,C): surj(C, f``C)"
apply (insert restrict_type2 [THEN surj_image])
apply (simp add: restrict_image)
done
lemma restrict_bij:
"[| f \<in> inj(A,B); C<=A |] ==> restrict(f,C): bij(C, f``C)"
apply (simp add: inj_def bij_def)
apply (blast intro: restrict_surj surj_is_fun)
done
subsubsection\<open>Lemmas for Ramsey's Theorem\<close>
lemma inj_weaken_type: "[| f \<in> inj(A,B); B<=D |] ==> f \<in> inj(A,D)"
apply (unfold inj_def)
apply (blast intro: fun_weaken_type)
done
lemma inj_succ_restrict:
"[| f \<in> inj(succ(m), A) |] ==> restrict(f,m) \<in> inj(m, A-{f`m})"
apply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)
apply (unfold inj_def)
apply (fast elim: range_type mem_irrefl dest: apply_equality)
done
lemma inj_extend:
"[| f \<in> inj(A,B); a\<notin>A; b\<notin>B |]
==> cons(<a,b>,f) \<in> inj(cons(a,A), cons(b,B))"
apply (unfold inj_def)
apply (force intro: apply_type simp add: fun_extend)
done
end
|
A set $S$ is an interval if and only if it is simply connected. |
State Before: x y : ℝ
⊢ ↑(exp (-x)) = ↑(exp x)⁻¹ State After: no goals Tactic: simp [exp_neg] |
function s = s_blank_delete ( s )
%*****************************************************************************80
%
%% S_BLANK_DELETE removes blanks from a string, left justifying the remainder.
%
% Discussion:
%
% All TAB characters are also removed.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 08 March 2005
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, string S, the string to be transformed.
%
% Output, string S, the transformed string.
%
TAB = 9;
s_len = length ( s );
s2 = '';
put = 0;
for get = 1 : s_len
if ( s(get) ~= ' ' && s(get) ~= TAB )
put = put + 1;
s2(put) = s(get);
end
end
s = s2;
return
end
|
State Before: α : Type u_1
β : Type u_2
γ : Type ?u.48465
ι : Sort ?u.48468
ι' : Sort ?u.48471
f : α → β
s✝ t✝ : Set α
hf : Injective f
s t : Set α
⊢ f '' s ∆ t = (f '' s) ∆ (f '' t) State After: no goals Tactic: simp_rw [Set.symmDiff_def, image_union, image_diff hf] |
Set Implicit Arguments.
Require Import String.
Require Import ZArith.
Require Import domains.
Require Import kstyle.
Require Import coinduction.
Require Import evaluator.
Coercion EVar : string >-> Exp.
Coercion ECon : Z >-> Exp.
Function evals n kcfg :=
match n with
| 0 => kcfg
| S n =>
match eval kcfg with
| Some kcfg' => evals n kcfg'
| None => kcfg
end
end.
Lemma evals_sound :
forall n c (P : kcfg -> Prop), P (evals n c) -> reaches c P.
Proof.
induction n; simpl; intros;
[|pose proof (eval_sound c); destruct (eval c)];
eauto using done,step.
Qed.
Lemma eval_happy' : forall env,
steps (KCfg (kra (SAssign "x" (EPlus "x" "y")) nil)
("x" |-> 12%Z :* "y" |-> 13%Z :* env) mapEmpty mapEmpty)
(KCfg nil ("x" |-> 25%Z :* "y" |-> 13%Z :* env) mapEmpty mapEmpty).
intros.
repeat (refine (step _ _);[match goal with [|- kstep ?l _] => eapply (eval_sound l) end|]);
instantiate;simpl Zplus;apply done;reflexivity.
Qed.
Definition gcdProg : Map string Stmt :=
"gcd" |->
SIf (BLe "a" "b")
(SIf (BLe "b" "a")
(Jump "done")
(Seq (SAssign "b" (EMinus "b" "a"))
(Jump "gcd")))
(Seq (SAssign "a" (EMinus "a" "b"))
(Jump "gcd")).
Lemma label_eval : forall env,
steps (KCfg (kra (Jump "gcd") kdot)
("a" |-> 12%Z :* "b" |-> 13%Z :* env) mapEmpty gcdProg)
(KCfg (kra (Jump "done") kdot)
("a" |-> 1%Z :* "b" |-> 1%Z :* env) mapEmpty gcdProg).
intros. apply evals_sound with 307. simpl; repeat split; reflexivity.
Qed.
(* Some performance tests *)
Definition test_prop :=
steps (KCfg (kra (SWhile (BLe 0%Z "x")
(SAssign "x" (EPlus "x" (-1)%Z)))
nil) ("x" |-> 25%Z) mapEmpty mapEmpty)
(KCfg nil ("x" |-> (-1)%Z) mapEmpty mapEmpty).
Ltac kequiv_tac := repeat (apply conj);[reflexivity|simpl;equate_maps ..].
Ltac finish := apply done;kequiv_tac.
(* Using tactics alone *)
Lemma loop_test: test_prop.
Proof.
intros;
repeat (refine (step _ _);[econstructor (reflexivity || find_map_entry)|];instantiate;simpl Zplus);
finish.
Qed.
(* go step by step, but compute successor with eval rather than by tactics *)
Lemma loop_test': test_prop.
Proof.
Ltac step_eval :=refine (step _ _);[match goal with [|- kstep ?l _] => eapply (eval_sound l) end|].
intros;repeat step_eval;simpl;finish.
Qed.
(* use multi-step evaluator, reduce with simpl *)
Lemma loop_test_evals_simpl : test_prop.
Proof.
intros;apply (evals_sound 1000);simpl;kequiv_tac.
Qed.
(* reduce with lazy *)
Lemma loop_test_evals_lazy: test_prop.
Proof.
intros;apply (evals_sound 1000);lazy;kequiv_tac.
Qed.
(* reduce with cbv *)
Lemma loop_test_evals_cbv: test_prop.
Proof.
intros;apply (evals_sound 1000);cbv;kequiv_tac.
Qed.
(* reduce with compute *)
Lemma loop_test_evals_compute : test_prop.
Proof.
intros;apply (evals_sound 1000);compute;kequiv_tac.
Qed.
(* reduce with vm_compute *)
Lemma loop_test_evals_vm_compute : test_prop.
Proof.
intros;apply (evals_sound 1000);vm_compute;kequiv_tac.
Qed. |
Saudade lures you in with a long intro that will have you thinking you just walked into an instrumental post rock band rehearsal. Not before long the band is taking off into some extremely fast and screamy intensity. By the time you get to track 3 "Drone Distance" you might have already forgotten the slow, relaxing introduction.
But alas, the band knows how to navigate their peaks and valleys. About two minutes into "Drone Distance" we're brought back down to a beautiful instrumental interlude that reminds me very much of some Portraits of Past material.
We're witnessing some professionals here who have honed their sound and have no room for mistakes. |
import algebra.big_operators.norm_num
import data.nat.fib
import data.nat.succ_pred
import linear_algebra.basis
import ring_theory.adjoin_root
import ring_theory.power_basis
import tactic.norm_fin
import tactic.norm.ring
open_locale big_operators
local attribute [-instance] rat.semiring rat.comm_semiring rat.comm_ring
-- TODO: generalize this so we don't assume a multiplication on `S`
-- or even no structure on `S` at all
structure times_table (ι R S : Type*) [fintype ι]
[semiring R] [add_comm_monoid S] [module R S] [has_mul S] :=
(basis : basis ι R S)
(table : ι → ι → ι → R)
(unfold_mul' : ∀ x y k, basis.repr (x * y) k = ∑ i j : ι, basis.repr x i * basis.repr y j * table i j k)
-- (mul_def : ∀ i j k, basis.repr (basis i * basis j) k = table i j k)
mk_simp_attribute times_table_simps "The simpset `times_table_simps` is used by the tactic
`times_table` to reduce an expression of the form `(t : times_table).basis.repr x k` to a numeral."
section add_monoid
variables {ι R S : Type*} [fintype ι] [semiring R] [add_comm_monoid S] [module R S] [has_mul S]
noncomputable def times_table.coord (t : times_table ι R S) (x : S) (i : ι) : R :=
t.basis.repr x i
@[simp] lemma times_table.basis_repr_eq (t : times_table ι R S) (x : S) (i : ι) :
t.basis.repr x i = t.coord x i := rfl
@[simp] lemma times_table.coord_basis [decidable_eq ι] (t : times_table ι R S) (i : ι) :
t.coord (t.basis i) = pi.single i 1 :=
by ext; rw [← t.basis_repr_eq, t.basis.repr_self i, finsupp.single_eq_pi_single]
lemma times_table.unfold_mul (t : times_table ι R S) :
∀ x y k, t.coord (x * y) k = ∑ i j : ι, t.coord x i * t.coord y j * t.table i j k :=
t.unfold_mul'
lemma times_table.ext (t : times_table ι R S) {x y : S} (h : ∀ i, t.coord x i = t.coord y i) :
x = y :=
t.basis.ext_elem h
end add_monoid
section semiring
variables {ι R S : Type*} [fintype ι] [comm_semiring R] [non_unital_non_assoc_semiring S] [module R S]
@[simp] lemma times_table.mul_def (t : times_table ι R S) (i j k : ι) :
t.coord (t.basis i * t.basis j) k = t.table i j k :=
begin
letI := classical.dec_eq ι,
simp only [t.unfold_mul, times_table.coord_basis],
rw [fintype.sum_eq_single i, fintype.sum_eq_single j, pi.single_eq_same,
pi.single_eq_same, one_mul, one_mul];
{ intros x hx, simp [pi.single_eq_of_ne hx] }
end
variables [smul_comm_class R S S] [is_scalar_tower R S S]
@[simp] lemma linear_equiv.map_bit0 {R M N : Type*} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
(f : M ≃ₗ[R] N) (x : M) : f (bit0 x) = bit0 (f x) :=
by { unfold bit0, simp only [_root_.map_add, finsupp.coe_add, pi.add_apply] }
@[simp] lemma linear_equiv.map_bit1 {R M N : Type*} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] [has_one M]
(f : M ≃ₗ[R] N) (x : M) : f (bit1 x) = bit0 (f x) + f 1 :=
by { unfold bit1 bit0, simp only [_root_.map_add, finsupp.coe_add, pi.add_apply] }
end semiring
namespace tactic.times_table
open tactic
section add_comm_monoid
variables {R S ι : Type*} [fintype ι] [comm_semiring R] [add_comm_monoid S] [module R S]
variables [has_mul S]
protected lemma coord_zero (t : times_table ι R S) (k : ι) :
t.coord 0 k = 0 :=
by rw [← t.basis_repr_eq, _root_.map_zero, finsupp.zero_apply]
protected lemma coord_bit0 (t : times_table ι R S) (k : ι) {e₁ : S} {e₁' e' : R}
(e₁_eq : t.coord e₁ k = e₁') (e_eq : e₁' + e₁' = e') :
t.coord (bit0 e₁) k = e' :=
by rw [bit0, ← t.basis_repr_eq, _root_.map_add, finsupp.add_apply, t.basis_repr_eq, e₁_eq, e_eq]
protected lemma coord_bit1 [has_one S] (t : times_table ι R S) (k : ι) {e₁ : S} {e₁' e₁2 e' o : R}
(e₁_eq : t.coord e₁ k = e₁') (one_eq : t.coord 1 k = o) (e2_eq : e₁' + e₁' = e₁2)
(e_eq : e₁2 + o = e') :
t.coord (bit1 e₁) k = e' :=
by simp only [← t.basis_repr_eq,bit1, bit0, _root_.map_add, finsupp.add_apply, t.basis_repr_eq,
e₁_eq, e2_eq, one_eq, e_eq]
protected lemma coord_add (t : times_table ι R S) (k : ι) {e₁ e₂ : S} {e₁' e₂' e' : R}
(e₁_eq : t.coord e₁ k = e₁') (e₂_eq : t.coord e₂ k = e₂') (e_eq : e₁' + e₂' = e') :
t.coord (e₁ + e₂) k = e' :=
by rw [← t.basis_repr_eq,_root_.map_add, finsupp.add_apply, t.basis_repr_eq, e₁_eq, t.basis_repr_eq,
e₂_eq, e_eq]
protected lemma coord_mul (t : times_table ι R S) (k : ι) (e₁ e₂ : S) (e' : R)
(eq : ∑ i j : ι, t.coord e₁ i * t.coord e₂ j * t.table i j k = e') :
t.coord (e₁ * e₂) k = e' :=
by rw [times_table.unfold_mul t, eq]
protected lemma coord_repr_table {ι : Sort*}
{r₁i r₂j tijk e₁' e₂' t' e₁e₂ e' : R} (e₁_eq : r₁i = e₁') (e₂_eq : r₂j = e₂')
(t_eq : tijk = t') (e₁e₂_eq : e₁' * e₂' = e₁e₂) (eq : e₁e₂ * t' = e') :
r₁i * r₂j * tijk = e' :=
by rw [e₁_eq, e₂_eq, t_eq, e₁e₂_eq, eq]
end add_comm_monoid
section semiring
variables {R S ι : Type*} [fintype ι] [comm_semiring R] [semiring S] [module R S]
protected lemma eval_pow_zero (t : times_table ι R S) (k : ι) (e₁ : S) {e' : R}
(e_eq : t.coord 1 k = e') :
t.coord (e₁ ^ 0) k = e' :=
by rw [pow_zero, e_eq]
protected lemma eval_pow_one (t : times_table ι R S) (k : ι) {e₁ : S} {e' : R}
(e_eq : t.coord e₁ k = e') :
t.coord (e₁ ^ 1) k = e' :=
by rw [pow_one, e_eq]
protected lemma eval_pow_bit0 (t : times_table ι R S) (k : ι) (n : ℕ) {e₁ : S} {e' : R}
(e_eq : t.coord (e₁ ^ n * e₁ ^ n) k = e') :
t.coord (e₁ ^ (bit0 n)) k = e' :=
by rw [pow_bit0, e_eq]
protected lemma eval_pow_bit1 (t : times_table ι R S) (k : ι) (n : ℕ) {e₁ : S} {e' : R}
(e_eq : t.coord (e₁ ^ n * e₁ ^ n * e₁) k = e') :
t.coord (e₁ ^ (bit1 n)) k = e' :=
by rw [pow_bit1, e_eq]
end semiring
section ring
variables {R S ι : Type*} [fintype ι] [comm_ring R] [ring S] [module R S]
protected lemma coord_sub (t : times_table ι R S) (k : ι) {e₁ e₂ : S} {e₁' e₂' e' : R}
(e₁_eq : t.coord e₁ k = e₁') (e₂_eq : t.coord e₂ k = e₂') (e_eq : e₁' - e₂' = e') :
t.coord (e₁ - e₂) k = e' :=
by rw [← t.basis_repr_eq, _root_.map_sub, finsupp.sub_apply, t.basis_repr_eq, e₁_eq,
t.basis_repr_eq, e₂_eq, e_eq]
protected lemma coord_neg (t : times_table ι R S) (k : ι) {e₁ : S} {e₁' e' : R}
(e₁_eq : t.coord e₁ k = e₁') (e_eq : -e₁' = e') :
t.coord (-e₁) k = e' :=
by rw [← t.basis_repr_eq, _root_.map_neg, finsupp.neg_apply, t.basis_repr_eq, e₁_eq, e_eq]
end ring
section matrix
open matrix
section converter
meta structure context :=
(simps : simp_lemmas)
(cache : tactic.norm.ring.cache)
(coord_univ : native.rb_map expr (expr × expr × list expr))
meta abbreviation eval_m (α : Type*) := state_t context tactic α
/-- Evaluates a parsed (in α) expression into a normal form (in β). -/
meta abbreviation evaluator (α β : Type*) := expr × α → eval_m (expr × expr × β)
meta abbreviation converter := expr → eval_m (expr × expr)
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error {α σ} (msg : string) (t : state_t σ tactic α) : state_t σ tactic α :=
{ run := λ s ts, match t.run s ts with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception
(some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end }
meta def lift {σ α} : tactic α → state_t σ tactic α := state_t.lift
meta def converter.lift {σ α β} : (α → tactic β) → α → state_t σ tactic β := λ t x, lift (t x)
meta def converter.refl : converter
| e := lift (refl_conv e)
meta def converter.or : converter → converter → converter
| c d e := c e <|> d e
meta def converter.or_refl (c : converter) : converter := c.or converter.refl
meta def converter.trans : converter → converter → converter
| c d e := do
(e', pf_c) ← c.or_refl e,
(e'', pf_d) ← d.or_refl e',
pf ← lift $ mk_eq_trans pf_c pf_d,
pure (e'', pf)
meta def get_context : state_t context tactic context :=
state_t.get
meta def to_expr' : pexpr → tactic expr := i_to_expr
meta def to_expr : pexpr → eval_m expr := lift ∘ to_expr'
end converter
namespace tactic.norm_num
/-- Use `norm_num` to decide equality between two expressions.
If the decision procedure succeeds, the `bool` value indicates whether the expressions are equal,
and the `expr` is a proof of (dis)equality.
This procedure is partial: it will fail in cases where `norm_num` can't reduce either side
to a rational numeral.
-/
meta def decide_eq (l r : expr) : tactic (bool × expr) := do
(l', l'_pf) ← or_refl_conv norm_num.derive l,
(r', r'_pf) ← or_refl_conv norm_num.derive r,
n₁ ← l'.to_rat, n₂ ← r'.to_rat,
c ← infer_type l' >>= mk_instance_cache,
if n₁ = n₂ then do
pf ← mk_eq_symm r'_pf >>= mk_eq_trans l'_pf,
pure (tt, pf)
else do
(_, p) ← norm_num.prove_ne c l' r' n₁ n₂,
pure (ff, p)
lemma list.mem_cons_of_head {α : Type*} {x y : α} (ys : list α) (h₁ : x = y) :
x ∈ y :: ys :=
(list.mem_cons_iff x y _).mpr (or.inl h₁)
lemma list.mem_cons_of_tail {α : Type*} {x y : α} {ys : list α} (h₂ : x ∈ ys) :
x ∈ y :: ys :=
(list.mem_cons_iff x y _).mpr (or.inr h₂)
lemma list.not_mem_cons {α : Type*} {x y : α} {ys : list α} (h₁ : x ≠ y) (h₂ : x ∉ ys) :
x ∉ y :: ys :=
λ h, ((list.mem_cons_iff _ _ _).mp h).elim h₁ h₂
/-- Use a decision procedure for the equality of list elements to decide list membership.
If the decision procedure succeeds, the `bool` value indicates whether the expressions are equal,
and the `expr` is a proof of (dis)equality.
This procedure is partial iff its parameter `decide_eq` is partial.
-/
meta def list.decide_mem (decide_eq : expr → expr → tactic (bool × expr)) :
expr → list expr → tactic (bool × expr)
| x [] := do
pf ← mk_app `list.not_mem_nil [x],
pure (ff, pf)
| x (y :: ys) := do
(is_head, head_pf) ← decide_eq x y,
if is_head then do
pf ← mk_app `list.mem_cons_of_head [head_pf],
pure (tt, pf)
else do
(mem_tail, tail_pf) ← list.decide_mem x ys,
if mem_tail then do
pf ← mk_app `list.mem_cons_of_tail [tail_pf],
pure (tt, pf)
else do
pf ← mk_app `list.not_mem_cons [head_pf, tail_pf],
pure (ff, pf)
lemma finset.insert_eq_coe_list_of_mem {α : Type*} [decidable_eq α] (x : α) (xs : finset α)
{xs' : list α} (h : x ∈ xs') (nd_xs : xs'.nodup)
(hxs' : xs = finset.mk ↑xs' (multiset.coe_nodup.mpr nd_xs)) :
insert x xs = finset.mk ↑xs' (multiset.coe_nodup.mpr nd_xs) :=
have h : x ∈ xs, by simpa [hxs'] using h,
by rw [finset.insert_eq_of_mem h, hxs']
lemma finset.insert_eq_coe_list_cons {α : Type*} [decidable_eq α] (x : α) (xs : finset α)
{xs' : list α} (h : x ∉ xs') (nd_xs : xs'.nodup) (nd_xxs : (x :: xs').nodup)
(hxs' : xs = finset.mk ↑xs' (multiset.coe_nodup.mpr nd_xs)) :
insert x xs = finset.mk ↑(x :: xs') (multiset.coe_nodup.mpr nd_xxs) :=
have h : x ∉ xs, by simpa [hxs'] using h,
by { rw [← finset.val_inj, finset.insert_val_of_not_mem h, hxs'], simp only [multiset.cons_coe] }
/-- Given an expression defeq to a natural numeral, return the value of this numeral.
This is a slightly more powerful version of `expr.to_nat`.
-/
meta def parse_nat : expr → option ℕ
| `(%%a + %%b) := do
a' ← parse_nat a,
b' ← parse_nat b,
pure (a' + b')
| n := expr.to_nat n
lemma list.map_cons_congr {α β : Type*} (f : α → β) (x : α) (xs : list α) (fx : β) (fxs : list β)
(h₁ : f x = fx) (h₂ : xs.map f = fxs) : (x :: xs).map f = fx :: fxs :=
by rw [list.map_cons, h₁, h₂]
meta def list.to_expr (α : expr) : list expr → tactic expr
| [] := mk_app `list.nil [α]
| (ex :: xs) := do
exs ← list.to_expr xs,
mk_app `list.cons [α, ex, exs]
/-- Apply `ef : α → β` to all elements of the list, constructing an equality proof.
`eval_f (x : expr) : tactic (expr × expr)` is a conversion procedure for simplifying expressions
of the form `(%%ef %%x), where `ef : expr` is the function to apply and `x : expr` is a list
element.
-/
meta def eval_list_map {α β : Type*} (ef : expr)
(eval_f : expr × α → eval_m (expr × expr × β)) :
expr → list (α) → state_t context tactic (list (expr × β) × expr)
| exs [] := do
match exs with
| `(list.nil) := do
eq ← lift $ mk_app `list.map_nil [ef],
pure ([], eq)
| _ := lift $ fail!"eval_list_map: expecting `list.nil`, received {exs}"
end
| `(list.cons %%ex %%exs) (x :: xs) := do
(fx, fx_eq, fx_d) ← eval_f (ex, x),
(fxs, fxs_eq) ← eval_list_map exs xs,
ty ← lift $ infer_type fx,
fxs_list ← lift $ list.to_expr ty (fxs.map prod.fst),
eq ← lift $ mk_app `tactic.times_table.tactic.norm_num.list.map_cons_congr [ef, ex, exs, fx, fxs_list, fx_eq, fxs_eq],
pure ((fx, fx_d) :: fxs, eq)
| exs (_ :: _) := lift $ fail format!"eval_list_map: expecting `list.cons _ _`, received {exs}"
lemma list.cons_congr {α : Type*} (x : α) {xs : list α} {xs' : list α} (xs_eq : xs' = xs) :
x :: xs' = x :: xs :=
by rw xs_eq
lemma list.map_congr {α β : Type*} (f : α → β) {xs xs' : list α}
{ys : list β} (xs_eq : xs = xs') (ys_eq : xs'.map f = ys) :
xs.map f = ys :=
by rw [← ys_eq, xs_eq]
/-- Convert an expression denoting a list to a list of elements. -/
meta def eval_list : expr → eval_m (expr × expr × list expr)
| e@`(list.nil) := do
eq ← lift $ mk_eq_refl e,
pure (e, eq, [])
| e@`(list.cons %%x %%xs) := do
(exs, xs_eq, xs) ← eval_list xs,
e' ← lift $ mk_app `list.cons [x, exs],
eq ← lift $ mk_app `list.cons_congr [x, xs_eq],
pure (e', eq, x :: xs)
/-
| e@`(list.range %%en) := do
n ← lift $ parse_nat en,
eis ← lift $ (list.range n).mmap (λ i, expr.of_nat `(ℕ) i),
eq ← lift $ mk_eq_refl e,
pure (eis, eq)
| `(@list.map %%α %%β %%ef %%exs) := do
(xs, xs_eq) ← eval_list exs,
(ys, ys_eq) ← eval_list_map ef (converter.or_refl $ converter.lift norm_num.derive) xs,
eq ← to_expr ``(list.map_congr %%ef %%xs_eq %%ys_eq),
pure (ys, eq)
-/
| e@`(@list.fin_range %%en) := do
n ← lift $ parse_nat en,
eis ← (list.fin_range n).mmap (λ i, lift $ expr.of_nat `(fin %%en) i),
eq ← lift $ mk_eq_refl e,
let e'_list := eis.foldr (λ x xs, `(@list.cons (fin %%en) %%x %%xs)) `(@list.nil (fin %%en)),
pure (e'_list, eq, eis)
| e := lift $ fail (to_fmt "Unknown list expression" ++ format.line ++ to_fmt e)
lemma multiset.cons_congr {α : Type*} (x : α) {xs : multiset α} {xs' : list α}
(xs_eq : (xs' : multiset α) = xs) : (list.cons x xs' : multiset α) = x ::ₘ xs :=
by rw [← xs_eq]; refl
lemma multiset.map_congr {α β : Type*} (f : α → β) {xs : multiset α}
{xs' : list α} {ys : list β} (xs_eq : xs = (xs' : multiset α)) (ys_eq : xs'.map f = ys) :
xs.map f = (ys : multiset β) :=
by rw [← ys_eq, ← multiset.coe_map, xs_eq]
/-- Convert an expression denoting a multiset to a list of elements,
normalizing the expression to a sequence of `multiset.cons` and `0`.
We return a list rather than a finset, so we can more easily iterate over it
(without having to prove that our tactics are independent of the order of iteration,
which is in general not true).
-/
meta def eval_multiset : expr → eval_m (expr × expr × list expr)
| e@`(@has_zero.zero (multiset _) _) := do
eq ← lift $ mk_eq_refl e,
pure (e, eq, [])
| e@`(@has_emptyc.emptyc _ %%inst) := do
eq ← lift $ mk_eq_refl e,
pure (e, eq, [])
| e@`(has_singleton.singleton %%x) := do
eq ← lift $ mk_eq_refl e,
pure (e, eq, [x])
| e@`(multiset.cons %%x %%xs) := do
(exs, xs_eq, xs) ← eval_multiset xs,
e' ← lift $ mk_app `multiset.cons [x, exs],
eq ← lift $ mk_app `multiset.cons_congr [x, xs_eq],
pure (e', eq, x :: xs)
| e@`(@@has_insert.insert multiset.has_insert %%x %%xs) := do
(exs, xs_eq, xs) ← eval_multiset xs,
e' ← lift $ mk_app `multiset.cons [x, exs],
eq ← lift $ mk_app `multiset.cons_congr [x, xs_eq],
pure (e', eq, x :: xs)
/-
| e@`(multiset.range %%en) := do
n ← lift $ parse_nat en,
eis ← lift $ (list.range n).mmap (λ i, expr.of_nat `(ℕ) i),
eq ← lift $ mk_eq_refl e,
pure (eis, eq)
| `(@multiset.map %%α %%β %%ef %%exs) := do
(xs, xs_eq) ← eval_multiset exs,
(ys, ys_eq) ← eval_list_map ef (converter.or_refl $ converter.lift norm_num.derive) xs,
eq ← to_expr ``(multiset.map_congr %%ef %%xs_eq %%ys_eq),
pure (ys, eq)
-/
| `(@@coe (@@coe_to_lift (@@coe_base (multiset.has_coe))) %%exs) := do
(exs, xs_eq, xs) ← trace_error "eval_list" $ eval_list exs,
e ← to_expr ``(@@coe (@@coe_to_lift (@@coe_base (multiset.has_coe))) %%exs),
eq ← to_expr ``(congr_arg coe %%xs_eq),
pure (e, eq, xs)
| e := lift $ fail (to_fmt "Unknown multiset expression" ++ format.line ++ to_fmt e)
lemma finset.mk_congr {α : Type*} {xs xs' : multiset α} (h : xs = xs') (nd nd') :
finset.mk xs nd = finset.mk xs' nd' :=
by congr; assumption
lemma finset.nodup_congr {α : Type*} (xs xs' : multiset α) (h : xs = xs') (nd : xs.nodup) :
xs'.nodup :=
by rwa h at nd
/-- Convert an expression denoting a finset to an expression of the form `finset.mk ↑xs nodup`.
We return a list rather than a finset, so we can more easily iterate over it
(without having to prove that our tactics are independent of the order of iteration,
which is in general not true).
`decide_eq` is a (partial) decision procedure for determining whether two
elements of the finset are equal, for example to parse `{2, 1, 2}` into `[2, 1]`.
-/
meta def eval_finset (decide_eq : expr → expr → tactic (bool × expr)) :
expr → eval_m (expr × expr × list expr)
| e@`(finset.mk %%val %%nd) := do
(norm, eq, val') ← trace_error "eval_multiset" $ eval_multiset val,
nd' ← to_expr ``(finset.nodup_congr %%val %%norm %%eq %%nd),
e' ← to_expr ``(finset.mk %%norm %%nd'),
eq' ← to_expr ``(finset.mk_congr %%eq %%nd %%nd'),
pure (e', eq', val')
/-
| e@`(has_emptyc.emptyc) := do
eq ← mk_eq_refl e,
nd ← to_expr' ``(list.nodup_nil),
pure ([], eq, nd)
| e@`(has_singleton.singleton %%x) := do
eq ← mk_eq_refl e,
nd ← to_expr' ``(list.nodup_singleton %%x),
pure ([x], eq, nd)
| `(@@has_insert.insert (@@finset.has_insert %%dec) %%x %%xs) := do
(exs, xs_eq, xs_nd) ← eval_finset xs,
(is_mem, mem_pf) ← list.decide_mem decide_eq x exs,
if is_mem then do
pf ← to_expr' ``(finset.insert_eq_coe_list_of_mem %%x %%xs %%mem_pf %%xs_nd %%xs_eq),
pure (exs, pf, xs_nd)
else do
nd ← to_expr' ``(list.nodup_cons.mpr ⟨%%mem_pf, %%xs_nd⟩),
pf ← to_expr' ``(finset.insert_eq_coe_list_cons %%x %%xs %%mem_pf %%xs_nd %%nd %%xs_eq),
pure (x :: exs, pf, nd)
-/
| `(@@finset.univ %%ft) := trace_error "eval_finset `finset.univ`" $ do
-- Convert the fintype instance expression `ft` to a list of its elements.
-- Unfold it to the `fintype.mk` constructor and a list of arguments.
`fintype.mk ← lift $ get_app_fn_const_whnf ft
| lift $ fail (to_fmt "Unknown fintype expression" ++ format.line ++ to_fmt ft),
[_, args, _] ← lift $ get_app_args_whnf ft | lift $ fail (to_fmt "Expected 3 arguments to `fintype.mk`"),
msg ← lift $ pformat!"error in recursive call `eval_finset {args}`",
trace_error msg.to_string $ eval_finset args
| e@`(finset.range %%en) := do
n ← lift $ parse_nat en,
eis ← lift $ (list.range n).mmap (λ i, expr.of_nat `(ℕ) i),
eq ← lift $ mk_eq_refl e,
let e'_list := eis.foldr (λ x xs, `(@list.cons ℕ %%x %%xs)) `(@list.nil ℕ),
e' ← to_expr ``(finset.mk ↑%%e'_list (multiset.coe_nodup.mpr (list.nodup_range %%en))),
pure (e', eq, eis)
| e := lift $ fail (to_fmt "Unknown finset expression" ++ format.line ++ to_fmt e)
@[to_additive]
lemma list.prod_cons_congr {α : Type*} [monoid α] (xs : list α) (x y z : α)
(his : xs.prod = y) (hi : x * y = z) : (x :: xs).prod = z :=
by rw [list.prod_cons, his, hi]
/-
/-- Evaluate `list.prod %%xs`,
producing the evaluated expression and an equality proof. -/
meta def list.prove_prod (α : expr) : list expr → tactic (expr × expr)
| [] := do
result ← expr.of_nat α 1,
proof ← to_expr' ``(@list.prod_nil %%α _),
pure (result, proof)
| (x :: xs) := do
eval_xs ← list.prove_prod xs,
xxs ← to_expr' ``(%%x * %%eval_xs.1),
eval_xxs ← or_refl_conv norm_num.derive xxs,
exs ← expr.of_list α xs,
proof ← to_expr'
``(list.prod_cons_congr %%exs%%x %%eval_xs.1 %%eval_xxs.1 %%eval_xs.2 %%eval_xxs.2),
pure (eval_xxs.1, proof)
-/
/-- Evaluate `list.sum %%xs`,
producing the evaluated expression and an equality proof. -/
meta def list.prove_sum {α : Type*}
(eval_zero : eval_m (expr × expr × α)) (eval_add : expr × α → expr × α → eval_m (expr × expr × α))
(M : expr) : list (expr × α) → eval_m (expr × expr × α)
| [] := do
⟨zero, _, zero_d⟩ ← eval_zero,
proof ← to_expr ``(@list.sum_nil %%M _),
pure ⟨zero, proof, zero_d⟩
| (x :: xs) := do
⟨sxs, sxs_pf, sxs_d⟩ ← list.prove_sum xs,
⟨sxxs, sxxs_pf, sxxs_d⟩ ← eval_add x (sxs, sxs_d),
exs ← lift $ expr.of_list M (xs.map prod.fst),
proof ← to_expr
``(list.sum_cons_congr %%exs %%x.1 %%sxs %%sxxs %%sxs_pf %%sxxs_pf),
pure ⟨sxxs, proof, sxxs_d⟩
@[to_additive] lemma list.prod_congr {α : Type*} [monoid α] {xs xs' : list α} {z : α}
(h₁ : xs = xs') (h₂ : xs'.prod = z) : xs.prod = z := by cc
@[to_additive] lemma multiset.prod_congr {α : Type*} [comm_monoid α]
{xs : multiset α} {xs' : list α} {z : α}
(h₁ : xs = (xs' : multiset α)) (h₂ : xs'.prod = z) : xs.prod = z :=
by rw [← h₂, ← multiset.coe_prod, h₁]
/-
/-- Evaluate `(%%xs.map (%%ef : %%α → %%β)).prod`,
producing the evaluated expression and an equality proof.
`eval_f : expr → tactic (expr × expr)` is a conversion procedure for simplifying expressions
of the form `(%%ef %%x), where `ef : expr` is the function to apply and `x : expr` is a list
element.
-/
meta def list.prove_prod_map (β ef : expr) (eval_f : converter)
(xs : list expr) : state_t context tactic (expr × expr) := do
(fxs, fxs_eq) ← eval_list_map ef eval_f xs,
(prod, prod_eq) ← lift $ list.prove_prod β fxs,
eq ← to_expr ``(list.prod_congr %%fxs_eq %%prod_eq),
pure (prod, eq)
-/
/-- Evaluate `(%%xs.map (%%ef : %%α → %%β)).sum`,
producing the evaluated expression and an equality proof.
`eval_f : expr → tactic (expr × expr)` is a conversion procedure for simplifying expressions
of the form `(%%ef %%x), where `ef : expr` is the function to apply and `x : expr` is a list
element.
-/
meta def list.prove_sum_map (M ef : expr)
{α β : Type*}
(eval_zero : eval_m (expr × expr × α)) (eval_add : expr × α → expr × α → eval_m (expr × expr × α))
(eval_f : expr × β → eval_m (expr × expr × α))
(exs : expr) (xs : list β) : eval_m (expr × expr × α) :=
trace_error "internal error in prove_sum_map" $ do
(fxs, fxs_eq) ← eval_list_map ef eval_f exs xs,
(sum, sum_eq, sum_d) ← list.prove_sum eval_zero eval_add M fxs,
eq ← to_expr ``(list.sum_congr %%fxs_eq %%sum_eq),
pure (sum, eq, sum_d)
@[to_additive]
lemma finset.eval_prod_of_list {β α : Type*} [comm_monoid β]
(s : finset α) (f : α → β) {is : list α} (his : is.nodup)
(hs : finset.mk ↑is (multiset.coe_nodup.mpr his) = s)
{x : β} (hx : (is.map f).prod = x) :
s.prod f = x :=
by rw [← hs, finset.prod_mk, multiset.coe_map, multiset.coe_prod, hx]
meta def eval_finset_sum {α β : Type*} (eval_set : expr × unit → eval_m (expr × expr × list β))
(eval_zero : eval_m (expr × expr × α)) (eval_add : expr × α → expr × α → eval_m (expr × expr × α))
(eval_f : expr → expr × β → eval_m (expr × expr × α)) (eβ ef : expr) (es : expr) :
eval_m (expr × expr × α) :=
trace_error "internal error in eval_finset_sum" $ do
(es', list_eq, xs) ← eval_set (es, ()),
match es' with
| `(finset.mk (coe %%exs) %%nodup) := do
(result, sum_eq, result_d) ← list.prove_sum_map eβ ef eval_zero eval_add (eval_f ef) exs xs,
pf ← to_expr ``(finset.eval_sum_of_list %%es %%ef %%nodup %%list_eq %%sum_eq),
pure (result, pf, result_d)
| _ := do
lift $ fail format!"eval_finset_sum: expected `finset.mk _ _`, received {es'}"
end
/-- `eval_set` takes a `finset` expression and returns a tuple consisting of:
* the normal form, of the form `finset.mk (↑bs) nodup`, where `is` is a sequence of `list.cons` and `list.nil`
* the normalization proof
* a list of extra information, one per term in `bs` -/
meta def norm_finset_sum {α β : Type*} (eval_set : expr × unit → eval_m (expr × expr × list β))
(eval_zero : eval_m (expr × expr × α)) (eval_add : expr × α → expr × α → eval_m (expr × expr × α))
(eval_f : expr → expr × β → eval_m (expr × expr × α)) : expr → eval_m (expr × expr × α)
| `(@finset.sum %%β %%α %%inst %%es %%ef) := eval_finset_sum eval_set eval_zero eval_add eval_f β ef es
| e := lift $ fail $ format! "norm_finset_sum: expected ∑ i in s, f i, got {e}"
/-
/-- `norm_num` plugin for evaluating big operators:
* `list.prod`
* `list.sum`
* `multiset.prod`
* `multiset.sum`
* `finset.prod`
* `finset.sum`
-/
meta def eval_big_operators : converter
| `(@list.prod %%α %%inst1 %%inst2 %%exs) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq) ← eval_list exs,
(result, sum_eq) ← lift $ list.prove_prod α xs,
pf ← to_expr ``(list.prod_congr %%list_eq %%sum_eq),
pure (result, pf)
| `(@list.sum %%α %%inst1 %%inst2 %%exs) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq) ← eval_list exs,
(result, sum_eq) ← list.prove_sum (converter.or_refl $ converter.lift norm_num.derive) α xs,
pf ← to_expr ``(list.sum_congr %%list_eq %%sum_eq),
pure (result, pf)
| `(@multiset.prod %%α %%inst %%exs) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq) ← eval_multiset exs,
(result, sum_eq) ← lift $ list.prove_prod α xs,
pf ← to_expr ``(multiset.prod_congr %%list_eq %%sum_eq),
pure (result, pf)
| `(@multiset.sum %%α %%inst %%exs) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq) ← eval_multiset exs,
(result, sum_eq) ← list.prove_sum (converter.or_refl $ converter.lift norm_num.derive) α xs,
pf ← to_expr ``(multiset.sum_congr %%list_eq %%sum_eq),
pure (result, pf)
| `(@finset.prod %%β %%α %%inst %%es %%ef) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq, nodup) ← lift $ eval_finset decide_eq es,
(result, sum_eq) ← list.prove_prod_map β ef (converter.or_refl $ converter.lift norm_num.derive) xs,
pf ← to_expr ``(finset.eval_prod_of_list %%es %%ef %%nodup %%list_eq %%sum_eq),
pure (result, pf)
| `(@finset.sum %%β %%α %%inst %%es %%ef) :=
trace_error "Internal error in `tactic.norm_num.eval_big_operators`:" $ do
(xs, list_eq, nodup) ← lift $ eval_finset decide_eq es,
(result, sum_eq) ← list.prove_sum_map β ef (converter.or_refl $ converter.lift norm_num.derive) (converter.or_refl $ converter.lift norm_num.derive) xs,
pf ← to_expr ``(finset.eval_sum_of_list %%es %%ef %%nodup %%list_eq %%sum_eq),
pure (result, pf)
| _ := lift $ failed
-/
end tactic.norm_num
lemma eval_vec_cons_pf_zero {α : Type*} {n : ℕ} (x : α) (xs : fin n → α) :
vec_cons x xs has_zero.zero = x := rfl
lemma eval_vec_cons_pf_succ {α : Type*} {n : ℕ} (i : fin n) (x y : α) (xs : fin n → α)
(h : xs i = y) : vec_cons x xs (fin.succ i) = y :=
by rw [cons_val_succ, h]
/-- `eval_vec_cons n x xs` returns `(y, ⊢ vec_cons x xs n = y)` -/
meta def eval_vec_cons : ℕ → expr → expr → tactic (expr × expr)
| 0 x xs := do
eq ← mk_app ``eval_vec_cons_pf_zero [x, xs],
pure (x, eq)
| (n + 1) x' xxs@`(vec_cons %%x %%xs) := do
(result, eq') ← eval_vec_cons n x xs,
eq ← to_expr' ``(eval_vec_cons_pf_succ _ %%x' %%result %%xxs %%eq'),
pure (result, eq)
| (n + 1) x xs := tactic.trace xs >> fail "Expected vector of the form `vec_cons x y`"
open tactic.norm_fin
@[norm_num]
meta def norm_vec_cons : expr → tactic (expr × expr)
| `(vec_cons %%x %%xs %%i) := i.to_nat >>= λ n, tactic.trace_error "Internal error in `norm_vec_cons`." $ do
(y, pf) ← tactic.trace_error "" $ eval_vec_cons n x xs,
pure (y, pf)
| e := pformat!"norm_vec_cons: expected `vec_cons x xs i`, got {e}" >>= fail
end matrix
/-- Simplify expressions of the form `(t : times_table).coord x k` using lemmas tagged
`@[times_table_simps]`. -/
-- @[norm_num]
meta def simp_times_table : converter
| e := do
ctx ← get_context,
(e', pf, _) ← state_t.lift $ simplify ctx.simps [] e <|>
fail!"Failed to simplify {e}, are you missing a `@[times_table_simps]` lemma?",
pure (e', pf)
protected lemma eval_vec_cons_pf {α ι : Type*} (t : ι → ι → ι → α) (i j k : ι)
{ti : ι → ι → α} (ti_pf : t i = ti) {tij : ι → α} (tij_pf : ti j = tij) :
t i j k = tij k :=
by rw [ti_pf, tij_pf]
meta def head_beta' (e : expr) : state_t context tactic expr :=
trace_error "error in head_beta" $ lift (head_beta e)
meta def conv_pexpr (conv : converter) (e : pexpr) : state_t context tactic (expr × expr) :=
lift (to_expr' e) >>= conv
meta def norm_cf : expr → state_t context tactic (expr × expr × ℚ)
| e := do
(e', pf) ← converter.or_refl (converter.lift norm_num.derive) e,
match e'.to_rat with
| (some p) := pure (e', pf, p)
| _ := failure
end
meta def eval_add_cf : (expr × ℚ) → (expr × ℚ) → state_t context tactic (expr × expr × ℚ)
| (e₁, n₁) (e₂, n₂) := do
(e', pf) ← conv_pexpr (converter.or_refl $ converter.lift norm_num.derive) ``(%%e₁ + %%e₂),
pure (e', pf, n₁ + n₂)
meta def eval_neg_cf : (expr × ℚ) → state_t context tactic (expr × expr × ℚ)
| (e, n) := do
(e', pf) ← conv_pexpr (converter.or_refl $ converter.lift norm_num.derive) ``(- %%e),
pure (e', pf, -n)
meta def eval_mul_cf : (expr × ℚ) → (expr × ℚ) → state_t context tactic (expr × expr × ℚ)
| (e₁, n₁) (e₂, n₂) := do
(e', pf) ← conv_pexpr (converter.or_refl $ converter.lift norm_num.derive) ``(%%e₁ * %%e₂),
pure (e', pf, n₁ * n₂)
meta def eval_pow_cf : (expr × ℚ) → (expr × ℕ) → state_t context tactic (expr × expr × ℚ)
| (e₁, n₁) (e₂, n₂) := do
(e', pf) ← conv_pexpr (converter.or_refl $ converter.lift norm_num.derive) ``(%%e₁ ^ %%e₂),
pure (e', pf, n₁ ^ n₂)
meta instance : tactic.norm.ring.monad_ring (state_t context tactic) :=
⟨λ _, lift,
λ _, failure,
context.cache <$> state_t.get⟩
meta def eval_ring : evaluator unit (tactic.norm.ring.horner_expr ℚ)
| e := do
(horner, pf) ← tactic.norm.ring.eval norm_cf eval_add_cf eval_neg_cf eval_mul_cf eval_pow_cf e.1,
pure (horner.e, pf, horner)
meta def eval_ring_zero (M : expr) : eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) :=
do
zero ← lift $ expr.of_nat M 0,
pf ← lift $ mk_eq_refl zero,
pure (zero, pf, tactic.norm.ring.horner_expr.const zero 0)
meta def eval_ring_one (M : expr) : eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) :=
do
one ← lift $ expr.of_nat M 1,
pf ← lift $ mk_eq_refl one,
pure (one, pf, tactic.norm.ring.horner_expr.const one 1)
meta def eval_ring_add (l r : expr × tactic.norm.ring.horner_expr ℚ) :
eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) := do
do
(e', p') ← tactic.norm.ring.eval_add eval_add_cf l.2 r.2,
return (e', p', e')
meta def eval_ring_mul (l r : expr × tactic.norm.ring.horner_expr ℚ) :
eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) := do
do
(e', p') ← tactic.norm.ring.eval_mul eval_add_cf eval_mul_cf l.2 r.2,
return (e', p', e')
lemma unfold_sub {α} [add_group α] (a b b' c : α)
(hb : -b = b') (h : a + b' = c) : a - b = c :=
by rw [sub_eq_add_neg, hb, h]
meta def eval_ring_sub (l r : expr × tactic.norm.ring.horner_expr ℚ) :
eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) := do
do
(r', r'_eq) ← tactic.norm.ring.eval_neg eval_neg_cf r.2,
(e', p') ← tactic.norm.ring.eval_add eval_add_cf l.2 r',
p ← to_expr ``(unfold_sub %%(l.2 : expr) %%(r.2 : expr) %%(r' : expr) %%(e' : expr) %%r'_eq %%p'),
return (e', p, e')
meta def eval_ring_neg (e : expr × tactic.norm.ring.horner_expr ℚ) :
eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ) := do
do
(e', p') ← tactic.norm.ring.eval_neg eval_neg_cf e.2,
return (e', p', e')
meta def mk_cached_finset_univ (ι inst : expr) (ctx : context) : eval_m (expr × expr × list expr) :=
do
`fintype.mk ← lift $ get_app_fn_const_whnf inst
| lift $ fail (format!"Unknown fintype expression {inst}"),
[_, args, _] ← lift $ get_app_args_whnf inst | lift $ fail (format!"Expected 3 arguments to `fintype.mk`"),
result ← trace_error "eval_finset" $ tactic.norm_num.eval_finset tactic.norm_num.decide_eq args,
state_t.put { coord_univ := ctx.coord_univ.insert ι result, .. ctx },
pure result
meta def get_cached_finset_univ : expr × unit → eval_m (expr × expr × list expr)
| (`(@finset.univ %%ι %%inst), _) :=
do ctx ← get_context,
match ctx.coord_univ.find ι with
| (some cu) := pure cu
| none := mk_cached_finset_univ ι inst ctx
end
| e := lift $ fail format!"get_cached_finset_univ: expected `(univ : finset _)`, got {e}"
meta def eq_rhs (e : expr) : tactic expr := do
t ← infer_type e,
match t with
| `(_ = %%rhs) := pure rhs
| _ := fail!"eq_rhs: expecting type of form `(_ = _), got {t}"
end
/-- Evaluate expressions of the form `t.coord e₁ i * t.coord e₂ j * t.table i j k`.
`eval_coord` is a procedure for evaluating expression of the form `t.coord %%e %%i`.
This is passed as a separate parameter since Lean's support for mutual recursion is limited,
and we tie the recursive knot ourselves.
-/
meta def eval_mul_mul (ι R : expr)
(eval_coord : expr → expr → eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ)) :
expr → eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ)
| `(%%e₁i * %%e₂j * %%tableij) := trace_error "internal error in `eval_mul_mul`" $ do
ι_sort ← lift $ infer_type ι,
ι_level ← match ι_sort.match_sort with
| (some ι_level) := pure ι_level
| none := lift $ fail!"expecting (ι : Type), got ({ι} : {ι_sort})"
end,
-- Simplify and evaluate `t.coord e₁ i`
(e₁i', e₁i_pf₁) ← simp_times_table.trans (converter.lift norm_vec_cons) e₁i,
(e₁i', e₁i_pf₂, e₁i_expr) ← match e₁i' with
| `(times_table.coord %%t %%e₁ %%i) := eval_coord e₁ i
| _ := eval_ring (e₁i', ())
end,
e₁i_pf ← lift $ mk_eq_trans e₁i_pf₁ e₁i_pf₂,
-- Simplify and evaluate `t.coord e₂ j`
(e₂j', e₂j_pf₁) ← simp_times_table.trans (converter.lift norm_vec_cons) e₂j,
(e₂j', e₂j_pf₂, e₂j_expr) ← match e₂j' with
| `(times_table.coord %%t %%e₁ %%i) := eval_coord e₁ i
| _ := eval_ring (e₂j', ())
end,
e₂j_pf ← lift $ mk_eq_trans e₂j_pf₁ e₂j_pf₂,
-- Simplify and evaluate `t.table i j k`
(tableij', tableij_pf₁) ← simp_times_table.trans (λ e, match e with
| (expr.app (expr.app ti@(expr.app t i) j) k) := do
(ti', ti_pf) ← lift $ norm_vec_cons ti,
(tij', tij_pf) ← lift $ norm_vec_cons (expr.app ti' j),
pf ← lift $ mk_app `tactic.times_table.eval_vec_cons_pf [R, ι, t, i, j, k, ti', ti_pf, tij', tij_pf],
pure (expr.app tij' k, pf)
| e := lift $ pformat!"expected `t.table i j k`, got {e}" >>= fail
end) tableij,
(tableij', tableij_pf₂, tableij_expr) ← eval_ring (tableij', ()),
tableij_pf ← lift $ mk_eq_trans tableij_pf₁ tableij_pf₂,
(e₁e₂, e₁e₂_pf, e₁e₂_expr) ← eval_ring_mul (e₁i', e₁i_expr) (e₂j', e₂j_expr),
(e', e_pf, he') ← eval_ring_mul (e₁e₂, e₁e₂_expr) (tableij', tableij_expr),
pf ← norm.ring.ic_lift (λ ic, do
let n := `tactic.times_table.coord_repr_table,
let l := [ι, e₁i, e₂j, tableij, e₁i', e₂j', tableij', e₁e₂, e', e₁i_pf, e₂j_pf, tableij_pf,
e₁e₂_pf, e_pf],
d ← get_decl n,
(ic, l) ← ic.append_typeclasses d.type.binding_body l,
return (ic, (expr.const n [ic.univ, ι_level]).mk_app (ic.α :: l)) ),
pure (e', pf, he')
| e := lift $ pformat!"expected `t.coord e₁ i * t.coord e₂ j * t.table i j k`, got {e}" >>= fail
/-- Normalize `((t : times_table _ _ _).coord e) k` into Horner form. -/
protected meta def eval (ι R S t : expr) :
expr → expr → eval_m (expr × expr × tactic.norm.ring.horner_expr ℚ)
| `(0) k := trace_error "zero" $ do
e ← lift $ expr.of_nat R 0,
pf ← to_expr ``(tactic.times_table.coord_zero %%t %%k),
pure (e, pf, tactic.norm.ring.horner_expr.const e 0)
| `(bit0 %%e₁) k := trace_error "bit0" $ do
(e₁', e₁_eq, he₁') ← eval e₁ k,
(e', e_eq, he') ← eval_ring_add (e₁', he₁') (e₁', he₁'),
eq ← to_expr ``(tactic.times_table.coord_bit0 %%t %%k %%e₁_eq %%e_eq),
pure (e', eq, he')
| `(bit1 %%e₁) k := trace_error "bit1" $ do
(e₁', e₁_eq, he₁') ← eval e₁ k,
(one', one_eq, hone') ← (lift $ expr.of_nat S 1) >>= (λ e, eval e k),
(e', e_eq, he') ← eval_ring_add (e₁', he₁') (e₁', he₁'),
(e'', e'_eq, he'') ← eval_ring_add (e', he') (one', hone'),
eq ← to_expr ``(tactic.times_table.coord_bit1 %%t %%k %%e₁_eq %%one_eq %%e_eq %%e'_eq),
pure (e'', eq, he'')
| `(%%e₁ + %%e₂) k := trace_error "add" $ do
(e₁', e₁_eq, he₁') ← eval e₁ k,
(e₂', e₂_eq, he₂') ← eval e₂ k,
(e', e_eq, he') ← eval_ring_add (e₁', he₁') (e₂', he₂'),
eq ← to_expr ``(tactic.times_table.coord_add %%t %%k %%e₁_eq %%e₂_eq %%e_eq),
pure (e', eq, he')
| `(%%e₁ - %%e₂) k := trace_error "sub" $ do
(e₁', e₁_eq, he₁') ← eval e₁ k,
(e₂', e₂_eq, he₂') ← eval e₂ k,
(e', e_eq, he') ← eval_ring_sub (e₁', he₁') (e₂', he₂'),
eq ← to_expr ``(tactic.times_table.coord_sub %%t %%k %%e₁_eq %%e₂_eq %%e_eq),
pure (e', eq, he')
| `(-%%e₁) k := trace_error "neg" $ do
(e₁', e₁_eq, he₁') ← eval e₁ k,
(e', e_eq, he') ← eval_ring_neg (e₁', he₁'),
eq ← to_expr ``(tactic.times_table.coord_neg %%t %%k %%e₁_eq %%e_eq),
pure (e', eq, he')
| e@`(%%e₁ * %%e₂) k := trace_error "error in mul" $ do
eq_sum_mul_times_table ← lift $ mk_app `times_table.unfold_mul [t, e₁, e₂, k],
e ← lift $ eq_rhs eq_sum_mul_times_table,
(e', e_eq, he') ← tactic.norm_num.norm_finset_sum get_cached_finset_univ (eval_ring_zero R) eval_ring_add -- evaluates the sum over i
(λ f ⟨i, ei⟩, do
term ← lift $ whnf (f i) transparency.reducible,
tactic.norm_num.norm_finset_sum get_cached_finset_univ (eval_ring_zero R) eval_ring_add -- evaluates the sum over j
(λ f ⟨j, _⟩, do
term ← lift $ whnf (f j) transparency.reducible,
eval_mul_mul ι R eval term)
term)
e,
eq ← lift $ mk_eq_trans eq_sum_mul_times_table e_eq,
pure (e', eq, he')
| `(%%e₁ ^ %%n) k := trace_error "pow" $ do
match norm_num.match_numeral n with
| norm_num.match_numeral_result.zero := do
one ← lift $ expr.of_nat S 1,
(one', one_eq, hone') ← eval one k,
eq ← to_expr ``(tactic.times_table.eval_pow_zero %%t %%k %%e₁ %%one_eq),
pure (one', eq, hone')
| norm_num.match_numeral_result.one := do
(e', e₁_eq, he') ← eval e₁ k,
eq ← to_expr ``(tactic.times_table.eval_pow_one %%t %%k %%e₁_eq),
pure (e', eq, he')
| norm_num.match_numeral_result.bit0 b := do
e₁' ← to_expr ``((%%e₁ ^ %%b) * (%%e₁ ^ %%b)),
(e', e_eq, he') ← eval e₁' k,
eq ← to_expr ``(tactic.times_table.eval_pow_bit0 %%t %%k %%b %%e_eq),
pure (e', eq, he')
| norm_num.match_numeral_result.bit1 b := do
e₁' ← to_expr ``((%%e₁ ^ %%b) * (%%e₁ ^ %%b) * %%e₁),
(e', e_eq, he') ← eval e₁' k,
eq ← to_expr ``(tactic.times_table.eval_pow_bit1 %%t %%k %%b %%e_eq),
pure (e', eq, he')
| _ := lift $ tactic.fail "Expecting numeral in exponent"
end
| e k := trace_error "times_table_simps" $ do
full_e ← to_expr ``(times_table.coord %%t %%e %%k),
(e', pr) ← simp_times_table full_e,
(e'', pr', he'') ← eval_ring (e', ()),
pf ← lift $ mk_eq_trans pr pr',
pure (e'', pf, he'')
/--
`run_converter' atoms ek conv e` returns a `conv`-normalized form of `ek` = `f e`,
where `f` is some arbitrary function.
See also `run_converter` if you're running on only one subexpression.
-/
meta def run_converter' (atoms : ref (buffer expr)) (ek : expr) : converter → expr → tactic (expr × expr)
| conv e := do
(simps, _) ← mk_simp_set tt [`times_table_simps]
[simp_arg_type.expr ``(mul_zero), simp_arg_type.expr ``(zero_mul), simp_arg_type.expr ``(mul_one), simp_arg_type.expr ``(one_mul),
simp_arg_type.expr ``(add_zero), simp_arg_type.expr ``(zero_add)],
α ← infer_type ek,
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
ic ← mk_instance_cache α,
(ic, c) ← ic.get ``comm_semiring,
nc ← mk_instance_cache `(ℕ),
using_new_ref ic $ λ r,
using_new_ref nc $ λ nr,
let cache : norm.ring.cache := ⟨α, u, c, transparency.semireducible, r, nr, atoms⟩ in do
(result, _) ← (conv e).run { simps := simps, cache := cache, coord_univ := native.rb_map.mk _ _ },
pure result
/--
`run_converter ek conv e` returns a `conv`-normalized form of `ek` = `f e`, where `f` is some arbitrary function.
-/
meta def run_converter (ek : expr) : converter → expr → tactic (expr × expr)
| conv e := using_new_ref mk_buffer $ λ atoms, run_converter' atoms ek conv e
set_option eqn_compiler.max_steps 4096
/-- Normalize expressions of the form `t.coord _`. -/
protected meta def norm_conv : converter
| ek@(expr.app (expr.app `(times_table.coord %%t) e) k) := do
ι ← lift $ infer_type k,
S ← lift $ infer_type e,
R ← lift $ infer_type ek,
(e', pf, he') ← trace_error "Internal error in `tactic.times_table.eval`:" $
tactic.times_table.eval ι R S t e k,
pf_ty ← lift $ infer_type pf,
match pf_ty with
| `(%%lhs = %%rhs) := do
lift $ is_def_eq ek lhs <|> (trace "lhs does not match:" >> trace ek >> trace " ≠ " >> trace lhs),
lift $ is_def_eq e' rhs <|> (trace "rhs does not match:" >> trace e' >> trace " ≠ " >> trace rhs)
| _ := lift $ trace "Proof type is not an equality: " >> trace pf_ty
end,
pure (e', pf)
| _ := failure
/-- `norm_num` extension for expressions of the form `times_table.coord t _` -/
@[norm_num]
protected meta def norm : expr → tactic (expr × expr)
| ek@(expr.app (expr.app `(times_table.coord %%t) e) k) := do
ι ← infer_type k,
S ← infer_type e,
R ← infer_type ek,
(e', pf) ← tactic.trace_error "Internal error in `tactic.times_table.eval`:" $
run_converter ek (λ e, tactic.times_table.eval ι R S t e k >>= λ eph, pure (eph.1, eph.2.1)) e,
pf_ty ← infer_type pf,
match pf_ty with
| `(%%lhs = %%rhs) := do
is_def_eq ek lhs <|> (trace "lhs does not match:" >> trace ek >> trace " ≠ " >> trace lhs),
is_def_eq e' rhs <|> (trace "rhs does not match:" >> trace e' >> trace " ≠ " >> trace rhs)
| _ := trace "Proof type is not an equality: " >> trace pf_ty
end,
pure (e', pf)
| _ := failure
meta def conv_subexpressions (step : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) :=
do e ← instantiate_mvars e,
(_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, trace "no discharger" >> failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← step e,
guard (¬ new_e =ₐ e) <|> (trace "rewriting was idempotent: " >> trace e >> trace " → " >> trace new_e >> failure),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
end tactic.times_table
namespace tactic.interactive
open tactic
setup_tactic_parser
/-- Tactic for proving equalities of polynomial expressions in a finite extension of a base ring. -/
meta def times_table (red : parse (tk "!")?) : tactic unit :=
let transp := if red.is_some then semireducible else reducible in
do `(%%e₁ = %%e₂) ← target >>= instantiate_mvars,
using_new_ref mk_buffer $ λ atoms, do
(e₁', p₁) ← (tactic.times_table.run_converter' atoms e₁ tactic.times_table.norm_conv) e₁,
(e₂', p₂) ← (tactic.times_table.run_converter' atoms e₂ tactic.times_table.norm_conv) e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
end tactic.interactive
|
############################################################################
##
## primitive.gi IRREDSOL Burkhard Höfling
##
## Copyright © 2003–2016 Burkhard Höfling
##
############################################################################
##
#F PcGroupExtensionByMatrixAction(<pcgs>, <hom>)
##
## Let <G> be a finite soluble group with pcgs <pcgs>, and let <hom> be a
## group hom. $<hom>\colon G \to GL(n, p)$, where $p$ is a prime. Let $E$
## denote the split
## extension of $G$ by $V = \F_p$, where <G> acts on <V> via <hom>.
## This function returns a record with the following components.
## ext: the group $E$ as a new pc group
## V: the subgroup $V$ of $E$ corresponding to the vector space
## C: a complement of $V$ in $E$ isomorphic with $G$
## embed: a group homomorphism $G \to E$ with image $C$
## proj: a group homomorphism $E \to G$ with kernel $V$
## pcgsV: an induced pcgs of V (wrt. FamilyPcgs(E)) whose elements
## correspond to the natural basis elements
## of the vector space V
## pcgsC: an induced pcgs of C (wrt. FamilyPcgs(E)) whose elements
## correspond to the images of pcgs under embed;
## the elements of pcgsC act on pcgsV as the images of pcgs
## under hom act on the natural basis of V
##
InstallGlobalFunction(PcGroupExtensionByMatrixAction,
function(pcgs, hom)
local p, d, ros, f, coll, exp, mat, i, j, r, E, pcgsC, pcgsV;
p := Size(FieldOfMatrixGroup(Range(hom)));
d := DegreeOfMatrixGroup(Range(hom));
if not IsPrimeInt(p) then
Error("Range(hom) must be over a prime field ");
fi;
ros := RelativeOrders(pcgs);
f := FreeGroup(Length(pcgs) + d);
coll := SingleCollector(f,
Concatenation(ros,
ListWithIdenticalEntries(d, p)));
# relations for complement - same as for those for G
exp := [];
exp{[1,3..2*Length(pcgs)-1]} := [1..Length(pcgs)];
for i in [1..Length(pcgs)] do
exp{[2,4..2*Length(pcgs)]} := ExponentsOfPcElement(pcgs, pcgs[i]^ros[i]);
# Print("power relation ", i,": ", exp, "\n");
SetPower(coll, i, ObjByExtRep(FamilyObj(f.1), exp));
for j in [i+1..Length(pcgs)] do
exp{[2,4..2*Length(pcgs)]} := ExponentsOfPcElement(pcgs, pcgs[j]^pcgs[i]);
# Print("conj. relation ", j, "^", i,": ", exp, "\n");
SetConjugate(coll, j, i, ObjByExtRep(FamilyObj(f.1), exp));
od;
od;
# relations for socle
for j in [1..d] do
SetPower(coll, j+Length(pcgs), One(f));
od;
exp := [];
exp{[1,3..2*d-1]} :=
[Length(pcgs) + 1..Length(pcgs) + d];
for i in [1..Length(pcgs)] do
mat := ImageElm(hom, pcgs[i]);
for j in [1..d] do
exp{[2,4..2*d]} := List(mat[j], IntFFE);
# Print("conj. relation ", j+ Length(pcgs), "^", i,": ", exp, "\n");
SetConjugate(coll, j + Length(pcgs), i, ObjByExtRep(FamilyObj(f.1), exp));
od;
od;
E := GroupByRwsNC(coll);
SetSize(E, Product(ros) * p^d);
pcgsV := InducedPcgsByPcSequenceNC(FamilyPcgs(E),
FamilyPcgs(E){[Length(pcgs) + 1..Length(FamilyPcgs(E))]});
# the following sets attributes/properties which are defined
# in the CRISP packages
pcgsC := InducedPcgsByPcSequenceNC(FamilyPcgs(E),
FamilyPcgs(E){[1..Length(pcgs)]});
r := rec(
E := E,
V := GroupOfPcgs(pcgsV),
C := GroupOfPcgs(pcgsC),
pcgsV := pcgsV,
pcgsC := pcgsC);
r.embed := GroupHomomorphismByImagesNC(GroupOfPcgs(pcgs), E, pcgs, pcgsC);
SetIsInjective(r.embed, true);
SetImagesSource(r.embed, r.C);
r.proj := GroupHomomorphismByImagesNC(E, GroupOfPcgs(pcgs),
Concatenation(pcgsC, pcgsV),
Concatenation(pcgs, ListWithIdenticalEntries(d, OneOfPcgs(pcgs))));
SetIsSurjective(r.proj, true);
SetKernelOfMultiplicativeGeneralMapping(r.proj, r.V);
return r;
end);
############################################################################
##
#F PrimitivePcGroupIrreducibleMatrixGroup(<G>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(PrimitivePcGroupIrreducibleMatrixGroup,
function(G)
if not IsMatrixGroup(G) or not IsFinite(FieldOfMatrixGroup(G))
or not IsPrimeInt(Size(FieldOfMatrixGroup(G)))
or not IsIrreducibleMatrixGroup(G) then
Error("G must be an irreducible matrix group over a prime field");
fi;
return PrimitivePcGroupIrreducibleMatrixGroupNC(G);
end);
############################################################################
##
#F PrimitivePcGroupIrreducibleMatrixGroupNC(<G>)
##
## see IRREDSOL documentation
##
## it is important that the map from Pcgs(Source(RepresentationIsomorphism(G)))
##
InstallGlobalFunction(PrimitivePcGroupIrreducibleMatrixGroupNC,
function(G)
local rep, ext;
rep := RepresentationIsomorphism(G);
ext := PcGroupExtensionByMatrixAction(Pcgs(Source(rep)), rep);
SetSocle(ext.E, ext.V);
SetSocleComplement(ext.E, ext.C);
SetFittingSubgroup(ext.E, ext.V);
# the following sets attributes/properties which are defined
# in the CRISP packages
if IsBoundGlobal("SetIsPrimitiveSoluble") then
ValueGlobal("SetIsPrimitiveSoluble")(ext.E, true);
fi;
return ext.E;
end);
############################################################################
##
#F PrimitivePcGroup(<n>,<p>,<d>,<k>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(PrimitivePcGroup,
function(n, p, d, k)
local q, desc, G, mat, bas, hom, ext, o, pcgs, pcgsC, pcgsV, H;
if not IsPosInt(n) or not IsPosInt(d) or not IsPosInt(p) or not IsPrimeInt(p) or n mod d <> 0 then
Error("n, p, and d must be positive integers, ",
"p must be a prime, and d must divide n");
elif not k in IndicesIrreducibleSolubleMatrixGroups(n, p, d) then
Error("k must be in IndicesIrreducibleSolubleMatrixGroups(n, p, d)");
else
n := n /d;
q := p^d;
LoadAbsolutelyIrreducibleSolubleGroupData(n, q);
if n > 1 then
desc := IRREDSOL_DATA.GROUPS[n][q][k];
fi;
if not IsBound(IRREDSOL_DATA.PRIM_GUARDIANS[n]) then
IRREDSOL_DATA.PRIM_GUARDIANS[n] := [];
fi;
if not IsBound(IRREDSOL_DATA.PRIM_GUARDIANS[n][q]) then
if n = 1 then
G := IRREDSOL_DATA.GUARDIANS[1][q][1];
mat := [[Z(q)]];
hom := GroupHomomorphismByImagesNC(G, Group(mat),
MinimalGeneratingSet(G), [mat]);
SetIsBijective(hom, true);
else
hom := IRREDSOL_DATA.GUARDIANS[n][q][desc[1]][3];
G := Source(hom);
fi;
if d > 1 then
bas := CanonicalBasis(AsVectorSpace(GF(p), GF(q)));
mat := List(InducedPcgsWrtFamilyPcgs(G),
g -> BlownUpMat(bas, ImageElm(hom, g)));
hom := GroupHomomorphismByImagesNC(G, Group(mat),
InducedPcgsWrtFamilyPcgs(G), mat);
fi;
IRREDSOL_DATA.PRIM_GUARDIANS[n][q] :=
PcGroupExtensionByMatrixAction(InducedPcgsWrtFamilyPcgs(G), hom);
fi;
ext := IRREDSOL_DATA.PRIM_GUARDIANS[n][q];
if n = 1 then
Assert(1, Length(MinimalGeneratingSet(ext.C)) = 1);
o := IRREDSOL_DATA.GROUPS_DIM1[q][k][1];
pcgsC := InducedPcgsByGenerators(FamilyPcgs(ext.E),
[MinimalGeneratingSet(ext.C)[1]^((q-1)/o)]);
else
pcgsC := CanonicalPcgsByNumber(ext.pcgsC, desc[2]);
fi;
pcgs := InducedPcgsByPcSequenceNC(FamilyPcgs(ext.E), Concatenation(pcgsC, ext.pcgsV));
H := GroupOfPcgs(pcgs);
SetIdPrimitiveSolubleGroup(H, [n*d,p,d,k]);
SetSocle(H, ext.V);
SetFittingSubgroup(H, ext.V);
SetSocleComplement(H, GroupOfPcgs(pcgsC));
# the following sets attributes/properties which are defined
# in the CRISP packages
if IsBoundGlobal("SetIsPrimitiveSoluble") then
ValueGlobal("SetIsPrimitiveSoluble")(H, true);
fi;
return H;
fi;
end);
############################################################################
##
#F IrreducibleMatrixGroupPrimitiveSolubleGroup(<G>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(IrreducibleMatrixGroupPrimitiveSolubleGroup,
function(G)
local F, p, matgrp, compl;
if not IsFinite(G) or not IsSolvableGroup(G) then
Error("G must be finite and soluble");
# test if primitive - use the CRISP method if it is available
elif IsBoundGlobal("IsPrimitiveSoluble")
and ValueGlobal("IsPrimitiveSoluble")(G) then
return IrreducibleMatrixGroupPrimitiveSolubleGroupNC(G);
else # test for primitivity
F := FittingSubgroup(G);
if not IsPGroup(F) or not IsAbelian(F) then
Error("G must be primitive");
else
p := PrimePGroup(F);
if ForAny(GeneratorsOfGroup(F), x -> x^p <> One(G)) then
Error("G must be primitive");
else
matgrp := IrreducibleMatrixGroupPrimitiveSolubleGroupNC(G);
if not IsIrreducibleMatrixGroup(matgrp, GF(p)) then
Error("G must be primitive");
else
compl := ComplementClassesRepresentatives(G, F);
if Length(compl) <> 1 then
Error("G must be primitive");
fi;
SetSocle(G, F);
return matgrp;
fi;
fi;
fi;
fi;
end);
############################################################################
##
#F IrreducibleMatrixGroupPrimitiveSolubleGroupNC(<G>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(IrreducibleMatrixGroupPrimitiveSolubleGroupNC,
function(G)
local N, p, F, pcgsN, pcgsGmodN, GmodN, one, mat, mats, g, h, i, H, hom;
N := FittingSubgroup(G);
pcgsN := Pcgs(N);
p := RelativeOrders(pcgsN)[1];
F := GF(p);
one := One(F);
mats := [];
pcgsGmodN := ModuloPcgs(G, N);
for g in pcgsGmodN do
mat := [];
for i in [1..Length(pcgsN)] do
mat[i] := ExponentsOfPcElement(pcgsN, pcgsN[i]^g)*one;
od;
Add(mats, ImmutableMatrix(F, mat));
od;
H := Group(mats);
SetSize(H, Size(G)/Size(N));
GmodN := PcGroupWithPcgs(pcgsGmodN);
hom := GroupGeneralMappingByImagesNC(GmodN, H, FamilyPcgs(GmodN), mats);
SetIsGroupHomomorphism(hom, true);
SetIsBijective(hom, true);
SetRepresentationIsomorphism(H, hom);
return H;
end);
############################################################################
##
#F DoIteratorPrimitiveSolubleGroups(<convert_func>, <arg_list>)
##
## generic constructor function for an iterator of all primitive soluble groups
## which can construct permutation groups or pc groups (or other types of groups),
## depending on convert_func
##
InstallGlobalFunction(DoIteratorPrimitiveSolubleGroups,
function(convert_func, arg_list)
local r, iter;
r := CheckAndExtractArguments([
[[Degree, NrMovedPoints, LargestMovedPoint], IsPosInt],
[[Order, Size], IsPosInt]],
arg_list,
"IteratorPrimitivePcGroups");
if ForAny(r.specialvalues, v -> IsEmpty(v)) then
return Iterator([]);
fi;
iter := rec(convert_func := convert_func);
if not IsBound(r.specialvalues[1]) then
Error("IteratorPrimitivePcGroupsIterator: You must specify the degree(s) of the desired primitive groups");
else
iter.degs := Filtered(r.specialvalues[1], IsPPowerInt);
fi;
iter.degind := 0;
if IsBound(r.specialvalues[2]) then
iter.orders := r.specialvalues[2];
else
iter.orders := fail;
fi;
iter.iteratormatgrp := Iterator([]);
iter.IsDoneIterator := function(iterator)
local d, p, n, orders, o;
if iterator!.degind > Length(iterator!.degs) then
Error("isDoneIterator called after it returned true");
fi;
while IsDoneIterator(iterator!.iteratormatgrp) do
iterator!.degind := iterator!.degind + 1;
if iterator!.degind > Length(iterator!.degs) then
return true;
fi;
d := iterator!.degs[iterator!.degind];
p := SmallestRootInt(d);
n := LogInt(d, p);
if IsAvailableIrreducibleSolubleGroupData(n, p) then
if iterator!.orders <> fail then
orders := [];
for o in iterator!.orders do
if o mod d = 0 then
Add(orders, o/d);
fi;
od;
iterator!.iteratormatgrp := IteratorIrreducibleSolubleMatrixGroups(
Degree, n, Field, GF(p), Order, orders);
else
iterator!.iteratormatgrp := IteratorIrreducibleSolubleMatrixGroups(
Degree, n, Field, GF(p));
fi;
else
Error("groups of degree ", d, " are beyond the scope of the IRREDSOL library");
iterator!.iteratormatgrp := Iterator([]);
fi;
od;
return false;
end;
iter.NextIterator := function(iterator)
local G;
G := NextIterator(iterator!.iteratormatgrp);
return iterator!.convert_func(G);
end;
iter.ShallowCopy := function(iterator)
return rec(
orders := iterator!.orders,
degs := iterator!.degs,
degind := iterator!.degind,
convert_func := iterator!.convert_func,
iteratormatgrp := ShallowCopy(iterator!.iteratormatgrp),
IsDoneIterator := iterator!.IsDoneIterator,
NextIterator := iterator!.NextIterator,
ShallowCopy := iterator!.ShallowCopy);
end;
return IteratorByFunctions(iter);
end);
############################################################################
##
#F IteratorPrimitivePcGroups(<func_1>, <val_1>, ...)
##
## see the IRREDSOL manual
##
InstallGlobalFunction(IteratorPrimitivePcGroups,
function(arg)
return DoIteratorPrimitiveSolubleGroups(
PrimitivePcGroupIrreducibleMatrixGroupNC,
arg);
end);
###########################################################################
##
#F AllPrimitivePcGroups(<arg>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(AllPrimitivePcGroups,
function(arg)
local iter, l, G;
iter := CallFuncList(IteratorPrimitivePcGroups, arg);
l := [];
for G in iter do
Add(l, G);
od;
return l;
end);
###########################################################################
##
#F OnePrimitivePcGroup(<arg>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(OnePrimitivePcGroup,
function(arg)
local iter;
iter := CallFuncList(IteratorPrimitivePcGroups, arg);
if IsDoneIterator(iter) then
return fail;
else
return NextIterator(iter);
fi;
end);
############################################################################
##
#F PrimitivePermGroupIrreducibleMatrixGroup(<G>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(PrimitivePermGroupIrreducibleMatrixGroup,
function(G)
if not IsMatrixGroup(G) or not IsFinite(FieldOfMatrixGroup(G))
or not IsPrimeInt(Size(FieldOfMatrixGroup(G)))
or not IsIrreducibleMatrixGroup(G) then
Error("G must be an irreducible matrix group over a prime field");
fi;
return PrimitivePermGroupIrreducibleMatrixGroupNC(G);
end);
############################################################################
##
#F PrimitivePermGroupIrreducibleMatrixGroupNC(<G>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(PrimitivePermGroupIrreducibleMatrixGroupNC,
function( M )
local gensc, genss, V, bas, enum, G;
V := FieldOfMatrixGroup( M ) ^ DimensionOfMatrixGroup( M );
bas := CanonicalBasis(V);
enum := EnumeratorByBasis(bas);
gensc := List(GeneratorsOfGroup(M), x -> Permutation(x, enum));
genss := List( bas, x -> Permutation( x, enum, \+));
G := GroupByGenerators(Concatenation(genss, gensc));
SetSize( G, Size( M ) * Size( V ) );
SetSocle(G, Subgroup(G, genss));
SetSocleComplement(G, Subgroup(G, gensc));
# the following sets attributes/properties which are defined
# in the CRISP packages
if IsBoundGlobal("SetIsPrimitiveSoluble") then
ValueGlobal("SetIsPrimitiveSoluble")(G, true);
fi;
return G;
end);
############################################################################
##
#F PrimitiveSolublePermGroup(<n>,<p>,<d>,<k>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(PrimitiveSolublePermGroup,
function(n, p, d, k)
local G;
if not IsPosInt(n) or not IsPosInt(d) or not IsPosInt(p) or not IsPrimeInt(p) then
Error("n, p, and d must be positive integers, ",
"p must be a prime, and d must divide n");
elif not k in IndicesIrreducibleSolubleMatrixGroups(n, p, d) then
Error("k must be in IndicesIrreducibleSolubleMatrixGroups(n, p, d)");
else
G := PrimitivePermGroupIrreducibleMatrixGroupNC(
IrreducibleSolubleMatrixGroup(n, p, d, k));
SetIdPrimitiveSolubleGroup(G, [n,p,d,k]);
fi;
return G;
end);
############################################################################
##
#F IteratorPrimitiveSolublePermGroups(<func_1>, <val_1>, ...)
##
## see the IRREDSOL manual
##
InstallGlobalFunction(IteratorPrimitiveSolublePermGroups,
function(arg)
return DoIteratorPrimitiveSolubleGroups(
PrimitivePermGroupIrreducibleMatrixGroupNC,
arg);
end);
###########################################################################
##
#F AllPrimitiveSolublePermGroups(<arg>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(AllPrimitiveSolublePermGroups,
function(arg)
local iter, l, G;
iter := CallFuncList(IteratorPrimitiveSolublePermGroups, arg);
l := [];
for G in iter do
Add(l, G);
od;
return l;
end);
###########################################################################
##
#F OnePrimitiveSolublePermGroup(<arg>)
##
## see IRREDSOL documentation
##
InstallGlobalFunction(OnePrimitiveSolublePermGroup,
function(arg)
local iter;
iter := CallFuncList(IteratorPrimitiveSolublePermGroups, arg);
if IsDoneIterator(iter) then
return fail;
else
return NextIterator(iter);
fi;
end);
############################################################################
##
#E
##
|
(* Title: HOL/Fields.thy
Author: Gertrud Bauer
Author: Steven Obua
Author: Tobias Nipkow
Author: Lawrence C Paulson
Author: Markus Wenzel
Author: Jeremy Avigad
*)
section \<open>Fields\<close>
theory Fields
imports Nat
begin
subsection \<open>Division rings\<close>
text \<open>
A division ring is like a field, but without the commutativity requirement.
\<close>
class inverse = divide +
fixes inverse :: "'a \<Rightarrow> 'a"
begin
abbreviation inverse_divide :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "'/" 70)
where
"inverse_divide \<equiv> divide"
end
text \<open>Setup for linear arithmetic prover\<close>
ML_file \<open>~~/src/Provers/Arith/fast_lin_arith.ML\<close>
ML_file \<open>Tools/lin_arith.ML\<close>
setup \<open>Lin_Arith.global_setup\<close>
declaration \<open>K (
Lin_Arith.init_arith_data
#> Lin_Arith.add_discrete_type \<^type_name>\<open>nat\<close>
#> Lin_Arith.add_lessD @{thm Suc_leI}
#> Lin_Arith.add_simps @{thms simp_thms ring_distribs if_True if_False
minus_diff_eq
add_0_left add_0_right order_less_irrefl
zero_neq_one zero_less_one zero_le_one
zero_neq_one [THEN not_sym] not_one_le_zero not_one_less_zero
add_Suc add_Suc_right nat.inject
Suc_le_mono Suc_less_eq Zero_not_Suc
Suc_not_Zero le_0_eq One_nat_def}
#> Lin_Arith.add_simprocs [\<^simproc>\<open>group_cancel_add\<close>, \<^simproc>\<open>group_cancel_diff\<close>,
\<^simproc>\<open>group_cancel_eq\<close>, \<^simproc>\<open>group_cancel_le\<close>,
\<^simproc>\<open>group_cancel_less\<close>,
\<^simproc>\<open>nateq_cancel_sums\<close>,\<^simproc>\<open>natless_cancel_sums\<close>,
\<^simproc>\<open>natle_cancel_sums\<close>])\<close>
simproc_setup fast_arith_nat ("(m::nat) < n" | "(m::nat) \<le> n" | "(m::nat) = n") =
\<open>K Lin_Arith.simproc\<close> \<comment> \<open>Because of this simproc, the arithmetic solver is
really only useful to detect inconsistencies among the premises for subgoals which are
\<^emph>\<open>not\<close> themselves (in)equalities, because the latter activate
\<^text>\<open>fast_nat_arith_simproc\<close> anyway. However, it seems cheaper to activate the
solver all the time rather than add the additional check.\<close>
lemmas [linarith_split] = nat_diff_split split_min split_max abs_split
text\<open>Lemmas \<open>divide_simps\<close> move division to the outside and eliminates them on (in)equalities.\<close>
named_theorems divide_simps "rewrite rules to eliminate divisions"
class division_ring = ring_1 + inverse +
assumes left_inverse [simp]: "a \<noteq> 0 \<Longrightarrow> inverse a * a = 1"
assumes right_inverse [simp]: "a \<noteq> 0 \<Longrightarrow> a * inverse a = 1"
assumes divide_inverse: "a / b = a * inverse b"
assumes inverse_zero [simp]: "inverse 0 = 0"
begin
subclass ring_1_no_zero_divisors
proof
fix a b :: 'a
assume a: "a \<noteq> 0" and b: "b \<noteq> 0"
show "a * b \<noteq> 0"
proof
assume ab: "a * b = 0"
hence "0 = inverse a * (a * b) * inverse b" by simp
also have "\<dots> = (inverse a * a) * (b * inverse b)"
by (simp only: mult.assoc)
also have "\<dots> = 1" using a b by simp
finally show False by simp
qed
qed
lemma nonzero_imp_inverse_nonzero:
"a \<noteq> 0 \<Longrightarrow> inverse a \<noteq> 0"
proof
assume ianz: "inverse a = 0"
assume "a \<noteq> 0"
hence "1 = a * inverse a" by simp
also have "... = 0" by (simp add: ianz)
finally have "1 = 0" .
thus False by (simp add: eq_commute)
qed
lemma inverse_zero_imp_zero:
assumes "inverse a = 0" shows "a = 0"
proof (rule ccontr)
assume "a \<noteq> 0"
then have "inverse a \<noteq> 0"
by (simp add: nonzero_imp_inverse_nonzero)
with assms show False
by auto
qed
lemma inverse_unique:
assumes ab: "a * b = 1"
shows "inverse a = b"
proof -
have "a \<noteq> 0" using ab by (cases "a = 0") simp_all
moreover have "inverse a * (a * b) = inverse a" by (simp add: ab)
ultimately show ?thesis by (simp add: mult.assoc [symmetric])
qed
lemma nonzero_inverse_minus_eq:
"a \<noteq> 0 \<Longrightarrow> inverse (- a) = - inverse a"
by (rule inverse_unique) simp
lemma nonzero_inverse_inverse_eq:
"a \<noteq> 0 \<Longrightarrow> inverse (inverse a) = a"
by (rule inverse_unique) simp
lemma nonzero_inverse_eq_imp_eq:
assumes "inverse a = inverse b" and "a \<noteq> 0" and "b \<noteq> 0"
shows "a = b"
proof -
from \<open>inverse a = inverse b\<close>
have "inverse (inverse a) = inverse (inverse b)" by (rule arg_cong)
with \<open>a \<noteq> 0\<close> and \<open>b \<noteq> 0\<close> show "a = b"
by (simp add: nonzero_inverse_inverse_eq)
qed
lemma inverse_1 [simp]: "inverse 1 = 1"
by (rule inverse_unique) simp
lemma nonzero_inverse_mult_distrib:
assumes "a \<noteq> 0" and "b \<noteq> 0"
shows "inverse (a * b) = inverse b * inverse a"
proof -
have "a * (b * inverse b) * inverse a = 1" using assms by simp
hence "a * b * (inverse b * inverse a) = 1" by (simp only: mult.assoc)
thus ?thesis by (rule inverse_unique)
qed
lemma division_ring_inverse_add:
"a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a + inverse b = inverse a * (a + b) * inverse b"
by (simp add: algebra_simps)
lemma division_ring_inverse_diff:
"a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a - inverse b = inverse a * (b - a) * inverse b"
by (simp add: algebra_simps)
lemma right_inverse_eq: "b \<noteq> 0 \<Longrightarrow> a / b = 1 \<longleftrightarrow> a = b"
proof
assume neq: "b \<noteq> 0"
{
hence "a = (a / b) * b" by (simp add: divide_inverse mult.assoc)
also assume "a / b = 1"
finally show "a = b" by simp
next
assume "a = b"
with neq show "a / b = 1" by (simp add: divide_inverse)
}
qed
lemma nonzero_inverse_eq_divide: "a \<noteq> 0 \<Longrightarrow> inverse a = 1 / a"
by (simp add: divide_inverse)
lemma divide_self [simp]: "a \<noteq> 0 \<Longrightarrow> a / a = 1"
by (simp add: divide_inverse)
lemma inverse_eq_divide [field_simps, field_split_simps, divide_simps]: "inverse a = 1 / a"
by (simp add: divide_inverse)
lemma add_divide_distrib: "(a+b) / c = a/c + b/c"
by (simp add: divide_inverse algebra_simps)
lemma times_divide_eq_right [simp]: "a * (b / c) = (a * b) / c"
by (simp add: divide_inverse mult.assoc)
lemma minus_divide_left: "- (a / b) = (-a) / b"
by (simp add: divide_inverse)
lemma nonzero_minus_divide_right: "b \<noteq> 0 \<Longrightarrow> - (a / b) = a / (- b)"
by (simp add: divide_inverse nonzero_inverse_minus_eq)
lemma nonzero_minus_divide_divide: "b \<noteq> 0 \<Longrightarrow> (-a) / (-b) = a / b"
by (simp add: divide_inverse nonzero_inverse_minus_eq)
lemma divide_minus_left [simp]: "(-a) / b = - (a / b)"
by (simp add: divide_inverse)
lemma diff_divide_distrib: "(a - b) / c = a / c - b / c"
using add_divide_distrib [of a "- b" c] by simp
lemma nonzero_eq_divide_eq [field_simps]: "c \<noteq> 0 \<Longrightarrow> a = b / c \<longleftrightarrow> a * c = b"
proof -
assume [simp]: "c \<noteq> 0"
have "a = b / c \<longleftrightarrow> a * c = (b / c) * c" by simp
also have "... \<longleftrightarrow> a * c = b" by (simp add: divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma nonzero_divide_eq_eq [field_simps]: "c \<noteq> 0 \<Longrightarrow> b / c = a \<longleftrightarrow> b = a * c"
proof -
assume [simp]: "c \<noteq> 0"
have "b / c = a \<longleftrightarrow> (b / c) * c = a * c" by simp
also have "... \<longleftrightarrow> b = a * c" by (simp add: divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma nonzero_neg_divide_eq_eq [field_simps]: "b \<noteq> 0 \<Longrightarrow> - (a / b) = c \<longleftrightarrow> - a = c * b"
using nonzero_divide_eq_eq[of b "-a" c] by simp
lemma nonzero_neg_divide_eq_eq2 [field_simps]: "b \<noteq> 0 \<Longrightarrow> c = - (a / b) \<longleftrightarrow> c * b = - a"
using nonzero_neg_divide_eq_eq[of b a c] by auto
lemma divide_eq_imp: "c \<noteq> 0 \<Longrightarrow> b = a * c \<Longrightarrow> b / c = a"
by (simp add: divide_inverse mult.assoc)
lemma eq_divide_imp: "c \<noteq> 0 \<Longrightarrow> a * c = b \<Longrightarrow> a = b / c"
by (drule sym) (simp add: divide_inverse mult.assoc)
lemma add_divide_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> x + y / z = (x * z + y) / z"
by (simp add: add_divide_distrib nonzero_eq_divide_eq)
lemma divide_add_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> x / z + y = (x + y * z) / z"
by (simp add: add_divide_distrib nonzero_eq_divide_eq)
lemma diff_divide_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> x - y / z = (x * z - y) / z"
by (simp add: diff_divide_distrib nonzero_eq_divide_eq eq_diff_eq)
lemma minus_divide_add_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> - (x / z) + y = (- x + y * z) / z"
by (simp add: add_divide_distrib diff_divide_eq_iff)
lemma divide_diff_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> x / z - y = (x - y * z) / z"
by (simp add: field_simps)
lemma minus_divide_diff_eq_iff [field_simps]:
"z \<noteq> 0 \<Longrightarrow> - (x / z) - y = (- x - y * z) / z"
by (simp add: divide_diff_eq_iff[symmetric])
lemma division_ring_divide_zero [simp]:
"a / 0 = 0"
by (simp add: divide_inverse)
lemma divide_self_if [simp]:
"a / a = (if a = 0 then 0 else 1)"
by simp
lemma inverse_nonzero_iff_nonzero [simp]:
"inverse a = 0 \<longleftrightarrow> a = 0"
by (rule iffI) (fact inverse_zero_imp_zero, simp)
lemma inverse_minus_eq [simp]:
"inverse (- a) = - inverse a"
proof cases
assume "a=0" thus ?thesis by simp
next
assume "a\<noteq>0"
thus ?thesis by (simp add: nonzero_inverse_minus_eq)
qed
lemma inverse_inverse_eq [simp]:
"inverse (inverse a) = a"
proof cases
assume "a=0" thus ?thesis by simp
next
assume "a\<noteq>0"
thus ?thesis by (simp add: nonzero_inverse_inverse_eq)
qed
lemma inverse_eq_imp_eq:
"inverse a = inverse b \<Longrightarrow> a = b"
by (drule arg_cong [where f="inverse"], simp)
lemma inverse_eq_iff_eq [simp]:
"inverse a = inverse b \<longleftrightarrow> a = b"
by (force dest!: inverse_eq_imp_eq)
lemma mult_commute_imp_mult_inverse_commute:
assumes "y * x = x * y"
shows "inverse y * x = x * inverse y"
proof (cases "y=0")
case False
hence "x * inverse y = inverse y * y * x * inverse y"
by simp
also have "\<dots> = inverse y * (x * y * inverse y)"
by (simp add: mult.assoc assms)
finally show ?thesis by (simp add: mult.assoc False)
qed simp
lemmas mult_inverse_of_nat_commute =
mult_commute_imp_mult_inverse_commute[OF mult_of_nat_commute]
lemma divide_divide_eq_left':
"(a / b) / c = a / (c * b)"
by (cases "b = 0 \<or> c = 0")
(auto simp: divide_inverse mult.assoc nonzero_inverse_mult_distrib)
lemma add_divide_eq_if_simps [field_split_simps, divide_simps]:
"a + b / z = (if z = 0 then a else (a * z + b) / z)"
"a / z + b = (if z = 0 then b else (a + b * z) / z)"
"- (a / z) + b = (if z = 0 then b else (-a + b * z) / z)"
"a - b / z = (if z = 0 then a else (a * z - b) / z)"
"a / z - b = (if z = 0 then -b else (a - b * z) / z)"
"- (a / z) - b = (if z = 0 then -b else (- a - b * z) / z)"
by (simp_all add: add_divide_eq_iff divide_add_eq_iff diff_divide_eq_iff divide_diff_eq_iff
minus_divide_diff_eq_iff)
lemma [field_split_simps, divide_simps]:
shows divide_eq_eq: "b / c = a \<longleftrightarrow> (if c \<noteq> 0 then b = a * c else a = 0)"
and eq_divide_eq: "a = b / c \<longleftrightarrow> (if c \<noteq> 0 then a * c = b else a = 0)"
and minus_divide_eq_eq: "- (b / c) = a \<longleftrightarrow> (if c \<noteq> 0 then - b = a * c else a = 0)"
and eq_minus_divide_eq: "a = - (b / c) \<longleftrightarrow> (if c \<noteq> 0 then a * c = - b else a = 0)"
by (auto simp add: field_simps)
end
subsection \<open>Fields\<close>
class field = comm_ring_1 + inverse +
assumes field_inverse: "a \<noteq> 0 \<Longrightarrow> inverse a * a = 1"
assumes field_divide_inverse: "a / b = a * inverse b"
assumes field_inverse_zero: "inverse 0 = 0"
begin
subclass division_ring
proof
fix a :: 'a
assume "a \<noteq> 0"
thus "inverse a * a = 1" by (rule field_inverse)
thus "a * inverse a = 1" by (simp only: mult.commute)
next
fix a b :: 'a
show "a / b = a * inverse b" by (rule field_divide_inverse)
next
show "inverse 0 = 0"
by (fact field_inverse_zero)
qed
subclass idom_divide
proof
fix b a
assume "b \<noteq> 0"
then show "a * b / b = a"
by (simp add: divide_inverse ac_simps)
next
fix a
show "a / 0 = 0"
by (simp add: divide_inverse)
qed
text\<open>There is no slick version using division by zero.\<close>
lemma inverse_add:
"a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> inverse a + inverse b = (a + b) * inverse a * inverse b"
by (simp add: division_ring_inverse_add ac_simps)
lemma nonzero_mult_divide_mult_cancel_left [simp]:
assumes [simp]: "c \<noteq> 0"
shows "(c * a) / (c * b) = a / b"
proof (cases "b = 0")
case True then show ?thesis by simp
next
case False
then have "(c*a)/(c*b) = c * a * (inverse b * inverse c)"
by (simp add: divide_inverse nonzero_inverse_mult_distrib)
also have "... = a * inverse b * (inverse c * c)"
by (simp only: ac_simps)
also have "... = a * inverse b" by simp
finally show ?thesis by (simp add: divide_inverse)
qed
lemma nonzero_mult_divide_mult_cancel_right [simp]:
"c \<noteq> 0 \<Longrightarrow> (a * c) / (b * c) = a / b"
using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)
lemma times_divide_eq_left [simp]: "(b / c) * a = (b * a) / c"
by (simp add: divide_inverse ac_simps)
lemma divide_inverse_commute: "a / b = inverse b * a"
by (simp add: divide_inverse mult.commute)
lemma add_frac_eq:
assumes "y \<noteq> 0" and "z \<noteq> 0"
shows "x / y + w / z = (x * z + w * y) / (y * z)"
proof -
have "x / y + w / z = (x * z) / (y * z) + (y * w) / (y * z)"
using assms by simp
also have "\<dots> = (x * z + y * w) / (y * z)"
by (simp only: add_divide_distrib)
finally show ?thesis
by (simp only: mult.commute)
qed
text\<open>Special Cancellation Simprules for Division\<close>
lemma nonzero_divide_mult_cancel_right [simp]:
"b \<noteq> 0 \<Longrightarrow> b / (a * b) = 1 / a"
using nonzero_mult_divide_mult_cancel_right [of b 1 a] by simp
lemma nonzero_divide_mult_cancel_left [simp]:
"a \<noteq> 0 \<Longrightarrow> a / (a * b) = 1 / b"
using nonzero_mult_divide_mult_cancel_left [of a 1 b] by simp
lemma nonzero_mult_divide_mult_cancel_left2 [simp]:
"c \<noteq> 0 \<Longrightarrow> (c * a) / (b * c) = a / b"
using nonzero_mult_divide_mult_cancel_left [of c a b] by (simp add: ac_simps)
lemma nonzero_mult_divide_mult_cancel_right2 [simp]:
"c \<noteq> 0 \<Longrightarrow> (a * c) / (c * b) = a / b"
using nonzero_mult_divide_mult_cancel_right [of b c a] by (simp add: ac_simps)
lemma diff_frac_eq:
"y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y - w / z = (x * z - w * y) / (y * z)"
by (simp add: field_simps)
lemma frac_eq_eq:
"y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> (x / y = w / z) = (x * z = w * y)"
by (simp add: field_simps)
lemma divide_minus1 [simp]: "x / - 1 = - x"
using nonzero_minus_divide_right [of "1" x] by simp
text\<open>This version builds in division by zero while also re-orienting
the right-hand side.\<close>
lemma inverse_mult_distrib [simp]:
"inverse (a * b) = inverse a * inverse b"
proof cases
assume "a \<noteq> 0 \<and> b \<noteq> 0"
thus ?thesis by (simp add: nonzero_inverse_mult_distrib ac_simps)
next
assume "\<not> (a \<noteq> 0 \<and> b \<noteq> 0)"
thus ?thesis by force
qed
lemma inverse_divide [simp]:
"inverse (a / b) = b / a"
by (simp add: divide_inverse mult.commute)
text \<open>Calculations with fractions\<close>
text\<open>There is a whole bunch of simp-rules just for class \<open>field\<close> but none for class \<open>field\<close> and \<open>nonzero_divides\<close>
because the latter are covered by a simproc.\<close>
lemmas mult_divide_mult_cancel_left = nonzero_mult_divide_mult_cancel_left
lemmas mult_divide_mult_cancel_right = nonzero_mult_divide_mult_cancel_right
lemma divide_divide_eq_right [simp]:
"a / (b / c) = (a * c) / b"
by (simp add: divide_inverse ac_simps)
lemma divide_divide_eq_left [simp]:
"(a / b) / c = a / (b * c)"
by (simp add: divide_inverse mult.assoc)
lemma divide_divide_times_eq:
"(x / y) / (z / w) = (x * w) / (y * z)"
by simp
text \<open>Special Cancellation Simprules for Division\<close>
lemma mult_divide_mult_cancel_left_if [simp]:
shows "(c * a) / (c * b) = (if c = 0 then 0 else a / b)"
by simp
text \<open>Division and Unary Minus\<close>
lemma minus_divide_right:
"- (a / b) = a / - b"
by (simp add: divide_inverse)
lemma divide_minus_right [simp]:
"a / - b = - (a / b)"
by (simp add: divide_inverse)
lemma minus_divide_divide:
"(- a) / (- b) = a / b"
by (cases "b=0") (simp_all add: nonzero_minus_divide_divide)
lemma inverse_eq_1_iff [simp]:
"inverse x = 1 \<longleftrightarrow> x = 1"
using inverse_eq_iff_eq [of x 1] by simp
lemma divide_eq_0_iff [simp]:
"a / b = 0 \<longleftrightarrow> a = 0 \<or> b = 0"
by (simp add: divide_inverse)
lemma divide_cancel_right [simp]:
"a / c = b / c \<longleftrightarrow> c = 0 \<or> a = b"
by (cases "c=0") (simp_all add: divide_inverse)
lemma divide_cancel_left [simp]:
"c / a = c / b \<longleftrightarrow> c = 0 \<or> a = b"
by (cases "c=0") (simp_all add: divide_inverse)
lemma divide_eq_1_iff [simp]:
"a / b = 1 \<longleftrightarrow> b \<noteq> 0 \<and> a = b"
by (cases "b=0") (simp_all add: right_inverse_eq)
lemma one_eq_divide_iff [simp]:
"1 = a / b \<longleftrightarrow> b \<noteq> 0 \<and> a = b"
by (simp add: eq_commute [of 1])
lemma divide_eq_minus_1_iff:
"(a / b = - 1) \<longleftrightarrow> b \<noteq> 0 \<and> a = - b"
using divide_eq_1_iff by fastforce
lemma times_divide_times_eq:
"(x / y) * (z / w) = (x * z) / (y * w)"
by simp
lemma add_frac_num:
"y \<noteq> 0 \<Longrightarrow> x / y + z = (x + z * y) / y"
by (simp add: add_divide_distrib)
lemma add_num_frac:
"y \<noteq> 0 \<Longrightarrow> z + x / y = (x + z * y) / y"
by (simp add: add_divide_distrib add.commute)
lemma dvd_field_iff:
"a dvd b \<longleftrightarrow> (a = 0 \<longrightarrow> b = 0)"
proof (cases "a = 0")
case False
then have "b = a * (b / a)"
by (simp add: field_simps)
then have "a dvd b" ..
with False show ?thesis
by simp
qed simp
lemma inj_divide_right [simp]:
"inj (\<lambda>b. b / a) \<longleftrightarrow> a \<noteq> 0"
proof -
have "(\<lambda>b. b / a) = (*) (inverse a)"
by (simp add: field_simps fun_eq_iff)
then have "inj (\<lambda>y. y / a) \<longleftrightarrow> inj ((*) (inverse a))"
by simp
also have "\<dots> \<longleftrightarrow> inverse a \<noteq> 0"
by simp
also have "\<dots> \<longleftrightarrow> a \<noteq> 0"
by simp
finally show ?thesis
by simp
qed
end
class field_char_0 = field + ring_char_0
subsection \<open>Ordered fields\<close>
class field_abs_sgn = field + idom_abs_sgn
begin
lemma sgn_inverse [simp]:
"sgn (inverse a) = inverse (sgn a)"
proof (cases "a = 0")
case True then show ?thesis by simp
next
case False
then have "a * inverse a = 1"
by simp
then have "sgn (a * inverse a) = sgn 1"
by simp
then have "sgn a * sgn (inverse a) = 1"
by (simp add: sgn_mult)
then have "inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1"
by simp
then have "(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)"
by (simp add: ac_simps)
with False show ?thesis
by (simp add: sgn_eq_0_iff)
qed
lemma abs_inverse [simp]:
"\<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
proof -
from sgn_mult_abs [of "inverse a"] sgn_mult_abs [of a]
have "inverse (sgn a) * \<bar>inverse a\<bar> = inverse (sgn a * \<bar>a\<bar>)"
by simp
then show ?thesis by (auto simp add: sgn_eq_0_iff)
qed
lemma sgn_divide [simp]:
"sgn (a / b) = sgn a / sgn b"
unfolding divide_inverse sgn_mult by simp
lemma abs_divide [simp]:
"\<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
unfolding divide_inverse abs_mult by simp
end
class linordered_field = field + linordered_idom
begin
lemma positive_imp_inverse_positive:
assumes a_gt_0: "0 < a"
shows "0 < inverse a"
proof -
have "0 < a * inverse a"
by (simp add: a_gt_0 [THEN less_imp_not_eq2])
thus "0 < inverse a"
by (simp add: a_gt_0 [THEN less_not_sym] zero_less_mult_iff)
qed
lemma negative_imp_inverse_negative:
"a < 0 \<Longrightarrow> inverse a < 0"
using positive_imp_inverse_positive [of "-a"]
by (simp add: nonzero_inverse_minus_eq less_imp_not_eq)
lemma inverse_le_imp_le:
assumes invle: "inverse a \<le> inverse b" and apos: "0 < a"
shows "b \<le> a"
proof (rule classical)
assume "\<not> b \<le> a"
hence "a < b" by (simp add: linorder_not_le)
hence bpos: "0 < b" by (blast intro: apos less_trans)
hence "a * inverse a \<le> a * inverse b"
by (simp add: apos invle less_imp_le mult_left_mono)
hence "(a * inverse a) * b \<le> (a * inverse b) * b"
by (simp add: bpos less_imp_le mult_right_mono)
thus "b \<le> a" by (simp add: mult.assoc apos bpos less_imp_not_eq2)
qed
lemma inverse_positive_imp_positive:
assumes inv_gt_0: "0 < inverse a" and nz: "a \<noteq> 0"
shows "0 < a"
proof -
have "0 < inverse (inverse a)"
using inv_gt_0 by (rule positive_imp_inverse_positive)
thus "0 < a"
using nz by (simp add: nonzero_inverse_inverse_eq)
qed
lemma inverse_negative_imp_negative:
assumes inv_less_0: "inverse a < 0" and nz: "a \<noteq> 0"
shows "a < 0"
proof -
have "inverse (inverse a) < 0"
using inv_less_0 by (rule negative_imp_inverse_negative)
thus "a < 0" using nz by (simp add: nonzero_inverse_inverse_eq)
qed
lemma linordered_field_no_lb:
"\<forall>x. \<exists>y. y < x"
proof
fix x::'a
have m1: "- (1::'a) < 0" by simp
from add_strict_right_mono[OF m1, where c=x]
have "(- 1) + x < x" by simp
thus "\<exists>y. y < x" by blast
qed
lemma linordered_field_no_ub:
"\<forall> x. \<exists>y. y > x"
proof
fix x::'a
have m1: " (1::'a) > 0" by simp
from add_strict_right_mono[OF m1, where c=x]
have "1 + x > x" by simp
thus "\<exists>y. y > x" by blast
qed
lemma less_imp_inverse_less:
assumes less: "a < b" and apos: "0 < a"
shows "inverse b < inverse a"
proof (rule ccontr)
assume "\<not> inverse b < inverse a"
hence "inverse a \<le> inverse b" by simp
hence "\<not> (a < b)"
by (simp add: not_less inverse_le_imp_le [OF _ apos])
thus False by (rule notE [OF _ less])
qed
lemma inverse_less_imp_less:
assumes "inverse a < inverse b" "0 < a"
shows "b < a"
proof -
have "a \<noteq> b"
using assms by (simp add: less_le)
moreover have "b \<le> a"
using assms by (force simp: less_le dest: inverse_le_imp_le)
ultimately show ?thesis
by (simp add: less_le)
qed
text\<open>Both premises are essential. Consider -1 and 1.\<close>
lemma inverse_less_iff_less [simp]:
"0 < a \<Longrightarrow> 0 < b \<Longrightarrow> inverse a < inverse b \<longleftrightarrow> b < a"
by (blast intro: less_imp_inverse_less dest: inverse_less_imp_less)
lemma le_imp_inverse_le:
"a \<le> b \<Longrightarrow> 0 < a \<Longrightarrow> inverse b \<le> inverse a"
by (force simp add: le_less less_imp_inverse_less)
lemma inverse_le_iff_le [simp]:
"0 < a \<Longrightarrow> 0 < b \<Longrightarrow> inverse a \<le> inverse b \<longleftrightarrow> b \<le> a"
by (blast intro: le_imp_inverse_le dest: inverse_le_imp_le)
text\<open>These results refer to both operands being negative. The opposite-sign
case is trivial, since inverse preserves signs.\<close>
lemma inverse_le_imp_le_neg:
assumes "inverse a \<le> inverse b" "b < 0"
shows "b \<le> a"
proof (rule classical)
assume "\<not> b \<le> a"
with \<open>b < 0\<close> have "a < 0"
by force
with assms show "b \<le> a"
using inverse_le_imp_le [of "-b" "-a"] by (simp add: nonzero_inverse_minus_eq)
qed
lemma less_imp_inverse_less_neg:
assumes "a < b" "b < 0"
shows "inverse b < inverse a"
proof -
have "a < 0"
using assms by (blast intro: less_trans)
with less_imp_inverse_less [of "-b" "-a"] show ?thesis
by (simp add: nonzero_inverse_minus_eq assms)
qed
lemma inverse_less_imp_less_neg:
assumes "inverse a < inverse b" "b < 0"
shows "b < a"
proof (rule classical)
assume "\<not> b < a"
with \<open>b < 0\<close> have "a < 0"
by force
with inverse_less_imp_less [of "-b" "-a"] show ?thesis
by (simp add: nonzero_inverse_minus_eq assms)
qed
lemma inverse_less_iff_less_neg [simp]:
"a < 0 \<Longrightarrow> b < 0 \<Longrightarrow> inverse a < inverse b \<longleftrightarrow> b < a"
using inverse_less_iff_less [of "-b" "-a"]
by (simp del: inverse_less_iff_less add: nonzero_inverse_minus_eq)
lemma le_imp_inverse_le_neg:
"a \<le> b \<Longrightarrow> b < 0 \<Longrightarrow> inverse b \<le> inverse a"
by (force simp add: le_less less_imp_inverse_less_neg)
lemma inverse_le_iff_le_neg [simp]:
"a < 0 \<Longrightarrow> b < 0 \<Longrightarrow> inverse a \<le> inverse b \<longleftrightarrow> b \<le> a"
by (blast intro: le_imp_inverse_le_neg dest: inverse_le_imp_le_neg)
lemma one_less_inverse:
"0 < a \<Longrightarrow> a < 1 \<Longrightarrow> 1 < inverse a"
using less_imp_inverse_less [of a 1, unfolded inverse_1] .
lemma one_le_inverse:
"0 < a \<Longrightarrow> a \<le> 1 \<Longrightarrow> 1 \<le> inverse a"
using le_imp_inverse_le [of a 1, unfolded inverse_1] .
lemma pos_le_divide_eq [field_simps]:
assumes "0 < c"
shows "a \<le> b / c \<longleftrightarrow> a * c \<le> b"
proof -
from assms have "a \<le> b / c \<longleftrightarrow> a * c \<le> (b / c) * c"
using mult_le_cancel_right [of a c "b * inverse c"] by (auto simp add: field_simps)
also have "... \<longleftrightarrow> a * c \<le> b"
by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma pos_less_divide_eq [field_simps]:
assumes "0 < c"
shows "a < b / c \<longleftrightarrow> a * c < b"
proof -
from assms have "a < b / c \<longleftrightarrow> a * c < (b / c) * c"
using mult_less_cancel_right [of a c "b / c"] by auto
also have "... = (a*c < b)"
by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma neg_less_divide_eq [field_simps]:
assumes "c < 0"
shows "a < b / c \<longleftrightarrow> b < a * c"
proof -
from assms have "a < b / c \<longleftrightarrow> (b / c) * c < a * c"
using mult_less_cancel_right [of "b / c" c a] by auto
also have "... \<longleftrightarrow> b < a * c"
by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma neg_le_divide_eq [field_simps]:
assumes "c < 0"
shows "a \<le> b / c \<longleftrightarrow> b \<le> a * c"
proof -
from assms have "a \<le> b / c \<longleftrightarrow> (b / c) * c \<le> a * c"
using mult_le_cancel_right [of "b * inverse c" c a] by (auto simp add: field_simps)
also have "... \<longleftrightarrow> b \<le> a * c"
by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma pos_divide_le_eq [field_simps]:
assumes "0 < c"
shows "b / c \<le> a \<longleftrightarrow> b \<le> a * c"
proof -
from assms have "b / c \<le> a \<longleftrightarrow> (b / c) * c \<le> a * c"
using mult_le_cancel_right [of "b / c" c a] by auto
also have "... \<longleftrightarrow> b \<le> a * c"
by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma pos_divide_less_eq [field_simps]:
assumes "0 < c"
shows "b / c < a \<longleftrightarrow> b < a * c"
proof -
from assms have "b / c < a \<longleftrightarrow> (b / c) * c < a * c"
using mult_less_cancel_right [of "b / c" c a] by auto
also have "... \<longleftrightarrow> b < a * c"
by (simp add: less_imp_not_eq2 [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma neg_divide_le_eq [field_simps]:
assumes "c < 0"
shows "b / c \<le> a \<longleftrightarrow> a * c \<le> b"
proof -
from assms have "b / c \<le> a \<longleftrightarrow> a * c \<le> (b / c) * c"
using mult_le_cancel_right [of a c "b / c"] by auto
also have "... \<longleftrightarrow> a * c \<le> b"
by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
lemma neg_divide_less_eq [field_simps]:
assumes "c < 0"
shows "b / c < a \<longleftrightarrow> a * c < b"
proof -
from assms have "b / c < a \<longleftrightarrow> a * c < b / c * c"
using mult_less_cancel_right [of a c "b / c"] by auto
also have "... \<longleftrightarrow> a * c < b"
by (simp add: less_imp_not_eq [OF assms] divide_inverse mult.assoc)
finally show ?thesis .
qed
text\<open>The following \<open>field_simps\<close> rules are necessary, as minus is always moved atop of
division but we want to get rid of division.\<close>
lemma pos_le_minus_divide_eq [field_simps]: "0 < c \<Longrightarrow> a \<le> - (b / c) \<longleftrightarrow> a * c \<le> - b"
unfolding minus_divide_left by (rule pos_le_divide_eq)
lemma neg_le_minus_divide_eq [field_simps]: "c < 0 \<Longrightarrow> a \<le> - (b / c) \<longleftrightarrow> - b \<le> a * c"
unfolding minus_divide_left by (rule neg_le_divide_eq)
lemma pos_less_minus_divide_eq [field_simps]: "0 < c \<Longrightarrow> a < - (b / c) \<longleftrightarrow> a * c < - b"
unfolding minus_divide_left by (rule pos_less_divide_eq)
lemma neg_less_minus_divide_eq [field_simps]: "c < 0 \<Longrightarrow> a < - (b / c) \<longleftrightarrow> - b < a * c"
unfolding minus_divide_left by (rule neg_less_divide_eq)
lemma pos_minus_divide_less_eq [field_simps]: "0 < c \<Longrightarrow> - (b / c) < a \<longleftrightarrow> - b < a * c"
unfolding minus_divide_left by (rule pos_divide_less_eq)
lemma neg_minus_divide_less_eq [field_simps]: "c < 0 \<Longrightarrow> - (b / c) < a \<longleftrightarrow> a * c < - b"
unfolding minus_divide_left by (rule neg_divide_less_eq)
lemma pos_minus_divide_le_eq [field_simps]: "0 < c \<Longrightarrow> - (b / c) \<le> a \<longleftrightarrow> - b \<le> a * c"
unfolding minus_divide_left by (rule pos_divide_le_eq)
lemma neg_minus_divide_le_eq [field_simps]: "c < 0 \<Longrightarrow> - (b / c) \<le> a \<longleftrightarrow> a * c \<le> - b"
unfolding minus_divide_left by (rule neg_divide_le_eq)
lemma frac_less_eq:
"y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y < w / z \<longleftrightarrow> (x * z - w * y) / (y * z) < 0"
by (subst less_iff_diff_less_0) (simp add: diff_frac_eq )
lemma frac_le_eq:
"y \<noteq> 0 \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> x / y \<le> w / z \<longleftrightarrow> (x * z - w * y) / (y * z) \<le> 0"
by (subst le_iff_diff_le_0) (simp add: diff_frac_eq )
lemma divide_pos_pos[simp]:
"0 < x \<Longrightarrow> 0 < y \<Longrightarrow> 0 < x / y"
by(simp add:field_simps)
lemma divide_nonneg_pos:
"0 \<le> x \<Longrightarrow> 0 < y \<Longrightarrow> 0 \<le> x / y"
by(simp add:field_simps)
lemma divide_neg_pos:
"x < 0 \<Longrightarrow> 0 < y \<Longrightarrow> x / y < 0"
by(simp add:field_simps)
lemma divide_nonpos_pos:
"x \<le> 0 \<Longrightarrow> 0 < y \<Longrightarrow> x / y \<le> 0"
by(simp add:field_simps)
lemma divide_pos_neg:
"0 < x \<Longrightarrow> y < 0 \<Longrightarrow> x / y < 0"
by(simp add:field_simps)
lemma divide_nonneg_neg:
"0 \<le> x \<Longrightarrow> y < 0 \<Longrightarrow> x / y \<le> 0"
by(simp add:field_simps)
lemma divide_neg_neg:
"x < 0 \<Longrightarrow> y < 0 \<Longrightarrow> 0 < x / y"
by(simp add:field_simps)
lemma divide_nonpos_neg:
"x \<le> 0 \<Longrightarrow> y < 0 \<Longrightarrow> 0 \<le> x / y"
by(simp add:field_simps)
lemma divide_strict_right_mono:
"\<lbrakk>a < b; 0 < c\<rbrakk> \<Longrightarrow> a / c < b / c"
by (simp add: less_imp_not_eq2 divide_inverse mult_strict_right_mono
positive_imp_inverse_positive)
lemma divide_strict_right_mono_neg:
assumes "b < a" "c < 0" shows "a / c < b / c"
proof -
have "b / - c < a / - c"
by (rule divide_strict_right_mono) (use assms in auto)
then show ?thesis
by (simp add: less_imp_not_eq)
qed
text\<open>The last premise ensures that \<^term>\<open>a\<close> and \<^term>\<open>b\<close>
have the same sign\<close>
lemma divide_strict_left_mono:
"\<lbrakk>b < a; 0 < c; 0 < a*b\<rbrakk> \<Longrightarrow> c / a < c / b"
by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono)
lemma divide_left_mono:
"\<lbrakk>b \<le> a; 0 \<le> c; 0 < a*b\<rbrakk> \<Longrightarrow> c / a \<le> c / b"
by (auto simp: field_simps zero_less_mult_iff mult_right_mono)
lemma divide_strict_left_mono_neg:
"\<lbrakk>a < b; c < 0; 0 < a*b\<rbrakk> \<Longrightarrow> c / a < c / b"
by (auto simp: field_simps zero_less_mult_iff mult_strict_right_mono_neg)
lemma mult_imp_div_pos_le: "0 < y \<Longrightarrow> x \<le> z * y \<Longrightarrow> x / y \<le> z"
by (subst pos_divide_le_eq, assumption+)
lemma mult_imp_le_div_pos: "0 < y \<Longrightarrow> z * y \<le> x \<Longrightarrow> z \<le> x / y"
by(simp add:field_simps)
lemma mult_imp_div_pos_less: "0 < y \<Longrightarrow> x < z * y \<Longrightarrow> x / y < z"
by(simp add:field_simps)
lemma mult_imp_less_div_pos: "0 < y \<Longrightarrow> z * y < x \<Longrightarrow> z < x / y"
by(simp add:field_simps)
lemma frac_le:
assumes "0 \<le> y" "x \<le> y" "0 < w" "w \<le> z"
shows "x / z \<le> y / w"
proof (rule mult_imp_div_pos_le)
show "z > 0"
using assms by simp
have "x \<le> y * z / w"
proof (rule mult_imp_le_div_pos [OF \<open>0 < w\<close>])
show "x * w \<le> y * z"
using assms by (auto intro: mult_mono)
qed
also have "... = y / w * z"
by simp
finally show "x \<le> y / w * z" .
qed
lemma frac_less:
assumes "0 \<le> x" "x < y" "0 < w" "w \<le> z"
shows "x / z < y / w"
proof (rule mult_imp_div_pos_less)
show "z > 0"
using assms by simp
have "x < y * z / w"
proof (rule mult_imp_less_div_pos [OF \<open>0 < w\<close>])
show "x * w < y * z"
using assms by (auto intro: mult_less_le_imp_less)
qed
also have "... = y / w * z"
by simp
finally show "x < y / w * z" .
qed
lemma frac_less2:
assumes "0 < x" "x \<le> y" "0 < w" "w < z"
shows "x / z < y / w"
proof (rule mult_imp_div_pos_less)
show "z > 0"
using assms by simp
show "x < y / w * z"
using assms by (force intro: mult_imp_less_div_pos mult_le_less_imp_less)
qed
lemma less_half_sum: "a < b \<Longrightarrow> a < (a+b) / (1+1)"
by (simp add: field_simps zero_less_two)
lemma gt_half_sum: "a < b \<Longrightarrow> (a+b)/(1+1) < b"
by (simp add: field_simps zero_less_two)
subclass unbounded_dense_linorder
proof
fix x y :: 'a
from less_add_one show "\<exists>y. x < y" ..
from less_add_one have "x + (- 1) < (x + 1) + (- 1)" by (rule add_strict_right_mono)
then have "x - 1 < x + 1 - 1" by simp
then have "x - 1 < x" by (simp add: algebra_simps)
then show "\<exists>y. y < x" ..
show "x < y \<Longrightarrow> \<exists>z>x. z < y" by (blast intro!: less_half_sum gt_half_sum)
qed
subclass field_abs_sgn ..
lemma inverse_sgn [simp]:
"inverse (sgn a) = sgn a"
by (cases a 0 rule: linorder_cases) simp_all
lemma divide_sgn [simp]:
"a / sgn b = a * sgn b"
by (cases b 0 rule: linorder_cases) simp_all
lemma nonzero_abs_inverse:
"a \<noteq> 0 \<Longrightarrow> \<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
by (rule abs_inverse)
lemma nonzero_abs_divide:
"b \<noteq> 0 \<Longrightarrow> \<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
by (rule abs_divide)
lemma field_le_epsilon:
assumes e: "\<And>e. 0 < e \<Longrightarrow> x \<le> y + e"
shows "x \<le> y"
proof (rule dense_le)
fix t assume "t < x"
hence "0 < x - t" by (simp add: less_diff_eq)
from e [OF this] have "x + 0 \<le> x + (y - t)" by (simp add: algebra_simps)
then have "0 \<le> y - t" by (simp only: add_le_cancel_left)
then show "t \<le> y" by (simp add: algebra_simps)
qed
lemma inverse_positive_iff_positive [simp]: "(0 < inverse a) = (0 < a)"
proof (cases "a = 0")
case False
then show ?thesis
by (blast intro: inverse_positive_imp_positive positive_imp_inverse_positive)
qed auto
lemma inverse_negative_iff_negative [simp]: "(inverse a < 0) = (a < 0)"
proof (cases "a = 0")
case False
then show ?thesis
by (blast intro: inverse_negative_imp_negative negative_imp_inverse_negative)
qed auto
lemma inverse_nonnegative_iff_nonnegative [simp]: "0 \<le> inverse a \<longleftrightarrow> 0 \<le> a"
by (simp add: not_less [symmetric])
lemma inverse_nonpositive_iff_nonpositive [simp]: "inverse a \<le> 0 \<longleftrightarrow> a \<le> 0"
by (simp add: not_less [symmetric])
lemma one_less_inverse_iff: "1 < inverse x \<longleftrightarrow> 0 < x \<and> x < 1"
using less_trans[of 1 x 0 for x]
by (cases x 0 rule: linorder_cases) (auto simp add: field_simps)
lemma one_le_inverse_iff: "1 \<le> inverse x \<longleftrightarrow> 0 < x \<and> x \<le> 1"
proof (cases "x = 1")
case True then show ?thesis by simp
next
case False then have "inverse x \<noteq> 1" by simp
then have "1 \<noteq> inverse x" by blast
then have "1 \<le> inverse x \<longleftrightarrow> 1 < inverse x" by (simp add: le_less)
with False show ?thesis by (auto simp add: one_less_inverse_iff)
qed
lemma inverse_less_1_iff: "inverse x < 1 \<longleftrightarrow> x \<le> 0 \<or> 1 < x"
by (simp add: not_le [symmetric] one_le_inverse_iff)
lemma inverse_le_1_iff: "inverse x \<le> 1 \<longleftrightarrow> x \<le> 0 \<or> 1 \<le> x"
by (simp add: not_less [symmetric] one_less_inverse_iff)
lemma [field_split_simps, divide_simps]:
shows le_divide_eq: "a \<le> b / c \<longleftrightarrow> (if 0 < c then a * c \<le> b else if c < 0 then b \<le> a * c else a \<le> 0)"
and divide_le_eq: "b / c \<le> a \<longleftrightarrow> (if 0 < c then b \<le> a * c else if c < 0 then a * c \<le> b else 0 \<le> a)"
and less_divide_eq: "a < b / c \<longleftrightarrow> (if 0 < c then a * c < b else if c < 0 then b < a * c else a < 0)"
and divide_less_eq: "b / c < a \<longleftrightarrow> (if 0 < c then b < a * c else if c < 0 then a * c < b else 0 < a)"
and le_minus_divide_eq: "a \<le> - (b / c) \<longleftrightarrow> (if 0 < c then a * c \<le> - b else if c < 0 then - b \<le> a * c else a \<le> 0)"
and minus_divide_le_eq: "- (b / c) \<le> a \<longleftrightarrow> (if 0 < c then - b \<le> a * c else if c < 0 then a * c \<le> - b else 0 \<le> a)"
and less_minus_divide_eq: "a < - (b / c) \<longleftrightarrow> (if 0 < c then a * c < - b else if c < 0 then - b < a * c else a < 0)"
and minus_divide_less_eq: "- (b / c) < a \<longleftrightarrow> (if 0 < c then - b < a * c else if c < 0 then a * c < - b else 0 < a)"
by (auto simp: field_simps not_less dest: order.antisym)
text \<open>Division and Signs\<close>
lemma
shows zero_less_divide_iff: "0 < a / b \<longleftrightarrow> 0 < a \<and> 0 < b \<or> a < 0 \<and> b < 0"
and divide_less_0_iff: "a / b < 0 \<longleftrightarrow> 0 < a \<and> b < 0 \<or> a < 0 \<and> 0 < b"
and zero_le_divide_iff: "0 \<le> a / b \<longleftrightarrow> 0 \<le> a \<and> 0 \<le> b \<or> a \<le> 0 \<and> b \<le> 0"
and divide_le_0_iff: "a / b \<le> 0 \<longleftrightarrow> 0 \<le> a \<and> b \<le> 0 \<or> a \<le> 0 \<and> 0 \<le> b"
by (auto simp add: field_split_simps)
text \<open>Division and the Number One\<close>
text\<open>Simplify expressions equated with 1\<close>
lemma zero_eq_1_divide_iff [simp]: "0 = 1 / a \<longleftrightarrow> a = 0"
by (cases "a = 0") (auto simp: field_simps)
lemma one_divide_eq_0_iff [simp]: "1 / a = 0 \<longleftrightarrow> a = 0"
using zero_eq_1_divide_iff[of a] by simp
text\<open>Simplify expressions such as \<open>0 < 1/x\<close> to \<open>0 < x\<close>\<close>
lemma zero_le_divide_1_iff [simp]:
"0 \<le> 1 / a \<longleftrightarrow> 0 \<le> a"
by (simp add: zero_le_divide_iff)
lemma zero_less_divide_1_iff [simp]:
"0 < 1 / a \<longleftrightarrow> 0 < a"
by (simp add: zero_less_divide_iff)
lemma divide_le_0_1_iff [simp]:
"1 / a \<le> 0 \<longleftrightarrow> a \<le> 0"
by (simp add: divide_le_0_iff)
lemma divide_less_0_1_iff [simp]:
"1 / a < 0 \<longleftrightarrow> a < 0"
by (simp add: divide_less_0_iff)
lemma divide_right_mono:
"\<lbrakk>a \<le> b; 0 \<le> c\<rbrakk> \<Longrightarrow> a/c \<le> b/c"
by (force simp add: divide_strict_right_mono le_less)
lemma divide_right_mono_neg: "a \<le> b \<Longrightarrow> c \<le> 0 \<Longrightarrow> b / c \<le> a / c"
by (auto dest: divide_right_mono [of _ _ "- c"])
lemma divide_left_mono_neg: "a \<le> b \<Longrightarrow> c \<le> 0 \<Longrightarrow> 0 < a * b \<Longrightarrow> c / a \<le> c / b"
by (auto simp add: mult.commute dest: divide_left_mono [of _ _ "- c"])
lemma inverse_le_iff: "inverse a \<le> inverse b \<longleftrightarrow> (0 < a * b \<longrightarrow> b \<le> a) \<and> (a * b \<le> 0 \<longrightarrow> a \<le> b)"
by (cases a 0 b 0 rule: linorder_cases[case_product linorder_cases])
(auto simp add: field_simps zero_less_mult_iff mult_le_0_iff)
lemma inverse_less_iff: "inverse a < inverse b \<longleftrightarrow> (0 < a * b \<longrightarrow> b < a) \<and> (a * b \<le> 0 \<longrightarrow> a < b)"
by (subst less_le) (auto simp: inverse_le_iff)
lemma divide_le_cancel: "a / c \<le> b / c \<longleftrightarrow> (0 < c \<longrightarrow> a \<le> b) \<and> (c < 0 \<longrightarrow> b \<le> a)"
by (simp add: divide_inverse mult_le_cancel_right)
lemma divide_less_cancel: "a / c < b / c \<longleftrightarrow> (0 < c \<longrightarrow> a < b) \<and> (c < 0 \<longrightarrow> b < a) \<and> c \<noteq> 0"
by (auto simp add: divide_inverse mult_less_cancel_right)
text\<open>Simplify quotients that are compared with the value 1.\<close>
lemma le_divide_eq_1:
"(1 \<le> b / a) = ((0 < a \<and> a \<le> b) \<or> (a < 0 \<and> b \<le> a))"
by (auto simp add: le_divide_eq)
lemma divide_le_eq_1:
"(b / a \<le> 1) = ((0 < a \<and> b \<le> a) \<or> (a < 0 \<and> a \<le> b) \<or> a=0)"
by (auto simp add: divide_le_eq)
lemma less_divide_eq_1:
"(1 < b / a) = ((0 < a \<and> a < b) \<or> (a < 0 \<and> b < a))"
by (auto simp add: less_divide_eq)
lemma divide_less_eq_1:
"(b / a < 1) = ((0 < a \<and> b < a) \<or> (a < 0 \<and> a < b) \<or> a=0)"
by (auto simp add: divide_less_eq)
lemma divide_nonneg_nonneg [simp]:
"0 \<le> x \<Longrightarrow> 0 \<le> y \<Longrightarrow> 0 \<le> x / y"
by (auto simp add: field_split_simps)
lemma divide_nonpos_nonpos:
"x \<le> 0 \<Longrightarrow> y \<le> 0 \<Longrightarrow> 0 \<le> x / y"
by (auto simp add: field_split_simps)
lemma divide_nonneg_nonpos:
"0 \<le> x \<Longrightarrow> y \<le> 0 \<Longrightarrow> x / y \<le> 0"
by (auto simp add: field_split_simps)
lemma divide_nonpos_nonneg:
"x \<le> 0 \<Longrightarrow> 0 \<le> y \<Longrightarrow> x / y \<le> 0"
by (auto simp add: field_split_simps)
text \<open>Conditional Simplification Rules: No Case Splits\<close>
lemma le_divide_eq_1_pos [simp]:
"0 < a \<Longrightarrow> (1 \<le> b/a) = (a \<le> b)"
by (auto simp add: le_divide_eq)
lemma le_divide_eq_1_neg [simp]:
"a < 0 \<Longrightarrow> (1 \<le> b/a) = (b \<le> a)"
by (auto simp add: le_divide_eq)
lemma divide_le_eq_1_pos [simp]:
"0 < a \<Longrightarrow> (b/a \<le> 1) = (b \<le> a)"
by (auto simp add: divide_le_eq)
lemma divide_le_eq_1_neg [simp]:
"a < 0 \<Longrightarrow> (b/a \<le> 1) = (a \<le> b)"
by (auto simp add: divide_le_eq)
lemma less_divide_eq_1_pos [simp]:
"0 < a \<Longrightarrow> (1 < b/a) = (a < b)"
by (auto simp add: less_divide_eq)
lemma less_divide_eq_1_neg [simp]:
"a < 0 \<Longrightarrow> (1 < b/a) = (b < a)"
by (auto simp add: less_divide_eq)
lemma divide_less_eq_1_pos [simp]:
"0 < a \<Longrightarrow> (b/a < 1) = (b < a)"
by (auto simp add: divide_less_eq)
lemma divide_less_eq_1_neg [simp]:
"a < 0 \<Longrightarrow> b/a < 1 \<longleftrightarrow> a < b"
by (auto simp add: divide_less_eq)
lemma eq_divide_eq_1 [simp]:
"(1 = b/a) = ((a \<noteq> 0 \<and> a = b))"
by (auto simp add: eq_divide_eq)
lemma divide_eq_eq_1 [simp]:
"(b/a = 1) = ((a \<noteq> 0 \<and> a = b))"
by (auto simp add: divide_eq_eq)
lemma abs_div_pos: "0 < y \<Longrightarrow> \<bar>x\<bar> / y = \<bar>x / y\<bar>"
by (simp add: order_less_imp_le)
lemma zero_le_divide_abs_iff [simp]: "(0 \<le> a / \<bar>b\<bar>) = (0 \<le> a \<or> b = 0)"
by (auto simp: zero_le_divide_iff)
lemma divide_le_0_abs_iff [simp]: "(a / \<bar>b\<bar> \<le> 0) = (a \<le> 0 \<or> b = 0)"
by (auto simp: divide_le_0_iff)
lemma field_le_mult_one_interval:
assumes *: "\<And>z. \<lbrakk> 0 < z ; z < 1 \<rbrakk> \<Longrightarrow> z * x \<le> y"
shows "x \<le> y"
proof (cases "0 < x")
assume "0 < x"
thus ?thesis
using dense_le_bounded[of 0 1 "y/x"] *
unfolding le_divide_eq if_P[OF \<open>0 < x\<close>] by simp
next
assume "\<not>0 < x" hence "x \<le> 0" by simp
obtain s::'a where s: "0 < s" "s < 1" using dense[of 0 "1::'a"] by auto
hence "x \<le> s * x" using mult_le_cancel_right[of 1 x s] \<open>x \<le> 0\<close> by auto
also note *[OF s]
finally show ?thesis .
qed
text\<open>For creating values between \<^term>\<open>u\<close> and \<^term>\<open>v\<close>.\<close>
lemma scaling_mono:
assumes "u \<le> v" "0 \<le> r" "r \<le> s"
shows "u + r * (v - u) / s \<le> v"
proof -
have "r/s \<le> 1" using assms
using divide_le_eq_1 by fastforce
moreover have "0 \<le> v - u"
using assms by simp
ultimately have "(r/s) * (v - u) \<le> 1 * (v - u)"
by (rule mult_right_mono)
then show ?thesis
by (simp add: field_simps)
qed
end
text \<open>Min/max Simplification Rules\<close>
lemma min_mult_distrib_left:
fixes x::"'a::linordered_idom"
shows "p * min x y = (if 0 \<le> p then min (p*x) (p*y) else max (p*x) (p*y))"
by (auto simp add: min_def max_def mult_le_cancel_left)
lemma min_mult_distrib_right:
fixes x::"'a::linordered_idom"
shows "min x y * p = (if 0 \<le> p then min (x*p) (y*p) else max (x*p) (y*p))"
by (auto simp add: min_def max_def mult_le_cancel_right)
lemma min_divide_distrib_right:
fixes x::"'a::linordered_field"
shows "min x y / p = (if 0 \<le> p then min (x/p) (y/p) else max (x/p) (y/p))"
by (simp add: min_mult_distrib_right divide_inverse)
lemma max_mult_distrib_left:
fixes x::"'a::linordered_idom"
shows "p * max x y = (if 0 \<le> p then max (p*x) (p*y) else min (p*x) (p*y))"
by (auto simp add: min_def max_def mult_le_cancel_left)
lemma max_mult_distrib_right:
fixes x::"'a::linordered_idom"
shows "max x y * p = (if 0 \<le> p then max (x*p) (y*p) else min (x*p) (y*p))"
by (auto simp add: min_def max_def mult_le_cancel_right)
lemma max_divide_distrib_right:
fixes x::"'a::linordered_field"
shows "max x y / p = (if 0 \<le> p then max (x/p) (y/p) else min (x/p) (y/p))"
by (simp add: max_mult_distrib_right divide_inverse)
hide_fact (open) field_inverse field_divide_inverse field_inverse_zero
code_identifier
code_module Fields \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith
end
|
lemma coeff_0_power: "coeff (p ^ n) 0 = coeff p 0 ^ n" |
Formal statement is: lemma connected_iff_connected_component_eq: "connected S \<longleftrightarrow> (\<forall>x \<in> S. \<forall>y \<in> S. connected_component_set S x = connected_component_set S y)" Informal statement is: A set $S$ is connected if and only if all of its connected components are equal. |
using SymbolicUtils: FnType, Sym
using Setfield
const IndexMap = Dict{Char,Char}(
'0' => '₀',
'1' => '₁',
'2' => '₂',
'3' => '₃',
'4' => '₄',
'5' => '₅',
'6' => '₆',
'7' => '₇',
'8' => '₈',
'9' => '₉')
struct VariableDefaultValue end
"""
$(TYPEDEF)
A named variable which represents a numerical value. The variable is uniquely
identified by its `name`, and all variables with the same `name` are treated
as equal.
# Fields
$(FIELDS)
For example, the following code defines an independent variable `t`, a parameter
`α`, a function parameter `σ`, a variable `x`, which depends on `t`, a variable
`y` with no dependents, a variable `z`, which depends on `t`, `α`, and `x(t)`
and parameters `β₁` and `β₂`.
```julia
σ = Num(Variable{Symbolics.FnType{Tuple{Any},Real}}(:σ)) # left uncalled, since it is used as a function
w = Num(Variable{Symbolics.FnType{Tuple{Any},Real}}(:w)) # unknown, left uncalled
x = Num(Variable{Symbolics.FnType{Tuple{Any},Real}}(:x))(t) # unknown, depends on `t`
y = Num(Variable(:y)) # unknown, no dependents
z = Num(Variable{Symbolics.FnType{NTuple{3,Any},Real}}(:z))(t, α, x) # unknown, multiple arguments
β₁ = Num(Variable(:β, 1)) # with index 1
β₂ = Num(Variable(:β, 2)) # with index 2
expr = β₁ * x + y^α + σ(3) * (z - t) - β₂ * w(t - 1)
```
"""
struct Variable{T} <: Function # backward compat
"""The variable's unique name."""
name::Symbol
Variable(name) = Sym{Real}(name)
Variable{T}(name) where T = Sym{T}(name)
function Variable{T}(name, indices...) where T
var_name = Symbol("$(name)$(join(map_subscripts.(indices), "ˏ"))")
Sym{T}(var_name)
end
end
function Variable(name, indices...)
var_name = Symbol("$(name)$(join(map_subscripts.(indices), "ˏ"))")
Variable(var_name)
end
# TODO: move this to Symutils
function Sym{T}(name, i, indices...) where T
var_name = Symbol("$(name)$(join(map_subscripts.((i, indices...,)), "ˏ"))")
Sym{T}(var_name)
end
function map_subscripts(indices)
str = string(indices)
join(IndexMap[c] for c in str)
end
rename(x::Sym,name) = @set! x.name = name
function rename(x::Symbolic, name)
if operation(x) isa Sym
@assert x isa Term
@set! x.f = rename(operation(x), name)
@set! x.hash = Ref{UInt}(0)
return x
else
error("can't rename $x to $name")
end
end
function unwrap_runtime_var(v)
isruntime = Meta.isexpr(v, :$) && length(v.args) == 1
isruntime && (v = v.args[1])
return isruntime, v
end
# Build variables more easily
function _parse_vars(macroname, type, x, transform=identity)
ex = Expr(:block)
var_names = Symbol[]
# if parsing things in the form of
# begin
# x
# y
# z
# end
x = x isa Tuple && first(x) isa Expr && first(x).head == :tuple ? first(x).args : x # tuple handling
x = flatten_expr!(x)
cursor = 0
isoption(ex) = Meta.isexpr(ex, [:vect, :vcat, :hcat])
while cursor < length(x)
cursor += 1
v = x[cursor]
# We need lookahead to the next `v` to parse
# `@variables x [connect=Flow,unit=u]`
nv = cursor < length(x) ? x[cursor+1] : nothing
val = unit = connect = options = nothing
# x = 1, [connect = flow; unit = u"m^3/s"]
if Meta.isexpr(v, :(=))
v, val = v.args
if Meta.isexpr(val, :tuple) && length(val.args) == 2 && isoption(val.args[2])
options = val.args[2].args
val = val.args[1]
end
end
# x [connect = flow; unit = u"m^3/s"]
if isoption(nv)
options = nv.args
cursor += 1
end
isruntime, v = unwrap_runtime_var(v)
iscall = Meta.isexpr(v, :call)
isarray = Meta.isexpr(v, :ref)
issym = v isa Symbol
@assert iscall || isarray || issym "@$macroname expects a tuple of expressions or an expression of a tuple (`@$macroname x y z(t) v[1:3] w[1:2,1:4]` or `@$macroname x y z(t) v[1:3] w[1:2,1:4] k=1.0`)"
if iscall
isruntime, fname = unwrap_runtime_var(v.args[1])
call_args = map(last∘unwrap_runtime_var, @view v.args[2:end])
var_name, expr = construct_vars(fname, type, call_args, val, options, transform, isruntime)
else
var_name, expr = construct_vars(v, type, nothing, val, options, transform, isruntime)
end
push!(var_names, var_name)
push!(ex.args, expr)
end
rhs = build_expr(:vect, var_names)
push!(ex.args, rhs)
return ex
end
function construct_vars(v, type, call_args, val, prop, transform, isruntime)
issym = v isa Symbol
isarray = isa(v, Expr) && v.head == :ref
if isarray
var_name = v.args[1]
isruntime, var_name = unwrap_runtime_var(var_name)
indices = v.args[2:end]
expr = _construct_array_vars(isruntime ? var_name : Meta.quot(var_name), type, call_args, val, prop, indices...)
else
var_name = v
expr = construct_var(isruntime ? var_name : Meta.quot(var_name), type, call_args, val, prop)
end
lhs = isruntime ? gensym(var_name) : var_name
rhs = :($transform($expr))
lhs, :($lhs = $rhs)
end
function option_to_metadata_type(::Val{opt}) where {opt}
throw(Base.Meta.ParseError("unknown property type $opt"))
end
function setprops_expr(expr, props)
isnothing(props) && return expr
for opt in props
if !Meta.isexpr(opt, :(=))
throw(Base.Meta.ParseError(
"Variable properties must be in " *
"the form of `a = b`. Got $opt."))
end
lhs, rhs = opt.args
@assert lhs isa Symbol "the lhs of an option must be a symbol"
expr = :($setmetadata($expr,
$(option_to_metadata_type(Val{lhs}())),
$rhs))
end
expr
end
function construct_var(var_name, type, call_args, val, prop)
expr = if call_args === nothing
:($Num($Sym{$type}($var_name)))
elseif !isempty(call_args) && call_args[end] == :..
:($Num($Sym{$FnType{Tuple, $type}}($var_name))) # XXX: using Num as output
else
:($Num($Sym{$FnType{NTuple{$(length(call_args)), Any}, $type}}($var_name)($(map(x->:($value($x)), call_args)...))))
end
if val !== nothing
expr = :($setmetadata($expr, $VariableDefaultValue, $val))
end
return setprops_expr(expr, prop)
end
function construct_var(var_name, type, call_args, val, prop, ind)
# TODO: just use Sym here
expr = if call_args === nothing
:($Num($Sym{$type}($var_name, $ind...)))
elseif !isempty(call_args) && call_args[end] == :..
:($Num($Sym{$FnType{Tuple{Any}, $type}}($var_name, $ind...))) # XXX: using Num as output
else
:($Num($Sym{$FnType{NTuple{$(length(call_args)), Any}, $type}}($var_name, $ind...)($(map(x->:($value($x)), call_args)...))))
end
if val !== nothing
expr = :($setmetadata($expr, $VariableDefaultValue, $val isa AbstractArray ? $val[$ind...] : $val))
end
return setprops_expr(expr, prop)
end
function _construct_array_vars(var_name, type, call_args, val, prop, indices...)
:(map(Iterators.product($(indices...))) do ind
$(construct_var(var_name, type, call_args, val, prop, :ind))
end)
end
"""
Define one or more unknown variables.
```julia
@variables t α σ(..) β[1:2]
@variables w(..) x(t) y z(t, α, x)
expr = β[1]* x + y^α + σ(3) * (z - t) - β[2] * w(t - 1)
```
`(..)` signifies that the value should be left uncalled.
Sometimes it is convenient to define arrays of variables to model things like `x₁,…,x₃`.
The `@variables` macro supports this with the following syntax:
```julia
julia> @variables x[1:3]
1-element Vector{Vector{Num}}:
[x₁, x₂, x₃]
julia> @variables y[2:3, 1:5:6] # support for arbitrary ranges and tensors
1-element Vector{Matrix{Num}}:
[y₂ˏ₁ y₂ˏ₆; y₃ˏ₁ y₃ˏ₆]
julia> @variables t z[1:3](t) # also works for dependent variables
2-element Vector{Any}:
t
Num[z₁(t), z₂(t), z₃(t)]
```
Note that `@variables` returns a vector of all the defined variables.
`@variables` can also take runtime symbol values by the `\$` interpolation
operator, and in this case, `@variables` doesn't automatically assign the value,
instead, it only returns a vector of symbolic variables. All the rest of the
syntax also applies here.
```julia
julia> a, b, c = :runtime_symbol_value, :value_b, :value_c
:runtime_symbol_value
julia> vars = @variables t \$a \$b(t) \$c[1:3](t)
3-element Vector{Num}:
t
runtime_symbol_value
value_b(t)
Num[value_c₁(t), value_c₂(t), value_c₃(t)]
julia> (t, a, b, c)
(t, :runtime_symbol_value, :value_b, :value_c)
```
"""
macro variables(xs...)
esc(_parse_vars(:variables, Real, xs))
end
TreeViews.hastreeview(x::Sym) = true
function TreeViews.treelabel(io::IO,x::Sym,
mime::MIME"text/plain" = MIME"text/plain"())
show(io,mime,Text(x.name))
end
|
(*
Authors: René Thiemann
BSD
*)
section \<open>Certification of External LLL Invocations\<close>
text \<open>Instead of using a fully verified algorithm, we also provide a technique to invoke
an external LLL solver. In order to check its result, we not only need the reduced basic,
but also the matrices which translate between the input basis and the reduced basis.
Then we can easily check whether the resulting lattices are indeed identical and just have
to start the verified algorithm on the already reduced basis.
This invocation will then usually just require one computation of Gram--Schmidt in order
to check that the basis is already reduced. Alternatively, one could also throw an error
message in case the basis is not reduced.\<close>
subsection \<open>Checking Results of External LLL Solvers\<close>
theory LLL_Certification
imports
LLL_Impl
Jordan_Normal_Form.Show_Matrix
begin
definition "gauss_jordan_integer_inverse n A B I = (case gauss_jordan A B of
(C,D) \<Rightarrow> C = I \<and> list_all is_int_rat (concat (mat_to_list D)))"
definition "integer_equivalent n fs gs = (let
fs' = map_mat rat_of_int (mat_of_cols n fs);
gs' = map_mat rat_of_int (mat_of_cols n gs);
I = 1\<^sub>m n
in gauss_jordan_integer_inverse n fs' gs' I \<and> gauss_jordan_integer_inverse n gs' fs' I)"
context vec_module
begin
lemma mat_mult_sub_lattice: assumes fs: "set fs \<subseteq> carrier_vec n"
and gs: "set gs \<subseteq> carrier_vec n"
and A: "A \<in> carrier_mat (length fs) (length gs)"
and prod: "mat_of_rows n fs = map_mat of_int A * mat_of_rows n gs"
shows "lattice_of fs \<subseteq> lattice_of gs"
proof
let ?m = "length fs"
let ?m' = "length gs"
let ?i = "of_int :: int \<Rightarrow> 'a"
let ?I = "map_mat ?i"
let ?A = "?I A"
have gsC: "mat_of_rows n gs \<in> carrier_mat ?m' n" by auto
from A have A: "?A \<in> carrier_mat ?m ?m'" by auto
from fs have fsi[simp]: "\<And> i. i < ?m \<Longrightarrow> fs ! i \<in> carrier_vec n" by auto
hence fsi'[simp]: "\<And> i. i < ?m \<Longrightarrow> dim_vec (fs ! i) = n" by simp
from gs have fsi[simp]: "\<And> i. i < ?m' \<Longrightarrow> gs ! i \<in> carrier_vec n" by auto
hence gsi'[simp]: "\<And> i. i < ?m' \<Longrightarrow> dim_vec (gs ! i) = n" by simp
fix v
assume "v \<in> lattice_of fs"
from in_latticeE[OF this]
obtain c where v: "v = M.sumlist (map (\<lambda>i. ?i (c i) \<cdot>\<^sub>v fs ! i) [0..<?m])" by auto
let ?c = "vec ?m (\<lambda> i. ?i (c i))"
let ?d = "A\<^sup>T *\<^sub>v vec ?m c"
note v
also have "\<dots> = mat_of_cols n fs *\<^sub>v ?c"
by (rule eq_vecI, auto intro!: dim_sumlist sum.cong
simp: sumlist_nth scalar_prod_def mat_of_cols_def)
also have "mat_of_cols n fs = (mat_of_rows n fs)\<^sup>T"
by (simp add: transpose_mat_of_rows)
also have "\<dots> = (?A * mat_of_rows n gs)\<^sup>T" unfolding prod ..
also have "\<dots> = (mat_of_rows n gs)\<^sup>T * ?A\<^sup>T"
by (rule transpose_mult[OF A gsC])
also have "(mat_of_rows n gs)\<^sup>T = mat_of_cols n gs"
by (simp add: transpose_mat_of_rows)
finally have "v = (mat_of_cols n gs * ?A\<^sup>T) *\<^sub>v ?c" .
also have "\<dots> = mat_of_cols n gs *\<^sub>v (?A\<^sup>T *\<^sub>v ?c)"
by (rule assoc_mult_mat_vec, insert A, auto)
also have "?A\<^sup>T = ?I (A\<^sup>T)" by fastforce
also have "?c = map_vec ?i (vec ?m c)" by auto
also have "?I (A\<^sup>T) *\<^sub>v \<dots> = map_vec ?i ?d"
using A by (simp add: of_int_hom.mult_mat_vec_hom)
finally have "v = mat_of_cols n gs *\<^sub>v map_vec ?i ?d" .
define d where "d = ?d"
have d: "d \<in> carrier_vec ?m'" unfolding d_def using A by auto
have "v = mat_of_cols n gs *\<^sub>v map_vec ?i d" unfolding d_def by fact
also have "\<dots> = M.sumlist (map (\<lambda>i. ?i (d $ i) \<cdot>\<^sub>v gs ! i) [0..<?m'])"
by (rule sym, rule eq_vecI, insert d, auto intro!: dim_sumlist sum.cong
simp: sumlist_nth scalar_prod_def mat_of_cols_def)
finally show "v \<in> lattice_of gs"
by (intro in_latticeI, auto)
qed
end
context LLL_with_assms
begin
lemma mult_left_identity:
defines "B \<equiv> (map_mat rat_of_int (mat_of_rows n fs_init))"
assumes P_carrier[simp]: "P \<in> carrier_mat m m"
and PB: "P * B = B"
shows "P = 1\<^sub>m m"
proof -
let ?set_rows = "set (rows B)"
let ?hom = "of_int_hom.vec_hom :: int vec \<Rightarrow> rat vec"
have set_rows_carrier: "?set_rows \<subseteq> (carrier_vec n)" by (auto simp add: rows_def B_def)
have set_rows_eq: "?set_rows = set (map of_int_hom.vec_hom fs_init)"
proof -
have "x \<in> of_int_hom.vec_hom ` set fs_init" if x: "x \<in> set (rows B)" for x
using x unfolding B_def
by (metis cof_vec_space.lin_indpt_list_def fs_init image_set
lin_dep mat_of_rows_map rows_mat_of_rows)
moreover have "of_int_hom.vec_hom xa \<in> set (rows B)" if xa: "xa \<in> set fs_init" for xa
proof -
obtain i where xa: "xa = fs_init ! i" and i: "i<m"
by (metis in_set_conv_nth len xa)
have "?hom (fs_init ! i) = row B i" unfolding B_def
by (metis i cof_vec_space.lin_indpt_list_def fs_init index_map_mat(2) len lin_dep
mat_of_rows_carrier(2) mat_of_rows_map nth_map nth_rows rows_mat_of_rows)
thus ?thesis
by (metis B_def xa i cof_vec_space.lin_indpt_list_def fs_init index_map_mat(2) len
length_rows lin_dep mat_of_rows_map nth_map nth_mem rows_mat_of_rows)
qed
ultimately show ?thesis by auto
qed
have ind_set_rows: "gs.lin_indpt ?set_rows"
using lin_dep set_rows_eq unfolding gs.lin_indpt_list_def by auto
have inj_on_rowB: "inj_on (row B) {0..<m}"
proof -
have "x = y" if x: "x < m" and y: "y < m" and row_xy: "row B x = row B y" for x y
proof (rule ccontr)
assume xy: "x \<noteq> y"
have 1: "?hom (fs_init ! x) = row B x" unfolding B_def
by (metis fs_init index_map_mat(2) len local.set_rows_carrier mat_of_rows_carrier(2)
mat_of_rows_map nth_map nth_rows rows_mat_of_rows set_rows_eq that(1))
moreover have 2: "?hom (fs_init ! y) = row B y" unfolding B_def
by (metis fs_init index_map_mat(2) len local.set_rows_carrier mat_of_rows_carrier(2)
mat_of_rows_map nth_map nth_rows rows_mat_of_rows set_rows_eq that(2))
ultimately have "?hom (fs_init ! x) = ?hom (fs_init ! y)" using row_xy by auto
thus False using lin_dep x y row_xy unfolding gs.lin_indpt_list_def
using xy x y len unfolding distinct_conv_nth by auto
qed
thus ?thesis unfolding inj_on_def by auto
qed
have the_x: "(THE k. k < m \<and> row B x = row B k) = x" if x: "x < m" for x
proof (rule theI2)
show "x < m \<and> row B x = row B x" using x by auto
fix xa assume xa: "xa < m \<and> row B x = row B xa"
show "xa = x" using xa inj_on_rowB x unfolding inj_on_def by auto
thus "xa = x" .
qed
let ?h= "row B"
show ?thesis
proof (rule eq_matI, unfold one_mat_def, auto)
fix j assume j: "j < m"
let ?f = "(\<lambda>v. P $$ (j, THE k. k < m \<and> v = row B k))"
let ?g = "\<lambda>v. if v = row B j then (?f v) - 1 else ?f v"
have finsum_closed[simp]:
"finsum_vec TYPE(rat) n (\<lambda>k. P $$ (j, k) \<cdot>\<^sub>v row B k) {0..<m} \<in> carrier_vec n"
by (rule finsum_vec_closed, insert len B_def, auto)
have B_carrier[simp]: "B \<in> carrier_mat m n" using len fs_init B_def by auto
define v where "v \<equiv> row B j"
have v_set_rows: "v \<in> set (rows B)" using nth_rows j unfolding v_def
by (metis B_carrier carrier_matD(1) length_rows nth_mem)
have [simp]: "mat_of_rows n fs_init \<in> carrier_mat m n" using len fs_init by auto
have "B = P*B" using PB by auto
also have "... = mat\<^sub>r m n (\<lambda>i. finsum_vec TYPE(rat) n (\<lambda>k. P $$ (i, k) \<cdot>\<^sub>v row B k) {0..<m})"
by (rule mat_mul_finsum_alt, auto)
also have "row (...) j = finsum_vec TYPE(rat) n (\<lambda>k. P $$ (j, k) \<cdot>\<^sub>v row B k) {0..<m}"
by (rule row_mat_of_row_fun[OF j], simp)
also have "... = finsum_vec TYPE(rat) n (\<lambda>v. ?f v \<cdot>\<^sub>v v) ?set_rows" (is "?lhs = ?rhs")
proof (rule eq_vecI)
have rhs_carrier: "?rhs \<in> carrier_vec n"
by (rule finsum_vec_closed, insert set_rows_carrier, auto)
have "dim_vec ?lhs = n" using vec_space.finsum_dim by simp
also have dim_rhs: "... = dim_vec ?rhs" using rhs_carrier by auto
finally show "dim_vec ?lhs = dim_vec ?rhs" .
fix i assume i: "i < dim_vec ?rhs"
have i_n: "i < n" using i dim_rhs by auto
let ?g = "\<lambda>v. (?f v \<cdot>\<^sub>v v) $ i"
have image_h: "?h `{0..<m} = ?set_rows" by (auto simp add: B_def len rows_def)
have "?lhs $ i = (\<Sum>k\<in>{0..<m}. (P $$ (j, k) \<cdot>\<^sub>v row B k) $ i)"
by (rule index_finsum_vec[OF _ i_n], auto)
also have "... = sum (?g \<circ> ?h) {0..<m}" unfolding o_def
by (rule sum.cong, insert the_x, auto)
also have "... = sum (\<lambda>v. (?f v \<cdot>\<^sub>v v) $ i) (?h `{0..<m})"
by (rule sum.reindex[symmetric, OF inj_on_rowB])
also have "... = (\<Sum>v\<in>?set_rows. (?f v \<cdot>\<^sub>v v) $ i)" using image_h by auto
also have "... = ?rhs $ i"
by (rule index_finsum_vec[symmetric, OF _ i_n], insert set_rows_carrier, auto)
finally show "?lhs $ i = ?rhs $ i" by auto
qed
also have "... = (\<Oplus>\<^bsub>gs.V\<^esub>v\<in>?set_rows. ?f v \<cdot>\<^sub>v v)" unfolding vec_space.finsum_vec ..
also have "... = gs.lincomb ?f ?set_rows" unfolding gs.lincomb_def by auto
finally have lincomb_rowBj: "gs.lincomb ?f ?set_rows = row B j" ..
have lincomb_0: "gs.lincomb ?g (?set_rows) = 0\<^sub>v n"
proof -
have v_closed[simp]: "v \<in> Rn" unfolding v_def using j by auto
have lincomb_f_closed[simp]: "gs.lincomb ?f (?set_rows-{v}) \<in> Rn"
by (rule gs.lincomb_closed, insert set_rows_carrier, auto)
have fv_v_closed[simp]: "?f v \<cdot>\<^sub>v v \<in> Rn" by auto
have lincomb_f: "gs.lincomb ?f ?set_rows = ?f v \<cdot>\<^sub>v v + gs.lincomb ?f (?set_rows-{v})"
by (rule gs.lincomb_del2, insert set_rows_carrier v_set_rows, auto)
have fvv_gvv: "?f v \<cdot>\<^sub>v v - v = ?g v \<cdot>\<^sub>v v" unfolding v_def
by (rule eq_vecI, auto, simp add: left_diff_distrib)
have lincomb_fg: "gs.lincomb ?f (?set_rows-{v}) = gs.lincomb ?g (?set_rows-{v})"
(is "?lhs = ?rhs")
proof (rule eq_vecI)
show dim_vec_eq: "dim_vec ?lhs = dim_vec ?rhs"
by (smt DiffE carrier_vecD gs.lincomb_closed local.set_rows_carrier subsetCE subsetI)
fix i assume i: "i<dim_vec ?rhs"
hence i_n: "i<n" using dim_vec_eq lincomb_f_closed by auto
have "?lhs $ i = (\<Sum>x\<in>(?set_rows-{v}). ?f x * x $ i)"
by (rule gs.lincomb_index[OF i_n], insert set_rows_carrier, auto)
also have "... = (\<Sum>x\<in>(?set_rows-{v}). ?g x * x $ i)"
by (rule sum.cong, auto simp add: v_def)
also have "... = ?rhs $ i"
by (rule gs.lincomb_index[symmetric, OF i_n], insert set_rows_carrier, auto)
finally show "?lhs $ i = ?rhs $ i" .
qed
have "0\<^sub>v n = gs.lincomb ?f ?set_rows - v" using lincomb_rowBj unfolding v_def B_def by auto
also have "... = ?f v \<cdot>\<^sub>v v + gs.lincomb ?f (?set_rows-{v}) - v" using lincomb_f by auto
also have "... = (gs.lincomb ?f (?set_rows-{v}) + ?f v \<cdot>\<^sub>v v) + - v"
unfolding gs.M.a_comm[OF lincomb_f_closed fv_v_closed] by auto
also have "... = gs.lincomb ?f (?set_rows-{v}) + (?f v \<cdot>\<^sub>v v + - v)"
by (rule gs.M.a_assoc, auto)
also have "... = gs.lincomb ?f (?set_rows-{v}) + (?f v \<cdot>\<^sub>v v - v)" by auto
also have "... = gs.lincomb ?g (?set_rows-{v}) + (?g v \<cdot>\<^sub>v v)"
unfolding lincomb_fg fvv_gvv by auto
also have "... = (?g v \<cdot>\<^sub>v v) + gs.lincomb ?g (?set_rows-{v})"
by (rule gs.M.a_comm, auto, rule gs.lincomb_closed, insert set_rows_carrier, auto)
also have "... = gs.lincomb ?g (?set_rows)"
by (rule gs.lincomb_del2[symmetric], insert v_set_rows set_rows_carrier, auto)
finally show ?thesis ..
qed
have g0: "?g \<in> ?set_rows \<rightarrow> {0}"
by (rule gs.not_lindepD[of ?set_rows, OF ind_set_rows _ _ _ lincomb_0], auto)
hence "?g (row B j) = 0" using v_set_rows unfolding v_def Pi_def by blast
hence "?f (row B j) - 1 = 0" by auto
hence "P $$ (j,j) - 1 = 0" using the_x j by auto
thus "P$$(j,j) = 1" by auto
fix i assume i: "i < m" and ji: "j \<noteq> i"
have row_ij: "row B i \<noteq> row B j" using inj_on_rowB ji i j unfolding inj_on_def by fastforce
have "row B i \<in> ?set_rows" using nth_rows i
by (metis B_carrier carrier_matD(1) length_rows nth_mem)
hence "?g (row B i) = 0" using g0 unfolding Pi_def by blast
hence "?f (row B i) = 0" using row_ij by auto
thus "P $$ (j, i) = 0" using the_x i by auto
next
show "dim_row P = m" and "dim_col P = m" using P_carrier unfolding carrier_mat_def by auto
qed
qed
text \<open>This is the key lemma. It permits to change from the initial basis
@{term fs_init} to an arbitrary @{term gs} that has been computed by some
external tool. Here, two change-of-basis matrices U1 and U2 are required
to certify the change via the conditions prod1 and prod2.\<close>
lemma LLL_change_basis: assumes gs: "set gs \<subseteq> carrier_vec n"
and len': "length gs = m"
and U1: "U1 \<in> carrier_mat m m"
and U2: "U2 \<in> carrier_mat m m"
and prod1: "mat_of_rows n fs_init = U1 * mat_of_rows n gs"
and prod2: "mat_of_rows n gs = U2 * mat_of_rows n fs_init"
shows "lattice_of gs = lattice_of fs_init" "LLL_with_assms n m gs \<alpha>"
proof -
let ?i = "of_int :: int \<Rightarrow> int"
have "U1 = map_mat ?i U1" by (intro eq_matI, auto)
with prod1 have prod1: "mat_of_rows n fs_init = map_mat ?i U1 * mat_of_rows n gs" by simp
have "U2 = map_mat ?i U2" by (intro eq_matI, auto)
with prod2 have prod2: "mat_of_rows n gs = map_mat ?i U2 * mat_of_rows n fs_init" by simp
have "lattice_of gs \<subseteq> lattice_of fs_init"
by (rule mat_mult_sub_lattice[OF gs fs_init _ prod2], auto simp: U2 len len')
moreover have "lattice_of gs \<supseteq> lattice_of fs_init"
by (rule mat_mult_sub_lattice[OF fs_init gs _ prod1], auto simp: U1 len len')
ultimately show "lattice_of gs = lattice_of fs_init" by blast
show "LLL_with_assms n m gs \<alpha>"
proof
show "4/3 \<le> \<alpha>" by (rule \<alpha>)
show "length gs = m" by fact
show "lin_indep gs"
proof -
let ?fs = "map_mat rat_of_int (mat_of_rows n fs_init)"
let ?gs = "map_mat rat_of_int (mat_of_rows n gs)"
let ?U1 = "map_mat rat_of_int U1"
let ?U2 = "map_mat rat_of_int U2"
let ?P = "?U1 * ?U2"
have rows_gs_eq: "rows ?gs = map of_int_hom.vec_hom gs"
proof (rule nth_equalityI)
fix i assume i: "i < length (rows ?gs)"
have "rows ?gs ! i = row ?gs i" by (rule nth_rows, insert i, auto)
also have "... = of_int_hom.vec_hom (gs ! i)"
by (metis (mono_tags, lifting) gs i index_map_mat(2) length_map length_rows map_carrier_vec
mat_of_rows_map mat_of_rows_row nth_map nth_mem rows_mat_of_rows subset_code(1))
also have "... = map of_int_hom.vec_hom gs ! i"
by (rule nth_map[symmetric], insert i, auto)
finally show "rows ?gs ! i = map of_int_hom.vec_hom gs ! i" .
qed (simp)
have fs_hom: "?fs \<in> carrier_mat m n" unfolding carrier_mat_def using len by auto
have gs_hom: "?gs \<in> carrier_mat m n" unfolding carrier_mat_def using len' by auto
have U1U2: "U1 * U2 \<in> carrier_mat m m" by (meson assms(3) assms(4) mult_carrier_mat)
have U1_hom: "?U1 \<in> carrier_mat m m" by (simp add: U1)
have U2_hom: "?U2 \<in> carrier_mat m m" by (simp add: U2)
have U1U2_hom: "?U1 * ?U2 \<in> carrier_mat m m" using U1 U2 by auto
have Gs_U2Fs: "?gs = ?U2 * ?fs" using prod2
by (metis U2 assms(6) len mat_of_rows_carrier(1) of_int_hom.mat_hom_mult)
have fs_hom_eq: "?fs = ?P * ?fs"
by (smt U1 U1U2 U2 assms(5) assms(6) assoc_mult_mat fs_hom
map_carrier_mat of_int_hom.mat_hom_mult)
have P_id: "?P = 1\<^sub>m m" by (rule mult_left_identity[OF U1U2_hom fs_hom_eq[symmetric]])
hence "det (?U1) * det (?U2) = 1" by (smt U1_hom U2_hom det_mult det_one of_int_hom.hom_det)
hence det_U2: "det ?U2 \<noteq> 0" and det_U1: "det ?U1 \<noteq> 0" by auto
from det_non_zero_imp_unit[OF U2_hom det_U2, unfolded Units_def, of "()"]
have inv_U2: "invertible_mat ?U2"
using U1_hom U2_hom
unfolding invertible_mat_def inverts_mat_def by (auto simp: ring_mat_def)
interpret Rs: vectorspace class_ring "(gs.vs (gs.row_space ?gs))"
by (rule gs.vector_space_row_space[OF gs_hom])
interpret RS_fs: vectorspace class_ring "(gs.vs (gs.row_space (?fs)))"
by (rule gs.vector_space_row_space[OF fs_hom])
have submoduleGS: "submodule class_ring (gs.row_space ?gs) gs.V"
and submoduleFS: "submodule class_ring (gs.row_space ?fs) gs.V"
by (metis gs.row_space_def gs.span_is_submodule index_map_mat(3)
mat_of_rows_carrier(3) rows_carrier)+
have set_rows_fs_in: "set (rows ?fs) \<subseteq> gs.row_space ?fs"
and rows_gs_row_space: "set (rows ?gs) \<subseteq> gs.row_space ?gs"
unfolding gs.row_space_def
by (metis gs.in_own_span index_map_mat(3) mat_of_rows_carrier(3) rows_carrier)+
have Rs_fs_dim: "RS_fs.dim = m"
proof -
have "RS_fs.dim = card (set (rows ?fs))"
proof (rule RS_fs.dim_basis)
have "RS_fs.span (set (rows ?fs)) = gs.span (set (rows ?fs))"
by (rule gs.span_li_not_depend[OF _ submoduleFS], simp add: set_rows_fs_in)
also have "... = carrier (gs.vs (gs.row_space ?fs))"
unfolding gs.row_space_def unfolding gs.carrier_vs_is_self by auto
finally have "RS_fs.gen_set (set (rows ?fs))" by auto
moreover have "RS_fs.lin_indpt (set (rows ?fs))"
proof -
have "module.lin_dep class_ring (gs.vs (gs.row_space ?fs)) (set (rows ?fs))
= gs.lin_dep (set (rows ?fs))"
by (rule gs.span_li_not_depend[OF _ submoduleFS], simp add: set_rows_fs_in)
thus ?thesis using lin_dep unfolding gs.lin_indpt_list_def
by (metis fs_init mat_of_rows_map rows_mat_of_rows)
qed
moreover have "set (rows ?fs) \<subseteq> carrier (gs.vs (gs.row_space ?fs))"
by (simp add: set_rows_fs_in)
ultimately show "RS_fs.basis (set (rows ?fs))" unfolding RS_fs.basis_def by simp
qed (simp)
also have "... = m"
by (metis cof_vec_space.lin_indpt_list_def distinct_card fs_init len
length_map lin_dep mat_of_rows_map rows_mat_of_rows)
finally show ?thesis .
qed
have "gs.row_space ?fs = gs.row_space (?U2*?fs)"
by (rule gs.row_space_is_preserved[symmetric, OF inv_U2 U2_hom fs_hom])
also have "... = gs.row_space ?gs" using Gs_U2Fs by auto
finally have "gs.row_space ?fs = gs.row_space ?gs" by auto
hence "vectorspace.dim class_ring (gs.vs (gs.row_space ?gs)) = m"
using Rs_fs_dim fs_hom_eq by auto
hence Rs_dim_is_m: "Rs.dim = m" by blast
have card_set_rows: "card (set (rows ?gs)) \<le> m"
by (metis assms(2) card_length length_map rows_gs_eq)
have Rs_basis: "Rs.basis (set (rows ?gs))"
proof (rule Rs.dim_gen_is_basis)
show "card (set (rows ?gs)) \<le> Rs.dim" using card_set_rows Rs_dim_is_m by auto
have "Rs.span (set (rows ?gs)) = gs.span (set (rows ?gs))"
by (rule gs.span_li_not_depend[OF rows_gs_row_space submoduleGS])
also have "... = carrier (gs.vs (gs.row_space ?gs))"
unfolding gs.row_space_def unfolding gs.carrier_vs_is_self by auto
finally show "Rs.gen_set (set (rows ?gs))" by auto
show "set (rows ?gs) \<subseteq> carrier (gs.vs (gs.row_space ?gs))" using rows_gs_row_space by auto
qed (simp)
hence indpt_Rs: "Rs.lin_indpt (set (rows ?gs))" unfolding Rs.basis_def by auto
have gs_lin_indpt_rows: "gs.lin_indpt (set (rows ?gs))"
(*Is there any automatic way to prove this?*)
(*TODO: via gs.span_li_not_depend*)
proof
define N where "N \<equiv> (gs.row_space ?gs)"
assume "gs.lin_dep (set (rows ?gs))"
from this obtain A f v where A1: "finite A" and A2: "A \<subseteq> set (rows ?gs)"
and lc_gs: "gs.lincomb f A = 0\<^sub>v n" and v: "v \<in> A" and fv: "f v \<noteq> 0"
unfolding gs.lin_dep_def by blast
have "gs.lincomb f A = module.lincomb (gs.vs N) f A"
by (rule gs.lincomb_not_depend, insert submoduleGS A1 A2 gs.row_space_def
rows_gs_row_space, auto simp add: N_def gs.row_space_def)
also have "... = Rs.lincomb f A" using N_def by blast
finally have "Rs.lin_dep (set (rows ?gs))"
unfolding Rs.lin_dep_def using A1 A2 v fv lc_gs by auto
thus False using indpt_Rs by auto
qed
have "card (set (rows ?gs)) \<ge> Rs.dim"
by (rule Rs.gen_ge_dim, insert rows_gs_row_space Rs_basis, auto simp add: Rs.basis_def)
hence card_m: "card (set (rows ?gs)) = m" using card_set_rows Rs_dim_is_m by auto
have "distinct (map (of_int_hom.vec_hom::int vec \<Rightarrow> rat vec) gs)"
using rows_gs_eq assms(2) card_m card_distinct by force
moreover have "set (map of_int_hom.vec_hom gs) \<subseteq> Rn" using gs by auto
ultimately show "gs.lin_indpt_list (map of_int_hom.vec_hom gs)"
using gs_lin_indpt_rows
unfolding rows_gs_eq gs.lin_indpt_list_def
by auto
qed
qed
qed
lemma gauss_jordan_integer_inverse: fixes fs gs :: "int vec list"
assumes gs: "set gs \<subseteq> carrier_vec n"
and len_gs: "length gs = n"
and fs: "set fs \<subseteq> carrier_vec n"
and len_fs: "length fs = n"
and gauss: "gauss_jordan_integer_inverse n (map_mat rat_of_int (mat_of_cols n fs))
(map_mat rat_of_int (mat_of_cols n gs)) (1\<^sub>m n)" (is "gauss_jordan_integer_inverse _ ?fs ?gs _")
shows "\<exists> U. U \<in> carrier_mat n n \<and> mat_of_rows n gs = U * mat_of_rows n fs"
proof -
have fs': "?fs \<in> carrier_mat n n" using fs len_fs by auto
have gs': "?gs \<in> carrier_mat n n" using gs len_gs by auto
note gauss = gauss[unfolded gauss_jordan_integer_inverse_def]
from gauss obtain A where gauss: "gauss_jordan ?fs ?gs = (1\<^sub>m n, A)"
and int: "list_all is_int_rat (concat (mat_to_list A))" by auto
note gauss = gauss_jordan[OF fs' gs' gauss]
note A = gauss(4)
let ?A = "map_mat int_of_rat A"
from gauss(2)[OF A] A
have id: "?fs * A = ?gs" by auto
let ?U = "(map_mat int_of_rat A)\<^sup>T"
from A have U: "?U \<in> carrier_mat n n" by auto
have "A = map_mat of_int ?A" using int[unfolded list_all_iff] A
by (intro eq_matI, auto simp: mat_to_list_def)
with id have "?gs = ?fs * map_mat of_int ?A" by auto
also have "\<dots> = map_mat of_int (mat_of_cols n fs * ?A)"
by (rule of_int_hom.mat_hom_mult[symmetric], insert fs' A, auto)
finally have "mat_of_cols n fs * ?A = mat_of_cols n gs"
using of_int_hom.mat_hom_inj by fastforce
hence "(mat_of_cols n gs)\<^sup>T = (mat_of_cols n fs * ?A)\<^sup>T" by simp
also have "\<dots> = ?U * (mat_of_cols n fs)\<^sup>T"
by (rule transpose_mult, insert fs' A, auto)
also have "(mat_of_cols n fs)\<^sup>T = mat_of_rows n fs"
using fs len_fs unfolding mat_of_rows_def mat_of_cols_def
by (intro eq_matI, auto)
also have "(mat_of_cols n gs)\<^sup>T = mat_of_rows n gs"
using gs len_gs unfolding mat_of_rows_def mat_of_cols_def
by (intro eq_matI, auto)
finally show ?thesis using U by blast
qed
lemma LLL_change_basis_mat_inverse: assumes gs: "set gs \<subseteq> carrier_vec n"
and len': "length gs = n"
and "m = n"
and eq: "integer_equivalent n fs_init gs"
shows "lattice_of gs = lattice_of fs_init" "LLL_with_assms n m gs \<alpha>"
proof -
from eq[unfolded integer_equivalent_def Let_def]
have 1: "gauss_jordan_integer_inverse n (of_int_hom.mat_hom (mat_of_cols n fs_init))
(of_int_hom.mat_hom (mat_of_cols n gs)) (1\<^sub>m n)"
and 2: "gauss_jordan_integer_inverse n (of_int_hom.mat_hom (mat_of_cols n gs))
(of_int_hom.mat_hom (mat_of_cols n fs_init)) (1\<^sub>m n)"
by auto
note len = len[unfolded \<open>m = n\<close>]
from gauss_jordan_integer_inverse[OF gs len' fs_init len 1] \<open>m = n\<close>
obtain U where U: "U \<in> carrier_mat m m" "mat_of_rows n gs = U * mat_of_rows n fs_init" by auto
from gauss_jordan_integer_inverse[OF fs_init len gs len' 2] \<open>m = n\<close>
obtain V where V: "V \<in> carrier_mat m m" "mat_of_rows n fs_init = V * mat_of_rows n gs" by auto
from LLL_change_basis[OF gs len'[folded \<open>m = n\<close>] V(1) U(1) V(2) U(2)]
show "lattice_of gs = lattice_of fs_init" "LLL_with_assms n m gs \<alpha>" by blast+
qed
end
text \<open>External solvers must deliver a reduced basis and optionally two
matrices to convert between the input and the reduced basis. These two
matrices are mandatory if the input matrix is not a square matrix.\<close>
consts external_lll_solver :: "integer \<times> integer \<Rightarrow> integer list list \<Rightarrow>
integer list list \<times> (integer list list \<times> integer list list)option"
definition reduce_basis_external :: "rat \<Rightarrow> int vec list \<Rightarrow> int vec list" where
"reduce_basis_external \<alpha> fs = (case fs of Nil \<Rightarrow> [] | Cons f _ \<Rightarrow> (let
rb = reduce_basis \<alpha>;
fsi = map (map integer_of_int o list_of_vec) fs;
n = dim_vec f;
m = length fs in
case external_lll_solver (map_prod integer_of_int integer_of_int (quotient_of \<alpha>)) fsi of
(gsi, co) \<Rightarrow>
let gs = (map (vec_of_list o map int_of_integer) gsi) in
if \<not> (length gs = m \<and> (\<forall> gi \<in> set gs. dim_vec gi = n)) then
Code.abort (STR ''error in external LLL invocation: dimensions of reduced basis do not fit\<newline>input to external solver: ''
+ String.implode (show fs) + STR ''\<newline>\<newline>'') (\<lambda> _. rb fs)
else
case co of Some (u1i, u2i) \<Rightarrow> (let
u1 = mat_of_rows_list m (map (map int_of_integer) u1i);
u2 = mat_of_rows_list m (map (map int_of_integer) u2i);
gs = (map (vec_of_list o map int_of_integer) gsi);
Fs = mat_of_rows n fs;
Gs = mat_of_rows n gs in
if (dim_row u1 = m \<and> dim_col u1 = m \<and> dim_row u2 = m \<and> dim_col u2 = m
\<and> Fs = u1 * Gs \<and> Gs = u2 * Fs)
then rb gs
else Code.abort (STR ''error in external lll invocation\<newline>f,g,u1,u2 are as follows\<newline>''
+ String.implode (show Fs) + STR ''\<newline>\<newline>''
+ String.implode (show Gs) + STR ''\<newline>\<newline>''
+ String.implode (show u1) + STR ''\<newline>\<newline>''
+ String.implode (show u2) + STR ''\<newline>\<newline>''
) (\<lambda> _. rb fs))
| None \<Rightarrow> (if (n = m \<and> integer_equivalent n fs gs) then
rb gs
else Code.abort (STR ''error in external LLL invocation:\<newline>'' +
(if n = m then STR ''reduced matrix does not span same lattice'' else
STR ''no certificate only allowed for square matrices'')) (\<lambda> _. rb fs))
))"
definition short_vector_external :: "rat \<Rightarrow> int vec list \<Rightarrow> int vec" where
"short_vector_external \<alpha> fs = (hd (reduce_basis_external \<alpha> fs))"
instance bool :: prime_card
by (standard, auto)
context LLL_with_assms
begin
lemma reduce_basis_external: assumes res: "reduce_basis_external \<alpha> fs_init = fs"
shows "reduced fs m" "LLL_invariant True m fs"
(* "lattice_of fs = lattice_of fs_init" is part of LLL_invariant *)
proof (atomize(full), goal_cases)
case 1
show ?case
proof (cases "LLL_Impl.reduce_basis \<alpha> fs_init = fs")
case True
from reduce_basis[OF this] show ?thesis by simp
next
case False
show ?thesis
proof (cases fs_init)
case Nil
with res have "fs = []" unfolding reduce_basis_external_def by auto
with False Nil have False by (simp add: LLL_Impl.reduce_basis_def)
thus ?thesis ..
next
case (Cons f rest)
from Cons fs_init len have dim_fs_n: "dim_vec f = n" by auto
let ?ext = "external_lll_solver (map_prod integer_of_int integer_of_int (quotient_of \<alpha>))
(map (map integer_of_int \<circ> list_of_vec) fs_init)"
note res = res[unfolded reduce_basis_external_def Cons Let_def list.case Code.abort_def dim_fs_n,
folded Cons]
from res False obtain gsi co where ext: "?ext = (gsi, co)" by (cases ?ext, auto)
define gs where "gs = map (vec_of_list o map int_of_integer) gsi"
note res = res[unfolded ext option.simps split len dim_fs_n, folded gs_def]
from res False have not: "(\<not> (length gs = m \<and> (\<forall>gi\<in>set gs. dim_vec gi = n))) = False"
by (auto split: if_splits)
note res = res[unfolded this if_False]
from not have gs: "set gs \<subseteq> carrier_vec n"
and len_gs: "length gs = m" by auto
have "lattice_of gs = lattice_of fs_init \<and> LLL_with_assms n m gs \<alpha> \<and> LLL_Impl.reduce_basis \<alpha> gs = fs"
proof (cases co)
case (Some pair)
from res Some obtain u1i u2i where co: "co = Some (u1i, u2i)" by (cases co, auto)
define u1 where "u1 = mat_of_rows_list m (map (map int_of_integer) u1i)"
define u2 where "u2 = mat_of_rows_list m (map (map int_of_integer) u2i)"
note res = res[unfolded co option.simps split len dim_fs_n, folded u1_def u2_def gs_def]
from res False
have u1: "u1 \<in> carrier_mat m m"
and u2: "u2 \<in> carrier_mat m m"
and prod1: "mat_of_rows n fs_init = u1 * mat_of_rows n gs"
and prod2: "mat_of_rows n gs = u2 * mat_of_rows n fs_init"
and gs_v: "LLL_Impl.reduce_basis \<alpha> gs = fs"
by (auto split: if_splits)
from LLL_change_basis[OF gs len_gs u1 u2 prod1 prod2] gs_v
show ?thesis by auto
next
case None
from res[unfolded None option.simps] False
have id: "fs = LLL_Impl.reduce_basis \<alpha> gs" and nm: "n = m"
and equiv: "integer_equivalent n fs_init gs"
by (auto split: if_splits)
from LLL_change_basis_mat_inverse[OF gs len_gs[folded nm] nm[symmetric] equiv] id
show ?thesis by auto
qed
hence id: "lattice_of gs = lattice_of fs_init"
and assms: "LLL_with_assms n m gs \<alpha>"
and gs_fs: "LLL_Impl.reduce_basis \<alpha> gs = fs" by auto
from LLL_with_assms.reduce_basis[OF assms gs_fs]
have red: "reduced fs m" and inv: "LLL.LLL_invariant n m gs \<alpha> True m fs" by auto
from inv[unfolded LLL.LLL_invariant_def LLL.L_def id]
have lattice: "lattice_of fs = lattice_of fs_init" by auto
show ?thesis
proof (intro conjI red lattice)
show "LLL_invariant True m fs" using inv unfolding LLL.LLL_invariant_def LLL.L_def id .
qed
qed
qed
qed
lemma short_vector_external: assumes res: "short_vector_external \<alpha> fs_init = v"
and m0: "m \<noteq> 0"
shows "v \<in> carrier_vec n"
"v \<in> L - {0\<^sub>v n}"
"h \<in> L - {0\<^sub>v n} \<Longrightarrow> rat_of_int (sq_norm v) \<le> \<alpha> ^ (m - 1) * rat_of_int (sq_norm h)"
"v \<noteq> 0\<^sub>v j"
proof (atomize(full), goal_cases)
case 1
obtain fs where red: "reduce_basis_external \<alpha> fs_init = fs" by blast
from res[unfolded short_vector_external_def red] have v: "v = hd fs" by auto
from reduce_basis_external[OF red]
have red: "reduced fs m" and inv: "LLL_invariant True m fs" by blast+
from basis_reduction_short_vector[OF inv v m0]
show ?case by blast
qed
end
text \<open>Unspecified constant to easily enable/disable external lll solver in generated code\<close>
consts enable_external_lll_solver :: bool
definition short_vector_hybrid :: "rat \<Rightarrow> int vec list \<Rightarrow> int vec" where
"short_vector_hybrid = (if enable_external_lll_solver then short_vector_external else short_vector)"
definition reduce_basis_hybrid :: "rat \<Rightarrow> int vec list \<Rightarrow> int vec list" where
"reduce_basis_hybrid = (if enable_external_lll_solver then reduce_basis_external else reduce_basis)"
context LLL_with_assms
begin
lemma short_vector_hybrid: assumes res: "short_vector_hybrid \<alpha> fs_init = v"
and m0: "m \<noteq> 0"
shows "v \<in> carrier_vec n"
"v \<in> L - {0\<^sub>v n}"
"h \<in> L - {0\<^sub>v n} \<Longrightarrow> rat_of_int (sq_norm v) \<le> \<alpha> ^ (m - 1) * rat_of_int (sq_norm h)"
"v \<noteq> 0\<^sub>v j"
using short_vector[of v, OF _ m0] short_vector_external[of v, OF _ m0]
res[unfolded short_vector_hybrid_def]
by (auto split: if_splits)
lemma reduce_basis_hybrid: assumes res: "reduce_basis_hybrid \<alpha> fs_init = fs"
shows "reduced fs m" "LLL_invariant True m fs"
using reduce_basis_external[of fs] reduce_basis[of fs] res[unfolded reduce_basis_hybrid_def]
by (auto split: if_splits)
end
lemma lll_oracle_default_code[code]:
"external_lll_solver x = Code.abort (STR ''no implementation of external_lll_solver specified'') (\<lambda> _. external_lll_solver x)"
by simp
text \<open>By default, external solvers are disabled.
For enabling an external solver, load it via a separate theory like \<^file>\<open>FPLLL_Solver.thy\<close>\<close>
overloading enable_external_lll_solver \<equiv> enable_external_lll_solver
begin
definition enable_external_lll_solver where "enable_external_lll_solver = False"
end
definition "short_vector_test_hybrid xs =
(let ys = map (vec_of_list o map int_of_integer) xs
in integer_of_int (sq_norm (short_vector_hybrid (3/2) ys)))"
(* export_code short_vector_test_hybrid in Haskell module_name LLL *)
end
|
module fmo_mod
use mqc_general
use mqc_algebra2
use mqc_gaussian
use iso_fortran_env
contains
function countNBasis(iAtom,atom2bfMap) Result(nBasis)
!
! This function returns an (intrinsic) integer giving the number of basis
! functions, <nBasis>, belonging to atomic center number <iAtom> according
! to the atom --> basis function map <atom2bfMap).
!
!
implicit none
integer(kind=int64),intent(in)::iAtom
type(MQC_Variable)::atom2bfMap
integer(kind=int64)::nBasis
integer(kind=int64)::bf1,bf2
!
bf1 = INT(MQC_Variable_get_MQC(atom2bfMap,[iAtom]))
bf2 = INT(MQC_Variable_get_MQC(atom2bfMap,[iAtom+1]))
nBasis = bf2-bf1
!
return
end function countNBasis
function build_atom2bfMap(nAtoms,bf2AtomMap) &
Result(atom2bfMap)
!
! This function produces an atom --> basis function map. The output array is
! dimensioned (nAtoms+1) long. Basis functions on atom center number i runs
! from atom2bfMap(i) to atom2bfMap(i+1)-1.
!
!
implicit none
integer(kind=int64),intent(in)::nAtoms
class(MQC_Variable)::bf2AtomMap
type(MQC_Variable)::temp
integer(kind=int64),dimension(:),allocatable::atom2bfMap
integer(kind=int64),dimension(1)::tempArray
integer(kind=int64)::i,currentAtom
!
!
! Allocate memory for atom2bfMap and then fill it.
!
allocate(atom2bfMap(nAtoms+1))
atom2bfMap = 0
atom2bfMap(nAtoms+1) = SIZE(bf2AtomMap)+1
call bf2AtomMap%print(iout=6,header='bf2AtomMap')
tempArray(1) = 1
do i = 1,SIZE(bf2AtomMap)
tempArray(1) = i
temp = MQC_Variable_get_MQC(bf2AtomMap,tempArray)
if(atom2bfMap(INT(temp)).eq.0) atom2bfMap(INT(temp)) = i
endDo
!
! In case there are atomic centers without any basis functions -- as there
! will be in the fragment calculations -- we have to step through
! <atom2bfMap> and replace zeros.
!
do i = nAtoms,1,-1
if(atom2bfMap(i).eq.0) atom2bfMap(i) = atom2bfMap(i+1)
endDo
!
return
end function build_atom2bfMap
function build_full2fragmentMap(iFragment,atom2fragment, &
atom2bfFull,bf2AtomFull,atom2bfFragment,bf2AtomFragment) &
Result(bfFull2FragmentMap)
!
! This function produces a fragment --> full basis set map for a particular
! fragment (number iFragment). To do thise work, the function needs the
! fragment number being considered <iFragment>, the fragment list over atoms
! <atom2fragment>, the full molecule's basis function --> atomic center
! map <bf2AtomFull>, and the current fragment job's basis function -->
! atomic center map <bf2AtomFragment>.
!
!
implicit none
integer(kind=int64),intent(in)::iFragment
type(mqc_variable)::atom2fragment,atom2bfFull,bf2AtomFull
type(mqc_variable)::atom2bfFragment,bf2AtomFragment
type(mqc_variable)::bfFull2FragmentMap
!
integer(kind=int64)::i,j,myAtom,myFragment
integer(kind=int64),dimension(:,:),allocatable::bfFull2FragmentMapTemp
!
! Do the map work.
!
allocate(bfFull2FragmentMapTemp(SIZE(bf2AtomFull,1),2))
!hph bfFull2FragmentMapTemp(:,:) = int(0.0)
do i = 1,SIZE(bf2AtomFull,1)
do j = 1,2
bfFull2FragmentMapTemp(i,j) = 0
endDo
endDo
! write(*,*)' Hrant: ',bfFull2FragmentMapTemp(1,1)
! call mqc_print(6,bfFull2FragmentMapTemp,header='Hrant: Flag 1')
write(*,*)
write(*,*)
write(*,*)' Hrant - Building frag->full map...'
write(*,*)' Fragment = ',iFragment
write(*,*)
do myAtom = 1,SIZE(atom2fragment)
myFragment = INT(MQC_Variable_get_MQC(atom2fragment,[myAtom]))
write(*,*)' myAtom = ',myAtom
write(*,*)' myFrag = ',myFragment
if(myFragment.eq.iFragment) then
j = INT(MQC_Variable_get_MQC(atom2bfFull,[myAtom]))
write(*,*)' MATCH! j = ',j, &
' nBasis = ',countNBasis(myAtom,atom2bfFull)
do i = INT(MQC_Variable_get_MQC(atom2bfFragment,[myAtom])), &
INT(MQC_Variable_get_MQC(atom2bfFragment,[myAtom+1]))-1
bfFull2FragmentMapTemp(j,1) = i
bfFull2FragmentMapTemp(j,2) = iFragment
j = j+1
endDo
endIf
endDo
bfFull2FragmentMap = bfFull2FragmentMapTemp
!
return
end function build_full2fragmentMap
function build_blockFragmentMatrixAO(iFragment,bfFull2Fragment, &
fragmentMatrix) Result(blockMatrix)
!
! This function pushes a matrix in a fragment AO basis (and sized NFragBasis
! x NFragBasis) out to a block in a full molecule AO basis.
!
!
implicit none
integer(kind=int64),intent(in)::iFragment
type(mqc_variable)::bfFull2Fragment,fragmentMatrix
type(mqc_variable)::blockMatrix
real(kind=real64),dimension(:,:),allocatable::blockMatrixTemp
!
integer(kind=int64)::i,j,nBasisFull,iFrag,jFrag,iFragBF,jFragBF
real(kind=real64)::temp
!
! Do the work...
!
nBasisFull = SIZE(bfFull2Fragment,1)
allocate(blockMatrixTemp(nBasisFull,nBasisFull))
!hph blockMatrixTemp = 0.0
do i = 1,nBasisFull
do j = 1,nBasisFull
blockMatrixTemp(i,j) = dfloat(0)
endDo
endDo
write(*,*)
do i = 1,nBasisFull
iFrag = INT(MQC_Variable_get_MQC(bfFull2Fragment,[i,2]))
if(iFrag.eq.iFragment) then
iFragBF = INT(MQC_Variable_get_MQC(bfFull2Fragment,[i,1]))
do j = 1,nBasisFull
jFrag = INT(MQC_Variable_get_MQC(bfFull2Fragment,[j,2]))
if(jFrag.eq.iFragment) then
jFragBF = INT(MQC_Variable_get_MQC(bfFull2Fragment,[j,1]))
temp = float(MQC_Variable_get_MQC(fragmentMatrix, &
[iFragBF,jFragBF]))
write(*,'(3x,''i='',I3,'' j='',I3,'' iFrag='',I3, &
'' jFrag='',I3,'' val='',f10.6)') i, &
j,iFrag,jFrag,temp
blockMatrixTemp(i,j) = &
float(MQC_Variable_get_MQC(fragmentMatrix, &
[iFragBF,jFragBF]))
endIf
endDo
endIf
endDo
write(*,*)
write(*,*)
blockMatrix = blockMatrixTemp
!
return
end function build_blockFragmentMatrixAO
end module fmo_mod
!
! *********************************************************************
! *********************************************************************
!
Program IPA_0001
Use MQC_Gaussian
Use MQC_Algebra2
Use MQC_Files
Use MQC_General
Use iso_fortran_env
! Written By: Samantha Bidwell
! Code Version: 0001
! Date: 2/25/20
! Purpose
! The program is developed to calculate the energy
! contribution from the mixing of the MO's of three fragments.
! This is done using the 1st, 2nd and 3rd order energy corrections
! of perturbation theory.
! General Information
! - This code ising gaussian matrix files as its input
! - The MQC package developed by the Hratchian group is
! used to analyze the matrix file.
! - To compile the code run the associated makefile.
! General Instructions for Using the Code
! 1. Run an optimization and frequency of the molecule you
! would like to study with the keyword output=matrix to
! create the matrix file.
! 2. Run individual jobs for each of fragments with the
! remaining molecules as ghost atoms also using the
! keyword output=matrix.
! 3. To complile the code...
! 4. To run the code (after it is compliled) use ./IPA_100
! molecule.mat frag1.mat frag2.mat frag3.mat
! Code Outline
! -- Overall variable declaration
! -- Read in the matrix files
! -- Save the fock, overlap, and coefficent matricies and
! the energy vectors
! -- Run the basic_information subroutine to calculate the
! HF_E, the IPM_E, the 2e_E, the 1e_E, and print the
! number of atoms, basis functions and electrons for each
! of the files.
! -- Check the the sum of the fragment jobs is equivilant
! to the overall molecule.
! -- Form the composite matricies using the proper basis
! function mapping technique.
! -- Transform all of the matricies into the FMO basis.
! -- Calculate the 1st, 2nd and 3rd order mixing for the
! fragments
! -- Print each of the energy corrections and emphasize
! the orbitals with the largest contributions.
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Variable Declarations
Implicit None
Character :: M, F1, F2, F3
Integer :: iout=6,p,q,r,s,i
Integer :: NAtom,NBasis,NEle
Integer :: NAtomTotal,NBasisTotal,NEleTotal
Integer :: M_NAtom,M_NBasis,M_NEle
Integer :: F1_NAtom,F1_NBasis,F1_NEle
Integer :: F2_NAtom,F2_NBasis,F2_NEle
Integer :: F3_NAtom,F3_NBasis,F3_NEle
Real :: N
Type(MQC_Variable) :: temp,temp1,temp2,temp3
Type(MQC_Variable) :: F_Comp,F_FMO_Comp,F_FMO_Molecule
Type(MQC_Variable) :: C_Comp,E_Comp
Type(MQC_Variable) :: First_Order_E,Second_Order_E,Third_Order_E
Type(MQC_Variable) :: DeltaE,VonE,VVonE,V,VV,VVV,TermOne,TermTwo
Type(MQC_Variable) :: DoubleDeltaE,EoneEtwo,term1minusterm2
Type(MQC_Variable) :: M_F,M_S,M_D,M_C,M_H,M_E
Type(MQC_Variable) :: F1_F,F1_S,F1_D,F1_C,F1_H,F1_E
Type(MQC_Variable) :: F2_F,F2_S,F2_D,F2_C,F2_H,F2_E
Type(MQC_Variable) :: F3_F,F3_S,F3_D,F3_C,F3_H,F3_E
Type(MQC_Gaussian_Unformatted_Matrix_File) :: M_Mat
Type(MQC_Gaussian_Unformatted_Matrix_File) :: F1_Mat
Type(MQC_Gaussian_Unformatted_Matrix_File) :: F2_Mat
Type(MQC_Gaussian_Unformatted_Matrix_File) :: F3_Mat
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Read in each of the command line arguments.
! Save the Fock, Overlap, Energy, Density and Coefficent matricies
! from each of the matrix files using the Basic_In formation
! subroutine.
Write(*,*) 'STEP: Calling each of the command line arguments &
and reading in all of the information'
Write(*,*) 'Reading in Molecule information.'
Call Get_Command_Argument(1,M)
Call Basic_Information(M,M_Mat,M_NAtom,M_NBasis,M_NEle, &
M_F,M,M_D,M_C,M_H,M_E)
Write(*,*) 'Reading in Fragment_1 information.'
Call Get_Command_Argument(1,F1)
Call Basic_Information(F1,F1_Mat,F1_NAtom,F1_NBasis,F1_NEle, &
F1_F,F1_S,F1_D,F1_C,F1_H,F1_E)
Write(*,*) 'Reading in Fragment_2 information.'
Call Get_Command_Argument(1,F2)
Call Basic_Information(F2,F2_Mat,F2_NAtom,F2_NBasis,F2_NEle, &
F2_F,F2_S,F2_D,F2_C,F2_H,F2_E)
Write(*,*) 'Reading in Fragment_3 information.'
Call Get_Command_Argument(1,F3)
Call Basic_Information(F3,F3_Mat,F3_NAtom,F3_NBasis,F3_NEle, &
F3_F,F3_S,F3_D,F3_C,F3_H,F3_E)
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Check that the number of basis functions, atoms and electrons
! are equal to their expected values.
Write(*,*) 'STEP: Checking that the number of atoms in each &
fragment input are equal:'
NAtomTotal=F1_NAtom+F2_NAtom+F3_NAtom
If (NAtomTotal.eq.3*M_NAtom) then
Write(iout,*) 'Atoms are equal. Continuing...'
Else
Write(iout,*) 'Atoms not equal. Program terminating.'
STOP
EndIf
NAtom=M_NAtom
Write(*,*) 'STEP: Checking that the number of basisfunctions &
in each fragment input are equal:'
NBasisTotal=F1_NBasis+F2_NBasis+F3_NBasis
If (NBasisTotal.eq.3*M_NBasis) then
Write(iout,*) 'Basis functions are equal. Continuing...'
Else
Write(iout,*) 'Basis functions not equal. Program terminating.'
STOP
EndIf
NBasis=M_NBasis
Write(*,*) 'STEP: Checking that the number of electrons &
in each fragment input are equal:'
NEleTotal=F1_NEle+F2_NEle+F3_NEle
If (NEleTotal.eq.3*M_NEle) then
Write(iout,*) 'Electrons are equal. Continuing...'
Else
Write(iout,*) 'Electrons not equal. Program terminating.'
STOP
EndIf
NEle=M_NEle
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Form the composite matricies.
Write(*,*) 'STEP: Forming the composite matricies.'
! The composite matrices that are formed are: Fock_Composite,
! Coefficent_Composite, Overlap_Composite and Energy_Composite.
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Transform each of the matricies into the FMO basis.
Write(*,*) 'STEP: Transforming each of the matricies into the &
fragment molecular orbital (FMO) basis.'
! These matricies are created to simplify the following energy
! corrections.
F_FMO_M =
F_FMO_C =
S_FMO_M =
S_FMO_C =
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! First Order Energy Correction
Write(*,*) 'STEP: Calculating the first order energy &
correction.'
Call First_Order_E%init(NBasisTotal,0)
Do p=1,NBasis
Call First_Order_E%put(F_FMO_Molecule%at(p,p)-F_FMO_Comp%at(p,p),p)
EndDo
Write(iout,*) ' '
Write(iout,*) '**********************************************&
************************************************************'
write(iout,*) 'The First Order Energy Correction'
Write(iout,*) '**********************************************&
************************************************************'
Call First_Order_E%print(iout,'First order:')
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Second Order Energy Correction
Write(*,*) 'STEP: Calculating the second order energy &
correction.'
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Third Order Energy Correction
Write(*,*) 'STEP: Calculating the third order energy &
correction.'
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
! Print the energy corrections and emphasize the mixing that leads
! to the largest contributions.
! ---------------------------------------------------------------------------
! ---------------------------------------------------------------------------
End Program IPA_0001
! ****************************************************************************
! ****************************************************************************
Subroutine Basic_Information(Commandline,Mat,NAtoms,NBasis, &
Nele,F,S,D,C,H,E)
Use MQC_Gaussian
Use MQC_Algebra2
Use MQC_Files
Use MQC_General
Use iso_fortran_env
! This subroutine is written to define:
! 1. Restricted or Unrestricted?
! 2. Print natoms, nbasis and nelectrons
! 3. The hartree fock energy
! 4. The IPM energy
! 5. The 1 and 2 electron energy
Implicit None
Character(len=256) :: Commandline
Integer :: iout=6, NAtoms, NBasis, Nele, i
Type(MQC_Variable) :: HFE, IPME, OneEle, TwoEle
Type(MQC_Variable) :: F, S, D, C, H, E
Type(MQC_Variable) :: FD, HD, tempIPM
Type(MQC_Gaussian_Unformatted_Matrix_File) :: Mat
Call Mat%load(Commandline)
Write(*,*) ' '
Write(*,*) 'SUB-STEP: Loading information from the *.mat &
file', Commandline
! Testing and printing if the job is restricted or unrestricted
Write(iout,*) 'Is restricted?', Mat%isrestricted()
Write(iout,*) 'Is unrestricted?', Mat%isunrestricted()
! Printing the number of ele, atoms and basis from the mat file
! and saving them.
Nele=Mat%getval('NElectrons')
Write(iout,*) 'NElectrons=', Nele
NAtoms=Mat%getval('NAtoms')
Write(iout,*) 'NAtoms=', NAtoms
Nele=Mat%getval('NBasis')
Write(iout,*) 'NBasis=', NBasis
! Load and save all need matricies/vectors (F,S,D,C,H,E)
Call Mat%getarray('alpha fock matrix', &
mqcVarOut=F)
Call Mat%getarray('overlap',mqcVarOut=S)
Call Mat%getarray('alpha density matrix', &
mqcVarOut=D)
Call Mat%getarray('alpha mo coefficents', &
mqcVarOut=C)
Call Mat%getarray('core hamiltonian alpha', &
mqcVarOut=H)
Call Mat%getarray('alpha orbital energies', &
mqcVarOut=E)
Write(*,*) ' '
Write(*,*) 'SUB-STEP: Calculating basic information using &
information for the *.mat file', Commandline
! Calculate the Hartree Fock Energy (HF=1/2(<FD>+1/2<HD>))
Call MQC_Variable_initialize(HFE,'real')
Call MQC_Variable_initialize(HD,'real')
Call MQC_Variable_initialize(FD,'real')
FD=contraction(F,D)
HD=contraction(H,D)
HFE=(1/2)*(float(FD)+((1/2)*float(HD)))
Call HFE%print(iout,'The HF energy is: ')
! Calculate the IPM Energy
Call MQC_Variable_initialize(IPME,'real')
Call MQC_Variable_initialize(tempIPM,'real')
Do i=1,Nele/2
!hph tempIPM=E%at(i)
IPME=float(IPME)+(2*float(tempIPM))
EndDo
Call IPME%print(iout,'The IPM energy is: ')
! Calculate the one-electron energy
Call MQC_Variable_initialize(OneEle,'real')
OneEle=contraction(F,D)-contraction(H,D)
Call OneEle%print(iout,'The One Electron Energy is: ')
! Calculate the two-electron energy
Call MQC_Variable_initialize(TwoEle,'real')
TwoEle=contraction(D,H)
Call TwoEle%print(iout,'The Two Electron Energy is: ')
write(*,*) ' '
write(*,*) 'SUB-STEP: Finishing basic information subroutine.'
End Subroutine Basic_Information
|
function x = ndmax(x,dim)
% NDMAX Multi-dimensional maximization.
% NDMAX(X,DIM) takes the maximum element along the dimensions in DIM,
% and squeezes the result.
% Written by Thomas P Minka
% (c) Microsoft Corporation. All rights reserved.
sz = size(x);
for i=1:length(dim)
x = max(x, [], dim(i));
end
x = mysqueeze(x);
addflops(2*(prod(sz)-prod(size(x))));
|
lemmas scaleR_minus_left = real_vector.scale_minus_left |
##### calculate the TSLS esitmators and covariance matrix estimator
para=function(ivmodel){
output=list()
fit1=lm(ivmodel$Dadj~ivmodel$Zadj-1)
output$gamma=coef(fit1)
names(output$gamma)=NULL
output$beta=c(KClass(ivmodel, k=1)$point.est)
hat_eps=ivmodel$Yadj-c(output$beta)*ivmodel$Dadj
hat_eta=resid(fit1)
output$sigmau=sqrt(sum(hat_eps^2)/(ivmodel$n-ivmodel$p))
output$sigmav=sqrt(sum(hat_eta^2)/(ivmodel$n-ivmodel$p))
output$rho=sum(hat_eta*hat_eps)/(ivmodel$n-ivmodel$p)/output$sigmau/output$sigmav
return(output)
}
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Class 1, NE 155
%%
\documentclass[xcolor=x11names,compress]{beamer}
\definecolor{CoolBlack}{rgb}{0.0, 0.18, 0.39}
%% General document %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{decorations.fractals}
\usepackage{hyperref}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Beamer Layout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\useoutertheme[subsection=false,shadow]{miniframes}
\useinnertheme{default}
\usefonttheme{serif}
\usepackage{palatino}
\usepackage{tabu}
% Links
\usepackage{hyperref}
\definecolor{links}{HTML}{003262}
\hypersetup{colorlinks,linkcolor=,urlcolor=links}
% addition of color
\usepackage{xcolor}
\definecolor{CoolBlack}{rgb}{0.0, 0.18, 0.39}
\definecolor{byellow}{rgb}{0.55037, 0.38821, 0.06142}
\definecolor{dgreen}{rgb}{0.,0.6,0.}
\definecolor{RawSienna}{cmyk}{0,0.72,1,0.45}
\definecolor{forestgreen(web)}{rgb}{0.13, 0.55, 0.13}
\definecolor{cardinal}{rgb}{0.77, 0.12, 0.23}
\setbeamerfont{title like}{shape=\scshape}
\setbeamerfont{frametitle}{shape=\scshape}
\setbeamercolor*{lower separation line head}{bg=CoolBlack}
\setbeamercolor*{normal text}{fg=black,bg=white}
\setbeamercolor*{alerted text}{fg=dgreen} % just testing; I think this looks better
\setbeamercolor*{example text}{fg=black}
\setbeamercolor*{structure}{fg=black}
\setbeamercolor*{palette tertiary}{fg=black,bg=black!10}
\setbeamercolor*{palette quaternary}{fg=black,bg=black!10}
% Margins
\usepackage{changepage}
\mode<presentation>
{
\definecolor{berkeleyblue}{HTML}{003262}
\definecolor{berkeleygold}{HTML}{FDB515}
\usetheme{Boadilla} % or try Darmstadt, Madrid, Warsaw, Boadilla...
%\usecolortheme{dove} % or try albatross, beaver, crane, ...
\setbeamercolor{structure}{fg=berkeleyblue,bg=berkeleygold}
\setbeamercolor{palette primary}{bg=berkeleyblue,fg=white} % changed this
\setbeamercolor{palette secondary}{fg=berkeleyblue,bg=berkeleygold} % changed this
\setbeamercolor{palette tertiary}{bg=berkeleyblue,fg=white} % changed this
\usefonttheme{structurebold} % or try serif, structurebold, ...
\useinnertheme{circles}
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{caption}[numbered]
\usebackgroundtemplate{}
}
%---
\renewcommand{\(}{\begin{columns}}
\renewcommand{\)}{\end{columns}}
\newcommand{\<}[1]{\begin{column}{#1}}
\renewcommand{\>}{\end{column}}
% adding slide numbers
\addtobeamertemplate{navigation symbols}{}{%
\usebeamerfont{footline}%
\usebeamercolor[fg]{footline}%
\hspace{1em}%
\insertframenumber/\inserttotalframenumber
}
% equation stuff
\newcommand{\Macro}{\ensuremath{\Sigma}}
\newcommand{\Sn}{\ensuremath{S_N} }
\newcommand{\vOmega}{\ensuremath{\hat{\Omega}}}
\usepackage{mathrsfs}
\usepackage[mathcal]{euscript}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{epsfig}
\usepackage{amsmath}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% title stuff for footer
\title{NE 155}
\author{R.\ N.\ Slaybaugh}
\date{January 21, 2017}
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}
\title{NE 155\\Introduction to Numerical Simulations in Radiation Transport}
\subtitle{Lecture 2: Computing}
\titlepage
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Outline}
%\tableofcontents
\begin{enumerate}
\item History and terminology
\vspace*{1 em}
% - define flops as measure of what we care about
% - chronological highlights of a few machines; show pictures, state details
\item Basic computer architecture
\vspace*{1 em}
% - hardware v software; we're talking about hardware now but the rest of the class will focus on software. We will care a little bit about the interface
% - definitions
% - Moore's law
\item Introduction to Parallelism
\vspace*{1 em}
% - basic considerations
% - types of parallelism
% - speedup
% - increase in use and potential
% - current status
\item Current supercomputers
% - Moore's law continuation?
% - GPUs
% - mic chips
% - What happens may have a large impact on algorithms
\end{enumerate}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{How do we measure utility?\footnote{\href{en.wikipedia.org}{en.wikipedia.org}}}
\textbf{IPS} (Instructions Per Second) is a measure of a computer's processor speed. IPS can be useful when comparing performance between processors made from a similar architecture, but are difficult to compare between CPU architectures
\vspace*{1 em}
\textbf{Clock rate} typically refers to the frequency at which a CPU is running. It is measured in the SI unit Hertz.
\vspace*{1 em}
\textbf{FLOPS} (FLoating-point Operations Per Second) is a measure of computer performance, useful in fields of scientific calculations that make heavy use of floating-point calculations.
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\scshape History}
\subsection{History}
\begin{frame}{Computing Machines, Origins}
\begin{figure}
\includegraphics[height=2.25in,clip]{../figs/RomanAbacus}
\caption{Roman Abacus, \href{http://history-computer.com/CalculatingTools/abacus.html}{http://history-computer.com/CalculatingTools/abacus.html}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Early Development of Computing}
\begin{figure}
\includegraphics[height=2in,clip]{../figs/BabbageDiffMachine}
\caption{Reconstruction of Babbage's Analytical Engine, the first general-purpose programmable computer, \href{http://en.wikipedia.org/wiki/History_of_computing_hardware
\#Punched_card_data_processing}{http://en.wikipedia.org/wiki/History\_of\_computing\_hardware
\#Punched\_card\_data\_processing}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{First Electromechanical Computers}
\begin{figure}
\includegraphics[height=2in,clip]{../figs/Z3DeutschesMuseum}
\caption{Zuse Z3 replica on display at Deutsches Museum in Munich, \href{http://en.wikipedia.org/wiki/Z3_(computer)}{http://en.wikipedia.org/wiki/Z3\_(computer)}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Stored Programs}
\begin{figure}
\includegraphics[height=2in,clip]{../figs/ManchesterMark1}
\caption{The Manchester Mark 1 was one of the world's first stored-program computers, \href{http://www.computer50.org/mark1/ip-mm1.mark1.html}{http://www.computer50.org/mark1/ip-mm1.mark1.html}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Microprogramming, Magnetic Storage, Transistors}
\begin{itemize}
\item 1951: realization that CPUs can be controlled by a miniature, highly specialized computer program in high-speed ROM \vspace*{0.5 em}
\item 1954: magnetic core memory was rapidly displacing most other forms of temporary storage \vspace*{0.5 em}
\item 1956: IBM introduced the first disk storage unit: using 50 24-inch metal disks, it stored 5 MB of data for \$10,000 per MB (\$90,000 in 2014 \$s)\vspace*{0.5 em}
\item 1947: invention of the bipolar transistor; this replaced vacuum tubes by 1955 $\rightarrow$ ``Second Generation" of computer designs
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Supercomputers}
\begin{figure}
\includegraphics[height=2in,clip]{../figs/Atlas1963}
\caption{The University of Manchester Atlas 1963, \href{http://en.wikipedia.org/wiki/History_of_computing_hardware
\#Punched_card_data_processing}{http://en.wikipedia.org/wiki/History\_of\_computing\_hardware
\#Punched\_card\_data\_processing}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Integrated Circuit}
With the advent of the \alert{transistor} and the work on semi-conductors generally, it now seems possible to envisage electronic equipment in a solid block with no connecting wires. The block may consist of layers of insulating, conducting, rectifying and amplifying materials, the \alert{electronic functions being connected directly} by cutting out areas of the various layers.\\
\vspace*{1.5 em}
\hspace*{0.5 in}Geoffrey W.A. Dummer, Royal Radar Establishment of the Ministry of Defence, 1952
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Generations 4-6}
\begin{itemize}
\item Very large scale integration of devices on chip \vspace*{0.5 em}
\item C and FORTRAN programming languages\vspace*{0.5 em}
\item \alert{UNIX} operating system (Bell labs, Berkeley)\vspace*{0.5 em}
\item Large scale parallel processing; supercomputing centers\vspace*{0.5 em}
\item Shared and distributed memory\vspace*{0.5 em}
\item Parallel/vector shared/distributed memory combinations\vspace*{0.5 em}
\item High speed networking
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\scshape Computer Architecture}
\subsection{Computer Architecture}
\begin{frame}{Computer Architecture}
\begin{figure}
\begin{center}
\includegraphics[height=2.25in,clip]{../figs/ComputerArchitecture}
\end{center}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Components}
\begin{figure}
\begin{center}
\includegraphics[height=2.25in,clip]{../figs/Components}
\end{center}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\begin{frame}{Types of Memory}
%\begin{itemize}
%\item \textbf{Read-only memory} (ROM): storage medium in which data cannot be modified, so it is mainly used to distribute firmware
%\item \textbf{Random Access Memory} (RAM): allows stored data to be accessed directly in any random order\footnote{Many computer systems have a memory hierarchy consisting different systems referred to collectively as ``RAM". The various subsystems can have very different access times.}
%\item Other data storage media only read and write data consecutively (time impact)
%\end{itemize}
%\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Moore's ``Law"}
The number of transistors on integrated circuits doubles approximately every 18 months.
\begin{columns}
\begin{column}{0.7\textwidth}
\begin{itemize}
\item In 1965 Gordon E. Moore described this trend and predicted it to hold for at least 10 years\vspace*{0.5 em}
\item He worked at Intel\vspace*{0.5 em}
\item The trend has held, but is expected to change around now...
\end{itemize}
\end{column}
\begin{column}{0.3\textwidth}
\includegraphics[height=1.5in,clip]{../figs/GordonMoore1975}
\end{column}
\end{columns}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Moore's ``Law"}
\begin{figure}
\includegraphics[height=2.5in,clip]{../figs/Moores-Law-120-Years}
\caption{By Steve Jurvetson - \url{https://www.flickr.com/photos/jurvetson/31409423572/}, CC BY 2.0}%, \url{https://commons.wikimedia.org/w/index.php?curid=55002144}}
\end{figure}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\scshape Parallelism}
\subsection{Parallelism}
\begin{frame}{What is Parallel Architecture?}
A \textcolor{dgreen}{parallel computer} is a collection of processing elements that cooperate to solve large problems
quickly
\begin{itemize}
\item Resource allocation
\begin{itemize}
\item How much \textcolor{dgreen}{memory}?
\item How \textcolor{dgreen}{many} elements?
\item How \textcolor{dgreen}{powerful} are the elements?
\end{itemize}
\item Data access, Communication, and Synchronization
\begin{itemize}
\item How do the elements cooperate and \textcolor{dgreen}{communicate}?
\item How are \textcolor{dgreen}{data transmitted} between processors?
\item What are the \textcolor{dgreen}{abstractions} and primitives for cooperation?
\end{itemize}
\item Performance and Scalability
\begin{itemize}
\item How does it all translate into \textcolor{dgreen}{performance}?
\item How does it \textcolor{dgreen}{scale}?
\end{itemize}
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Forms of Parallelism}
\begin{itemize}
\item \textbf{Bit level}: increases in word size reduced the \# of instructions the processor needs
\item \textbf{Instruction level}: hardware and/or software perform operations simultaneously when possible
\item \textbf{Memory system}: overlap of memory operations with computation
\item \textbf{Operating system}: multiple jobs run in parallel on commodity symmetric multiprocessors (SMPs)
\end{itemize}
There are limitations to all of these
\vspace*{1 em}
To achieve high performance, the programmer needs to identify, schedule, and coordinate parallel tasks and data
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Performance}
\begin{columns}
\begin{column}{0.65\textwidth}
\begin{itemize}
\item \textbf{Strong Scaling}: increase element count with problem size fixed (solve a problem faster)\\
\vspace*{0.5 em}
$Speedup = \frac{\text{Time with P cores}}{\text{Time with 1 core}}$
\vspace*{1 em}
\item \textbf{Weak Scaling}: increase element count and problem size to keep problem size per element fixed (solve bigger problems)\\
\vspace*{0.5 em}
$Speedup = \frac{\text{Time with 1 core}}{\text{Time with P cores}}$
\end{itemize}
\end{column}
\begin{column}{0.35\textwidth}
\includegraphics[height=2in,clip]{../figs/PerformanceGap}
\end{column}
\end{columns}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Types of Memory}
%\begin{itemize}
%\item \textbf{Shared Memory}: single memory space used by all processors; processors do not have to know where data resides
%\item \textbf{Distributed Memory}: each processor has its own private memory; tasks can only operate on local data; communication with a remote processor to get remote data
%\item \textbf{Distributed Shared Memory}: each node of a cluster has access to a large shared memory in addition to each node's limited non-shared private memory.
%\end{itemize}
\begin{center}
Shared \hspace*{2 em} Distributed \hspace*{2 em} Distributed Shared
\includegraphics[height=2.75in,clip]{../figs/MemorySystems}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{GPUs}
\begin{itemize}
\item Graphics Processing Unit (\textbf{GPU}): highly parallel, good for processing large blocks of data
\item General Purpose GPU (\textbf{GPGPU}): Using a GPU to do CPU work - computational science instead of graphics
\end{itemize}
\begin{center}
CPU vs.\ GPU memory structure \\ \vspace*{1 em}
\includegraphics[height=1.5in,clip]{../figs/GPUmemory}
% source https://www.bsc.es/research-development/research-areas/computer-architecture-and-codesign/memory-hierarchy-gpu
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{MICs}
\begin{itemize}
\item Many Integrated Core (\textbf{MIC}): combines many CPU cores onto a single chip
\item \textbf{Heterogeneous} architecture: GPUs + CPUs or MICs + CPUs, etc.
\end{itemize}
\begin{center}
Intel Xeon Phi Board\\ \vspace*{1 em}
\includegraphics[height=1.75in,clip]{../figs/Intel-Xeon-Phi-Board}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{\scshape Supercomputing}
%\subsection{Supercomputing}
%\begin{frame}{Scientific Computing Demand}
%
%\begin{center}
%\includegraphics[height=2.75in,clip]{../figs/MemoryNeeds}
%\end{center}
%
%\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{\href{https://www.top500.org/statistics/perfdevel/}{Top 500 Computers, Nov 2016}}
\begin{center}
\begin{figure}
\includegraphics[height=2.75in]{../figs/Supercomputers-history-2020}
\caption{\url{https://www.top500.org/statistics/perfdevel/}}
\end{figure}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{\href{https://www.top500.org/lists/2016/11/}{Top 10 Computers, Nov 2020}}
\begin{center}
\begin{figure}
\includegraphics[height=2.5in]{../figs/2020-top-5}
\caption{\url{https://www.top500.org/lists/2020/11/}}
\end{figure}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Power Consumption, Nov 2013}
\begin{center}
\includegraphics[height=2.25in]{../figs/Top500-power}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Power Efficiency, Nov 2013}
\begin{center}
\includegraphics[height=2.5in]{../figs/Green500evolution}
%"Green500 evolution" by Stefan Parviainen - Own work. Licensed under CC0 via Commons - https://commons.wikimedia.org/wiki/File:Green500_evolution.svg#/media/File:Green500_evolution.svg
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Power and Efficiency Trends}
\begin{center}
\begin{figure}
\includegraphics[height=2.75in]{../figs/35years-processors}
\caption{\url{https://www.karlrupp.net/2015/06/40-years-of-microprocessor-trend-data/}}
\end{figure}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Where are we going?}
\begin{center}
\includegraphics[height=2.25in]{../figs/road}
\end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{}
\begin{frame}{Recap}
\begin{itemize}
\item Humans have been working to use machines for computation for a very long time\vspace*{0.5 em}
\item The 20th century saw the development of the computers we know today $\rightarrow$ development of computational science as a field\vspace*{0.5 em}
\item A revolution in supercomputing began at the end of the 20th century $\rightarrow$ \alert{computational science is a major contributor to knowledge}\vspace*{0.5 em}
\item We are reaching the limits of ``traditional" architecture growth\vspace*{0.5 em}
\item What we can compute and how is tightly tied to computer architecture development
\end{itemize}
\end{frame}
\end{document} |
import os
import numpy as np
import matplotlib.pyplot as plt
os.system("g++ sumas.cpp -o sumas.x")
os.system("./sumas.x > datos.dat")
def leer(filename):
archivo = open(filename,"r")
lineas = archivo.readlines()
return lineas
data = leer("datos.dat")
print(data[0])
print(data[1]) |
! This file was generated by gpufort
module zhetrd_gpu_kernels
use hip
implicit none
interface
subroutine launch_krnl_2b8e8f_0(grid,&
block,&
sharedMem,&
stream,&
a,&
d,&
n) bind(c, name="launch_krnl_2b8e8f_0")
use iso_c_binding
use hip
implicit none
type(dim3),intent(IN) :: grid
type(dim3),intent(IN) :: block
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
TODO declaration not found :: a
TODO declaration not found :: d
integer,value :: n
end subroutine
subroutine launch_krnl_2b8e8f_0_auto(sharedMem,&
stream,&
a,&
d,&
n) bind(c, name="launch_krnl_2b8e8f_0_auto")
use iso_c_binding
use hip
implicit none
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
TODO declaration not found :: a
TODO declaration not found :: d
integer,value :: n
end subroutine
subroutine launch_krnl_9c27cb_1(grid,&
block,&
sharedMem,&
stream,&
iw,&
n,&
w) bind(c, name="launch_krnl_9c27cb_1")
use iso_c_binding
use hip
implicit none
type(dim3),intent(IN) :: grid
type(dim3),intent(IN) :: block
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
integer,value :: iw
integer,value :: n
TODO declaration not found :: w
end subroutine
subroutine launch_krnl_9c27cb_1_auto(sharedMem,&
stream,&
iw,&
n,&
w) bind(c, name="launch_krnl_9c27cb_1_auto")
use iso_c_binding
use hip
implicit none
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
integer,value :: iw
integer,value :: n
TODO declaration not found :: w
end subroutine
subroutine launch_zher2_mv_kernel(grid,&
block,&
sharedMem,&
stream,&
n,&
m,&
ldv,&
ldw,&
ldw2) bind(c, name="launch_zher2_mv_kernel")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: n
integer,value :: m
integer,value :: ldv
integer,value :: ldw
integer,value :: ldw2
end subroutine
subroutine launch_zlarfg_kernel(grid,&
block,&
sharedMem,&
stream,&
n,&
tau,&
e,&
x) bind(c, name="launch_zlarfg_kernel")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: n
complex(kind=8),value :: tau
real(kind=8),value :: e
type(c_ptr),value :: _x
end subroutine
subroutine launch_zher2_mv_zlarfg_kernel(grid,&
block,&
sharedMem,&
stream,&
n,&
m,&
ldv,&
ldw,&
ldw2,&
tau,&
e,&
finished) bind(c, name="launch_zher2_mv_zlarfg_kernel")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: n
integer,value :: m
integer,value :: ldv
integer,value :: ldw
integer,value :: ldw2
complex(kind=8),value :: tau
real(kind=8),value :: e
integer,value :: finished
end subroutine
subroutine launch_stacked_zgemv_c(grid,&
block,&
sharedMem,&
stream,&
m,&
n,&
ldv,&
ldw,&
v,&
w,&
x) bind(c, name="launch_stacked_zgemv_c")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _x
end subroutine
subroutine launch_stacked_zgemv_n(grid,&
block,&
sharedMem,&
stream,&
m,&
n,&
ldv,&
ldw,&
v,&
w,&
z1,&
z2) bind(c, name="launch_stacked_zgemv_n")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _z1
type(c_ptr),value :: _z2
end subroutine
subroutine launch_finish_w_col_kernel(grid,&
block,&
sharedMem,&
stream,&
n,&
tau,&
x,&
y) bind(c, name="launch_finish_w_col_kernel")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: n
complex(kind=8),value :: tau
type(c_ptr),value :: _x
type(c_ptr),value :: _y
end subroutine
subroutine launch_stacked_zgemv_n_finish_w(grid,&
block,&
sharedMem,&
stream,&
m,&
n,&
ldv,&
ldw,&
v,&
w,&
z1,&
z2,&
tau,&
x,&
y2,&
finished) bind(c, name="launch_stacked_zgemv_n_finish_w")
use iso_c_binding
use hip
implicit none
type(dim3,,intent(IN, :: grid
type(dim3,,intent(IN, :: block
integer(c_int,,intent(IN, :: sharedMem
type(c_ptr,,value,intent(IN, :: stream
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _z1
type(c_ptr),value :: _z2
complex(kind=8),value :: tau
type(c_ptr),value :: _x
type(c_ptr),value :: _y2
integer,value :: finished
end subroutine
end interface
contains
subroutine launch_krnl_2b8e8f_0_cpu(sharedMem,&
stream,&
a,&
d,&
n)
use iso_c_binding
use hip
implicit none
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
TODO declaration not found :: a
TODO declaration not found :: d
integer,value :: n
integer :: j
do j = 33, N
!A(j-1, j) = e(j-1) ! JR Not strictly needed so skipping this copy
d(j) = A(j, j)
end do
end subroutine
subroutine launch_krnl_9c27cb_1_cpu(sharedMem,&
stream,&
iw,&
n,&
w)
use iso_c_binding
use hip
implicit none
integer(c_int),intent(IN) :: sharedMem
type(c_ptr),value,intent(IN) :: stream
integer,value :: iw
integer,value :: n
TODO declaration not found :: w
integer :: k
do k = 1, N - 1
W(k, iw) = dcmplx(0, 0)
end do
end subroutine
subroutine launch_zher2_mv_kernel_cpu(n,&
m,&
ldv,&
ldw,&
ldw2)
use iso_c_binding
use hip
implicit none
integer,value :: n
integer,value :: m
integer,value :: ldv
integer,value :: ldw
integer,value :: ldw2
integer :: i
integer :: j
integer :: istat
complex(kind=8) :: val
real(kind=8) :: rv
real(kind=8) :: iv
implicit none
integer, value :: N, M, ldv, ldw, ldw2
complex(8), dimension(1:ldv, 1:M), device, intent(in) :: V
complex(8), dimension(1:ldw, 1:M), device, intent(in) :: W
complex(8), dimension(1:ldw2, 2), device :: W2
!DIR$ IGNORE_TKR x
real(8), dimension(1:2*N), device :: x
integer :: i, j, istat
complex(8) :: val
real(8) :: rv, iv
i = (blockIdx%x - 1)*blockDim%x + threadIdx%x
j = (blockIdx%y - 1)*blockDim%y + threadIdx%y
if (i <= N .and. j <= M) then
val = -conjg(W(N, j))*V(i, j) - conjg(V(N, j))*W(i, j)
rv = dble(val)
iv = dimag(val)
! Zero out imaginary part on diagonal
if (i == N) then
iv = 0.d0
endif
! Update x
istat = atomicadd(x(2*i - 1), rv)
istat = atomicadd(x(2*i), iv)
endif
if (threadIdx%y == 1) then
! Zero out column for zhemv call
if (i <= N) W2(i, 1) = 0
! Zero out workspace for intermediate zgemv results
if (i <= M) then
W2(N + i, 1) = 0
W2(N + i, 2) = 0
endif
endif
end subroutine
subroutine launch_zlarfg_kernel_cpu(n,&
tau,&
e,&
_x)
use iso_c_binding
use hip
implicit none
integer,value :: n
complex(kind=8),value :: tau
real(kind=8),value :: e
type(c_ptr),value :: _x
complex(8),target :: x()
integer :: tid
integer :: i
integer :: j
integer :: nb
integer :: istat
integer :: laneid
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: rv3
real(kind=8) :: scal
real(kind=8) :: invscal
real(kind=8) :: alphar
real(kind=8) :: alphai
real(kind=8) :: beta
real(kind=8) :: rsum
real(kind=8) :: isum
complex(kind=8) :: cv1
real(kind=8) :: xnorm
complex(kind=8) :: alpha_s
CALL hipCheck(hipMemcpy(c_loc(x),_x,C_SIZEOF(x),hipMemcpyDeviceToHost))
implicit none
integer, value :: N
complex(8), device :: tau
real(8), device :: e
complex(8), dimension(N), device :: x
integer :: tid, i, j, nb, istat, laneID
real(8) :: rv1, rv2, rv3, scal, invscal, alphar, alphai, beta, rsum, isum
complex(8) :: cv1
real(8), shared :: xnorm
complex(8), shared :: alpha_s
tid = threadIdx%x
laneID = iand(tid, 31)
if (tid == 1) then
alpha_s = x(N)
xnorm = 0.0_8
endif
call syncthreads()
alphar = dble(alpha_s)
alphai = dimag(alpha_s)
rsum = 0.0_8
nb = ceiling(real(N)/blockDim%x) ! number of blocks down column
i = tid
do j = 1, nb
! All threads perform their product, zero if out of bounds
if (i <= N - 1) then
cv1 = x(i)
rv2 = dble(cv1); rv3 = dimag(cv1)
rv1 = rv2*rv2 + rv3*rv3
else
rv1 = 0.0_8
endif
rsum = rsum + rv1
i = i + blockDim%x
end do
! Partial sum within warps using shuffle
rv1 = rsum
rv2 = __shfl_down(rv1, 1)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 2)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 4)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 8)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 16)
rv1 = rv1 + rv2
if (laneID == 1) then
istat = atomicadd(xnorm, rv1)
endif
call syncthreads()
if (xnorm == 0.0_8 .and. alphai == 0.0_8) then
if (tid == 1) then
tau = 0.0_8
endif
else
if (tid == 1) then
xnorm = sqrt(xnorm)
rv1 = abs(alphar)
rv2 = abs(alphai)
! not taking abs of xnorm
scal = max(rv1, rv2, xnorm)
invscal = 1.d0/scal
rv1 = rv1*invscal
rv2 = rv2*invscal
xnorm = xnorm*invscal
beta = -sign(scal*sqrt(rv1*rv1 + rv2*rv2 + xnorm*xnorm), alphar)
tau = dcmplx((beta - alphar)/beta, -alphai/beta)
!zladiv
rv1 = dble(alpha_s - beta)
rv2 = dimag(alpha_s - beta)
if (abs(rv2) .lt. abs(rv1)) then
xnorm = rv2/rv1
invscal = 1.d0/(rv1 + rv2*xnorm)
alpha_s = dcmplx(invscal, -xnorm*invscal)
else
xnorm = rv1/rv2
invscal = 1.d0/(rv2 + rv1*xnorm)
alpha_s = dcmplx(xnorm*invscal, -invscal)
endif
e = beta ! store beta in e vector
endif
call syncthreads()
do i = tid, N, blockDim%x
cv1 = x(i)
if (i <= N - 1) then
cv1 = alpha_s*cv1
elseif (i == N) then
!x(i) = 1.0_8
cv1 = dcmplx(1.0_8, 0.0_8)
endif
x(i) = cv1
end do
endif
CALL hipCheck(hipMemcpy(_x,c_loc(x),C_SIZEOF(x),hipMemcpyHostToDevice))
end subroutine
subroutine launch_zher2_mv_zlarfg_kernel_cpu(n,&
m,&
ldv,&
ldw,&
ldw2,&
tau,&
e,&
finished)
use iso_c_binding
use hip
implicit none
integer,value :: n
integer,value :: m
integer,value :: ldv
integer,value :: ldw
integer,value :: ldw2
complex(kind=8),value :: tau
real(kind=8),value :: e
integer,value :: finished
integer :: i
integer :: j
integer :: tx
integer :: ty
integer :: tid
integer :: nb
integer :: laneid
integer :: istat
integer :: nblocks
integer :: nfinished
complex(kind=8) :: val
real(kind=8) :: rv
real(kind=8) :: iv
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: rv3
real(kind=8) :: scal
real(kind=8) :: invscal
real(kind=8) :: alphar
real(kind=8) :: alphai
real(kind=8) :: beta
real(kind=8) :: rsum
real(kind=8) :: isum
complex(kind=8) :: cv1
real(kind=8) :: xnorm
complex(kind=8) :: alpha_s
implicit none
integer, value :: N, M, ldv, ldw, ldw2
complex(8), dimension(1:ldv, 1:M), device, intent(in) :: V
complex(8), dimension(1:ldw, 1:M), device, intent(in) :: W
complex(8), dimension(1:ldw2, 2), device :: W2
!DIR$ IGNORE_TKR x
real(8), dimension(1:2*N), device :: x
complex(8), dimension(1:N), device :: x2
complex(8), device :: tau
real(8), device :: e
integer :: i, j, tx, ty, tid, nb, laneid, istat, nBlocks
integer, device :: finished
integer, shared :: nFinished
complex(8) :: val
real(8) :: rv, iv
real(8) :: rv1, rv2, rv3, scal, invscal, alphar, alphai, beta, rsum, isum
complex(8) :: cv1
real(8), shared :: xnorm
complex(8), shared :: alpha_s
tx = threadIdx%x
ty = threadIdx%y
i = (blockIdx%x - 1)*blockDim%x + tx
j = (blockIdx%y - 1)*blockDim%y + ty
nBlocks = gridDim%x*gridDim%y
!if (i > N .or. j > M) return
if (i <= N .and. j <= M) then
val = -conjg(W(N, j))*V(i, j) - conjg(V(N, j))*W(i, j)
rv = dble(val)
iv = dimag(val)
! Zero out imaginary part on diagonal
if (i == N) then
iv = 0.d0
endif
! Update x
istat = atomicadd(x(2*i - 1), rv)
istat = atomicadd(x(2*i), iv)
endif
if (ty == 1) then
! Zero out column for zhemv call
if (i <= N) W2(i, 1) = 0
! Zero out workspace for intermediate zgemv results
if (i <= M) then
W2(N + i, 1) = 0
W2(N + i, 2) = 0
endif
endif
call threadfence()
nFinished = 0
call syncthreads()
if (tx + ty == 2) nFinished = atomicinc(finished, nBlocks - 1)
call syncthreads()
if (nFinished < nBlocks - 1) return
! Begin zlarfg work with last block
if (N == 1) return
tid = tx + (ty - 1)*blockDim%x
laneID = iand(tid, 31)
if (tid == 1) then
alpha_s = x2(N - 1)
xnorm = 0.0_8
endif
call syncthreads()
alphar = dble(alpha_s)
alphai = dimag(alpha_s)
rsum = 0.0_8
nb = ceiling(real(N - 1)/(blockDim%x*blockDim%y)) ! number of blocks down column
i = tid
do j = 1, nb
! All threads perform their product, zero if out of bounds
if (i <= N - 2) then
cv1 = x2(i)
rv2 = dble(cv1); rv3 = dimag(cv1)
rv1 = rv2*rv2 + rv3*rv3
else
rv1 = 0.0_8
endif
rsum = rsum + rv1
i = i + blockDim%x*blockDim%y
end do
! Partial sum within warps using shuffle
rv1 = rsum
rv2 = __shfl_down(rv1, 1)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 2)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 4)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 8)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 16)
rv1 = rv1 + rv2
if (laneID == 1) then
istat = atomicadd(xnorm, rv1)
endif
call syncthreads()
if (xnorm == 0.0_8 .and. alphai == 0.0_8) then
if (tid == 1) then
tau = 0.0_8
endif
else
if (tid == 1) then
xnorm = sqrt(xnorm)
rv1 = abs(alphar)
rv2 = abs(alphai)
! not taking abs of xnorm
scal = max(rv1, rv2, xnorm)
invscal = 1.d0/scal
rv1 = rv1*invscal
rv2 = rv2*invscal
xnorm = xnorm*invscal
beta = -sign(scal*sqrt(rv1*rv1 + rv2*rv2 + xnorm*xnorm), alphar)
tau = dcmplx((beta - alphar)/beta, -alphai/beta)
!zladiv
rv1 = dble(alpha_s - beta)
rv2 = dimag(alpha_s - beta)
if (abs(rv2) .lt. abs(rv1)) then
xnorm = rv2/rv1
invscal = 1.d0/(rv1 + rv2*xnorm)
alpha_s = dcmplx(invscal, -xnorm*invscal)
else
xnorm = rv1/rv2
invscal = 1.d0/(rv2 + rv1*xnorm)
alpha_s = dcmplx(xnorm*invscal, -invscal)
endif
e = beta ! store beta in e vector
endif
call syncthreads()
do i = tid, N - 1, blockDim%x*blockDim%y
cv1 = x2(i)
if (i <= N - 2) then
cv1 = alpha_s*cv1
elseif (i == N - 1) then
!x(i) = 1.0_8
cv1 = dcmplx(1.0_8, 0.0_8)
endif
x2(i) = cv1
end do
endif
end subroutine
subroutine launch_stacked_zgemv_c_cpu(m,&
n,&
ldv,&
ldw,&
_v,&
_w,&
_x)
use iso_c_binding
use hip
implicit none
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _x
complex(8), M), intent(in) ,target :: v()
complex(8), M), intent(in) ,target :: w()
complex(8), intent(in) ,target :: x()
integer :: i
integer :: j
integer :: tx
integer :: ty
integer :: istat
complex(kind=8) :: val
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: iv1
real(kind=8) :: iv2
real(kind=8) :: xr
real(kind=8) :: xi
CALL hipCheck(hipMemcpy(c_loc(v),_v,C_SIZEOF(v),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(w),_w,C_SIZEOF(w),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(x),_x,C_SIZEOF(x),hipMemcpyDeviceToHost))
use cudafor
implicit none
integer, value :: M, N, ldv, ldw
complex(8), dimension(ldv, M), device, intent(in) :: V
complex(8), dimension(ldw, M), device, intent(in) :: W
complex(8), dimension(N), device, intent(in) :: x
!DIR$ IGNORE_TKR z1, z2
real(8), dimension(2*M), device :: z1, z2
!complex(8), dimension(M), device, intent(in) :: z1, z2
!real(8), dimension(32), shared :: r_s
!real(8), dimension(32), shared :: i_s
integer :: i, j, tx, ty, istat
complex(8) :: val
real(8) :: rv1, rv2, iv1, iv2, xr, xi
tx = threadIdx%x
ty = threadIdx%y
i = (blockIdx%y - 1)*blockDim%y + ty
j = (blockIdx%x - 1)*blockDim%x + tx
!if (i > 2*M .or. j > N) return
if (i > 2*M) return
val = x(j)
xr = dble(val); xi = dimag(val)
if (j > N) then
!val = dcmplx(0,0)
rv1 = 0.d0; iv1 = 0.d0
else
if (i > M) then
val = W(j, i - M)
else
val = V(j, i)
endif
rv2 = dble(val); iv2 = dimag(val)
rv1 = rv2*xr + iv2*xi
iv1 = rv2*xi - iv2*xr
endif
!Partial sum within warps using shuffle
rv2 = __shfl_down(rv1, 1)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 2)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 4)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 8)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 16)
rv1 = rv1 + rv2
!if (tx == 1) then
!r_s(ty + k*blockDim%y) = rv1
!r_s(ty) = rv1
!endif
!Partial sum within warps using shuffle
iv2 = __shfl_down(iv1, 1)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 2)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 4)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 8)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 16)
iv1 = iv1 + iv2
!if (tx == 1) then
!i_s(ty + k*blockDim%y) = iv1
!i_s(ty) = iv1
!endif
!call syncthreads()
!if (ty == 1 .and. i+tx-1 <= 2*M) then
! if (i+tx-1 > M) then
! istat = atomicadd(z2(2*(i+tx-1-M) - 1), r_s(tx))
! istat = atomicadd(z2(2*(i+tx-1-M)), i_s(tx))
! else
! istat = atomicadd(z1(2*(i+tx-1) - 1), r_s(tx))
! istat = atomicadd(z1(2*(i+tx-1)), i_s(tx))
! endif
!endif
if (tx == 1) then
if (i > M) then
istat = atomicadd(z2(2*(i - M) - 1), rv1)
istat = atomicadd(z2(2*(i - M)), iv1)
else
istat = atomicadd(z1(2*i - 1), rv1)
istat = atomicadd(z1(2*i), iv1)
endif
endif
return
CALL hipCheck(hipMemcpy(_v,c_loc(v),C_SIZEOF(v),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_w,c_loc(w),C_SIZEOF(w),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_x,c_loc(x),C_SIZEOF(x),hipMemcpyHostToDevice))
end subroutine
subroutine launch_stacked_zgemv_n_cpu(m,&
n,&
ldv,&
ldw,&
_v,&
_w,&
_z1,&
_z2)
use iso_c_binding
use hip
implicit none
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _z1
type(c_ptr),value :: _z2
complex(8), N), intent(in) ,target :: v()
complex(8), N), intent(in) ,target :: w()
complex(8), intent(in) ,target :: z1()
complex(8), intent(in) ,target :: z2()
integer :: i
integer :: j
integer :: tx
integer :: ty
integer :: istat
complex(kind=8) :: val1
complex(kind=8) :: val2
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: iv1
real(kind=8) :: iv2
real(kind=8) :: xr
real(kind=8) :: xi
CALL hipCheck(hipMemcpy(c_loc(v),_v,C_SIZEOF(v),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(w),_w,C_SIZEOF(w),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(z1),_z1,C_SIZEOF(z1),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(z2),_z2,C_SIZEOF(z2),hipMemcpyDeviceToHost))
use cudafor
implicit none
integer, value :: M, N, ldv, ldw
complex(8), dimension(ldv, N), device, intent(in) :: V
complex(8), dimension(ldw, N), device, intent(in) :: W
complex(8), dimension(N), device, intent(in) :: z1, z2
!DIR$ IGNORE_TKR y
real(8), dimension(2*M), device :: y
integer :: i, j, tx, ty, istat
complex(8) :: val1, val2
real(8) :: rv1, rv2, iv1, iv2, xr, xi
tx = threadIdx%x
ty = threadIdx%y
i = (blockIdx%x - 1)*blockDim%x + tx
j = (blockIdx%y - 1)*blockDim%y + ty
if (i > M .or. j > 2*N) return
if (j > N) then
val1 = z2(j - N)
val2 = V(i, j - N)
else
val1 = z1(j)
val2 = W(i, j)
endif
xr = dble(val1); xi = dimag(val1)
rv2 = dble(val2); iv2 = dimag(val2)
rv1 = -rv2*xr + iv2*xi
iv1 = -rv2*xi - iv2*xr
istat = atomicadd(y(2*i - 1), rv1)
istat = atomicadd(y(2*i), iv1)
return
CALL hipCheck(hipMemcpy(_v,c_loc(v),C_SIZEOF(v),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_w,c_loc(w),C_SIZEOF(w),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_z1,c_loc(z1),C_SIZEOF(z1),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_z2,c_loc(z2),C_SIZEOF(z2),hipMemcpyHostToDevice))
end subroutine
subroutine launch_finish_w_col_kernel_cpu(n,&
tau,&
_x,&
_y)
use iso_c_binding
use hip
implicit none
integer,value :: n
complex(kind=8),value :: tau
type(c_ptr),value :: _x
type(c_ptr),value :: _y
complex(8), intent(in) ,target :: x()
complex(8),target :: y()
integer :: tid
integer :: i
integer :: j
integer :: k
integer :: nb
integer :: istat
integer :: laneid
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: iv1
real(kind=8) :: iv2
real(kind=8) :: rsum
real(kind=8) :: isum
complex(kind=8) :: val
complex(kind=8) :: cv1
complex(kind=8) :: mytau
real(kind=8) :: alphar
real(kind=8) :: alphai
complex(kind=8) :: alpha
CALL hipCheck(hipMemcpy(c_loc(x),_x,C_SIZEOF(x),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(y),_y,C_SIZEOF(y),hipMemcpyDeviceToHost))
implicit none
integer, value :: N
complex(8), device :: tau
complex(8), dimension(N), device, intent(in) :: x
complex(8), dimension(N), device :: y
integer :: tid, i, j, k, nb, istat, laneID
real(8) :: rv1, rv2, iv1, iv2, rsum, isum
complex(8) :: val, cv1, mytau
real(8), shared :: alphar, alphai
!complex(8), shared :: alpha
complex(8) :: alpha
tid = threadIdx%x
laneID = iand(tid, 31)
if (tid == 1) then
alphar = 0.0_8
alphai = 0.0_8
endif
call syncthreads()
rsum = 0.0_8
isum = 0.0_8
mytau = tau
nb = ceiling(real(N)/blockDim%x) ! number of blocks down column
i = tid
do j = 1, nb
! All threads perform their product, zero if out of bounds
if (i <= N) then
val = dconjg(mytau*y(i))*x(i)
else
val = dcmplx(0., 0.)
endif
rv1 = dble(val); iv1 = dimag(val)
rsum = rsum + rv1
isum = isum + iv1
i = i + blockDim%x
end do
! Partial sum within warps using shuffle
rv1 = rsum
rv2 = __shfl_down(rv1, 1)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 2)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 4)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 8)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 16)
rv1 = rv1 + rv2
iv1 = isum
iv2 = __shfl_down(iv1, 1)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 2)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 4)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 8)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 16)
iv1 = iv1 + iv2
if (laneID == 1) then
istat = atomicadd(alphar, rv1)
istat = atomicadd(alphai, iv1)
endif
call syncthreads()
alpha = -dcmplx(0.5, 0.0)*mytau*dcmplx(alphar, alphai)
do i = tid, N, blockDim%x
y(i) = mytau*y(i) + alpha*x(i) !zaxpy
end do
CALL hipCheck(hipMemcpy(_x,c_loc(x),C_SIZEOF(x),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_y,c_loc(y),C_SIZEOF(y),hipMemcpyHostToDevice))
end subroutine
subroutine launch_stacked_zgemv_n_finish_w_cpu(m,&
n,&
ldv,&
ldw,&
_v,&
_w,&
_z1,&
_z2,&
tau,&
_x,&
_y2,&
finished)
use iso_c_binding
use hip
implicit none
integer,value :: m
integer,value :: n
integer,value :: ldv
integer,value :: ldw
type(c_ptr),value :: _v
type(c_ptr),value :: _w
type(c_ptr),value :: _z1
type(c_ptr),value :: _z2
complex(kind=8),value :: tau
type(c_ptr),value :: _x
type(c_ptr),value :: _y2
integer,value :: finished
complex(8), N), intent(in) ,target :: v()
complex(8), N), intent(in) ,target :: w()
complex(8), intent(in) ,target :: z1()
complex(8), intent(in) ,target :: z2()
complex(8), intent(in) ,target :: x()
complex(8),target :: y2()
integer :: i
integer :: j
integer :: tx
integer :: ty
integer :: istat
integer :: nblocks
integer :: tid
integer :: laneid
integer :: nb
integer :: nfinished
complex(kind=8) :: val1
complex(kind=8) :: val2
complex(kind=8) :: mytau
complex(kind=8) :: alpha
real(kind=8) :: rv1
real(kind=8) :: rv2
real(kind=8) :: iv1
real(kind=8) :: iv2
real(kind=8) :: xr
real(kind=8) :: xi
real(kind=8) :: rsum
real(kind=8) :: isum
real(kind=8) :: alphar
real(kind=8) :: alphai
CALL hipCheck(hipMemcpy(c_loc(v),_v,C_SIZEOF(v),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(w),_w,C_SIZEOF(w),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(z1),_z1,C_SIZEOF(z1),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(z2),_z2,C_SIZEOF(z2),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(x),_x,C_SIZEOF(x),hipMemcpyDeviceToHost))
CALL hipCheck(hipMemcpy(c_loc(y2),_y2,C_SIZEOF(y2),hipMemcpyDeviceToHost))
use cudafor
implicit none
integer, value :: M, N, ldv, ldw
complex(8), dimension(ldv, N), device, intent(in) :: V
complex(8), dimension(ldw, N), device, intent(in) :: W
complex(8), dimension(N), device, intent(in) :: z1, z2
!DIR$ IGNORE_TKR y
real(8), dimension(2*M), device :: y
complex(8), device :: tau
complex(8), dimension(M), device, intent(in) :: x
complex(8), dimension(M), device :: y2
integer, device :: finished
integer :: i, j, tx, ty, istat, nBlocks, tid, laneID, nb
integer, shared :: nFinished
complex(8) :: val1, val2, mytau, alpha
real(8) :: rv1, rv2, iv1, iv2, xr, xi, rsum, isum
real(8), shared :: alphar, alphai
tx = threadIdx%x
ty = threadIdx%y
i = (blockIdx%x - 1)*blockDim%x + tx
j = (blockIdx%y - 1)*blockDim%y + ty
nBlocks = gridDim%x*gridDim%y
if (i <= M .and. j <= 2*N) then
if (j > N) then
val1 = z2(j - N)
val2 = V(i, j - N)
else
val1 = z1(j)
val2 = W(i, j)
endif
xr = dble(val1); xi = dimag(val1)
rv2 = dble(val2); iv2 = dimag(val2)
rv1 = -rv2*xr + iv2*xi
iv1 = -rv2*xi - iv2*xr
istat = atomicadd(y(2*i - 1), rv1)
istat = atomicadd(y(2*i), iv1)
endif
call threadfence()
nFinished = 0
call syncthreads()
if (tx + ty == 2) nFinished = atomicinc(finished, nBlocks - 1)
call syncthreads()
if (nFinished < nBlocks - 1) return
! Begin finish_W_col work with last block
tid = threadIdx%x + (threadIdx%y - 1)*blockDim%x
laneID = iand(tid, 31)
if (tid == 1) then
alphar = 0.0_8
alphai = 0.0_8
endif
call syncthreads()
rsum = 0.0_8
isum = 0.0_8
mytau = tau
nb = ceiling(real(M)/(blockDim%x*blockDim%y)) ! number of blocks down column
i = tid
do j = 1, nb
! All threads perform their product, zero if out of bounds
if (i <= M) then
val1 = dconjg(mytau*y2(i))*x(i)
else
val1 = dcmplx(0., 0.)
endif
rv1 = dble(val1); iv1 = dimag(val1)
rsum = rsum + rv1
isum = isum + iv1
i = i + blockDim%x*blockDim%y
end do
! Partial sum within warps using shuffle
rv1 = rsum
rv2 = __shfl_down(rv1, 1)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 2)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 4)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 8)
rv1 = rv1 + rv2
rv2 = __shfl_down(rv1, 16)
rv1 = rv1 + rv2
iv1 = isum
iv2 = __shfl_down(iv1, 1)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 2)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 4)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 8)
iv1 = iv1 + iv2
iv2 = __shfl_down(iv1, 16)
iv1 = iv1 + iv2
if (laneID == 1) then
istat = atomicadd(alphar, rv1)
istat = atomicadd(alphai, iv1)
endif
call syncthreads()
alpha = -dcmplx(0.5, 0.0)*mytau*dcmplx(alphar, alphai)
do i = tid, M, blockDim%x*blockDim%y
y2(i) = mytau*y2(i) + alpha*x(i) !zaxpy
end do
CALL hipCheck(hipMemcpy(_v,c_loc(v),C_SIZEOF(v),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_w,c_loc(w),C_SIZEOF(w),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_z1,c_loc(z1),C_SIZEOF(z1),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_z2,c_loc(z2),C_SIZEOF(z2),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_x,c_loc(x),C_SIZEOF(x),hipMemcpyHostToDevice))
CALL hipCheck(hipMemcpy(_y2,c_loc(y2),C_SIZEOF(y2),hipMemcpyHostToDevice))
end subroutine
end module zhetrd_gpu_kernels |
= = Nutrition = =
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
Require Import String.
Require Import Coqlib.
Require Import Decidableplus.
Require Import Maps.
Require Import AST.
Require Import Op.
(** ** Machine registers *)
(** The following type defines the machine registers that can be referenced
as locations. These include:
- Integer registers that can be allocated to RTL pseudo-registers ([Rxx]).
- Floating-point registers that can be allocated to RTL pseudo-registers
([Fxx]).
The type [mreg] does not include special-purpose or reserved
machine registers such as the stack pointer (GPR1), the small data area
pointers (GPR2, GPR13), and the condition codes. *)
Inductive mreg: Type :=
(** Allocatable integer regs *)
| R3: mreg | R4: mreg | R5: mreg | R6: mreg
| R7: mreg | R8: mreg | R9: mreg | R10: mreg
| R11: mreg | R12: mreg
| R14: mreg | R15: mreg | R16: mreg
| R17: mreg | R18: mreg | R19: mreg | R20: mreg
| R21: mreg | R22: mreg | R23: mreg | R24: mreg
| R25: mreg | R26: mreg | R27: mreg | R28: mreg
| R29: mreg | R30: mreg | R31: mreg
(** Allocatable float regs *)
| F0: mreg
| F1: mreg | F2: mreg | F3: mreg | F4: mreg
| F5: mreg | F6: mreg | F7: mreg | F8: mreg
| F9: mreg | F10: mreg | F11: mreg | F12: mreg
| F13: mreg | F14: mreg | F15: mreg
| F16: mreg | F17: mreg | F18: mreg | F19: mreg
| F20: mreg | F21: mreg | F22: mreg | F23: mreg
| F24: mreg | F25: mreg | F26: mreg | F27: mreg
| F28: mreg | F29: mreg | F30: mreg | F31: mreg.
Lemma mreg_eq: forall (r1 r2: mreg), {r1 = r2} + {r1 <> r2}.
Proof. decide equality. Defined.
Global Opaque mreg_eq.
Definition all_mregs :=
R3 :: R4 :: R5 :: R6 :: R7 :: R8 :: R9 :: R10
:: R11 :: R12 :: R14 :: R15 :: R16 :: R17 :: R18 :: R19 :: R20
:: R21 :: R22 :: R23 :: R24 :: R25 :: R26 :: R27 :: R28
:: R29 :: R30 :: R31
:: F0 :: F1 :: F2 :: F3 :: F4
:: F5 :: F6 :: F7 :: F8
:: F9 :: F10 :: F11 :: F12
:: F13 :: F14 :: F15
:: F16 :: F17 :: F18 :: F19
:: F20 :: F21 :: F22 :: F23
:: F24 :: F25 :: F26 :: F27
:: F28 :: F29 :: F30 :: F31 :: nil.
Lemma all_mregs_complete:
forall (r: mreg), In r all_mregs.
Proof.
assert (forall r, proj_sumbool (In_dec mreg_eq r all_mregs) = true) by (destruct r; reflexivity).
intros. specialize (H r). InvBooleans. auto.
Qed.
Global Instance Decidable_eq_mreg : forall (x y: mreg), Decidable (eq x y) := Decidable_eq mreg_eq.
Global Instance Finite_mreg : Finite mreg := {
Finite_elements := all_mregs;
Finite_elements_spec := all_mregs_complete
}.
Definition mreg_type (r: mreg): typ :=
match r with
| R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12
| R14 | R15 | R16 | R17 | R18 | R19 | R20 | R21 | R22 | R23 | R24
| R25 | R26 | R27 | R28 | R29 | R30 | R31 => if Archi.ppc64 then Tany64 else Tany32
| F0 | F1 | F2 | F3 | F4 | F5 | F6 | F7
| F8 | F9 | F10 | F11 | F12 | F13 | F14 | F15
| F16 | F17 | F18 | F19 | F20 | F21 | F22 | F23
| F24 | F25 | F26 | F27 | F28 | F29 | F30 | F31 => Tany64
end.
Open Scope positive_scope.
Module IndexedMreg <: INDEXED_TYPE.
Definition t := mreg.
Definition eq := mreg_eq.
Definition index (r: mreg): positive :=
match r with
| R3 => 1 | R4 => 2 | R5 => 3 | R6 => 4
| R7 => 5 | R8 => 6 | R9 => 7 | R10 => 8
| R11 => 9 | R12 => 10
| R14 => 11 | R15 => 12 | R16 => 13
| R17 => 14 | R18 => 15 | R19 => 16 | R20 => 17
| R21 => 18 | R22 => 19 | R23 => 20 | R24 => 21
| R25 => 22 | R26 => 23 | R27 => 24 | R28 => 25
| R29 => 26 | R30 => 27 | R31 => 28
| F0 => 29
| F1 => 30 | F2 => 31 | F3 => 32 | F4 => 33
| F5 => 34 | F6 => 35 | F7 => 36 | F8 => 37
| F9 => 38 | F10 => 39 | F11 => 40 | F12 => 41
| F13 => 42 | F14 => 43 | F15 => 44
| F16 => 45 | F17 => 46 | F18 => 47 | F19 => 48
| F20 => 49 | F21 => 50 | F22 => 51 | F23 => 52
| F24 => 53 | F25 => 54 | F26 => 55 | F27 => 56
| F28 => 57 | F29 => 58 | F30 => 59 | F31 => 60
end.
Lemma index_inj:
forall r1 r2, index r1 = index r2 -> r1 = r2.
Proof.
decide_goal.
Qed.
End IndexedMreg.
Definition is_stack_reg (r: mreg) : bool := false.
(** ** Names of registers *)
Local Open Scope string_scope.
Definition register_names :=
("R3", R3) :: ("R4", R4) :: ("R5", R5) :: ("R6", R6) ::
("R7", R7) :: ("R8", R8) :: ("R9", R9) :: ("R10", R10) ::
("R11", R11) :: ("R12", R12) ::
("R14", R14) :: ("R15", R15) :: ("R16", R16) ::
("R17", R17) :: ("R18", R18) :: ("R19", R19) :: ("R20", R20) ::
("R21", R21) :: ("R22", R22) :: ("R23", R23) :: ("R24", R24) ::
("R25", R25) :: ("R26", R26) :: ("R27", R27) :: ("R28", R28) ::
("R29", R29) :: ("R30", R30) :: ("R31", R31) ::
("F0", F0) :: ("F1", F1) :: ("F2", F2) :: ("F3", F3) :: ("F4", F4) ::
("F5", F5) :: ("F6", F6) :: ("F7", F7) :: ("F8", F8) ::
("F9", F9) :: ("F10", F10) :: ("F11", F11) :: ("F12", F12) ::
("F13", F13) :: ("F14", F14) :: ("F15", F15) ::
("F16", F16) :: ("F17", F17) :: ("F18", F18) :: ("F19", F19) ::
("F20", F20) :: ("F21", F21) :: ("F22", F22) :: ("F23", F23) ::
("F24", F24) :: ("F25", F25) :: ("F26", F26) :: ("F27", F27) ::
("F28", F28) :: ("F29", F29) :: ("F30", F30) :: ("F31", F31) :: nil.
Definition register_by_name (s: string) : option mreg :=
let fix assoc (l: list (string * mreg)) : option mreg :=
match l with
| nil => None
| (s1, r1) :: l' => if string_dec s s1 then Some r1 else assoc l'
end
in assoc register_names.
(** ** Destroyed registers, preferred registers *)
Definition destroyed_by_cond (cond: condition): list mreg := nil.
Definition destroyed_by_op (op: operation): list mreg :=
match op with
| Ofloatconst _ => R12 :: nil
| Osingleconst _ => R12 :: nil
| Olongconst _ => R12 :: nil
| Ointoffloat => F13 :: nil
| Olongoffloat => F13 :: nil
| Oaddlimm _ => R12 :: nil
| Oandlimm _ => R12 :: nil
| Oorlimm _ => R12 :: nil
| Oxorlimm _ => R12 :: nil
| Orolml _ _ => R12 :: nil
| Ocmp c => destroyed_by_cond c
| _ => nil
end.
Definition destroyed_by_load (chunk: memory_chunk) (addr: addressing): list mreg :=
R12 :: nil.
Definition destroyed_by_store (chunk: memory_chunk) (addr: addressing): list mreg :=
R11 :: R12 :: nil.
Definition destroyed_by_jumptable: list mreg :=
R12 :: nil.
Fixpoint destroyed_by_clobber (cl: list string): list mreg :=
match cl with
| nil => nil
| c1 :: cl =>
match register_by_name c1 with
| Some r => r :: destroyed_by_clobber cl
| None => destroyed_by_clobber cl
end
end.
Definition destroyed_by_builtin (ef: external_function): list mreg :=
match ef with
| EF_builtin id sg =>
if string_dec id "__builtin_set_spr64" then R10::nil
else if string_dec id "__builtin_atomic_exchange" then R10::nil
else if string_dec id "__builtin_atomic_compare_exchange" then R10::R11::nil
else F13 :: nil
| EF_vload _ => R11 :: nil
| EF_vstore Mint64 => R10 :: R11 :: R12 :: nil
| EF_vstore _ => R11 :: R12 :: nil
| EF_memcpy _ _ => R11 :: R12 :: F13 :: nil
| EF_inline_asm txt sg clob => destroyed_by_clobber clob
| _ => nil
end.
Definition destroyed_by_setstack (ty: typ): list mreg :=
nil.
Definition destroyed_at_function_entry: list mreg :=
nil.
Definition destroyed_at_indirect_call: list mreg :=
nil.
Definition temp_for_parent_frame: mreg :=
R11.
Definition mregs_for_operation (op: operation): list (option mreg) * option mreg :=
(nil, None).
Definition mregs_for_builtin (ef: external_function): list (option mreg) * list (option mreg) :=
match ef with
| EF_builtin id sg =>
if string_dec id "__builtin_atomic_exchange" then ((Some R3)::(Some R4)::(Some R5)::nil,nil)
else if string_dec id "__builtin_sync_fetch_and_add" then ((Some R4)::(Some R5)::nil,(Some R3)::nil)
else if string_dec id "__builtin_atomic_compare_exchange" then ((Some R4)::(Some R5)::(Some R6)::nil, (Some R3):: nil)
else (nil, nil)
| _ => (nil, nil)
end.
Global Opaque
destroyed_by_op destroyed_by_load destroyed_by_store
destroyed_by_cond destroyed_by_jumptable destroyed_by_builtin
destroyed_at_indirect_call
destroyed_by_setstack destroyed_at_function_entry temp_for_parent_frame
mregs_for_operation mregs_for_builtin.
(** Two-address operations. Return [true] if the first argument and
the result must be in the same location *and* are unconstrained
by [mregs_for_operation]. *)
Definition two_address_op (op: operation) : bool :=
match op with
| Oroli _ _ => true
| Olowlong => true
| Ofloatofsingle => true
| _ => false
end.
(* Constraints on constant propagation for builtins *)
Definition builtin_constraints (ef: external_function) :
list builtin_arg_constraint :=
match ef with
| EF_builtin id sg =>
if string_dec id "__builtin_get_spr" then OK_const :: nil
else if string_dec id "__builtin_get_spr64" then OK_const :: nil
else if string_dec id "__builtin_set_spr" then OK_const :: OK_default :: nil
else if string_dec id "__builtin_set_spr64" then OK_const :: OK_default :: nil
else if string_dec id "__builtin_prefetch" then OK_default :: OK_const :: OK_const :: nil
else if string_dec id "__builtin_dcbtls" then OK_default :: OK_const :: nil
else if string_dec id "__builtin_icbtls" then OK_default :: OK_const :: nil
else if string_dec id "__builtin_mbar" then OK_const :: nil
else if string_dec id "__builtin_mr" then OK_const :: OK_const :: nil
else nil
| EF_vload _ => OK_addressing :: nil
| EF_vstore _ => OK_addressing :: OK_default :: nil
| EF_memcpy _ _ => OK_addrstack :: OK_addrstack :: nil
| EF_annot kind txt targs => map (fun _ => OK_all) targs
| EF_debug kind txt targs => map (fun _ => OK_all) targs
| _ => nil
end.
|
theory Introduction
imports Setup
begin (*<*)
ML \<open>
Isabelle_System.make_directory (File.tmp_path (Path.basic "examples"))
\<close> (*>*)
section \<open>Introduction\<close>
text \<open>
This tutorial introduces the code generator facilities of \<open>Isabelle/HOL\<close>. It allows to turn (a certain class of) HOL
specifications into corresponding executable code in the programming
languages \<open>SML\<close> \<^cite>\<open>SML\<close>, \<open>OCaml\<close> \<^cite>\<open>OCaml\<close>,
\<open>Haskell\<close> \<^cite>\<open>"haskell-revised-report"\<close> and \<open>Scala\<close>
\<^cite>\<open>"scala-overview-tech-report"\<close>.
To profit from this tutorial, some familiarity and experience with
Isabelle/HOL \<^cite>\<open>"isa-tutorial"\<close> and its basic theories is assumed.
\<close>
subsection \<open>Code generation principle: shallow embedding \label{sec:principle}\<close>
text \<open>
The key concept for understanding Isabelle's code generation is
\emph{shallow embedding}: logical entities like constants, types and
classes are identified with corresponding entities in the target
language. In particular, the carrier of a generated program's
semantics are \emph{equational theorems} from the logic. If we view
a generated program as an implementation of a higher-order rewrite
system, then every rewrite step performed by the program can be
simulated in the logic, which guarantees partial correctness
\<^cite>\<open>"Haftmann-Nipkow:2010:code"\<close>.
\<close>
subsection \<open>A quick start with the Isabelle/HOL toolbox \label{sec:queue_example}\<close>
text \<open>
In a HOL theory, the @{command_def datatype} and @{command_def
definition}/@{command_def primrec}/@{command_def fun} declarations
form the core of a functional programming language. By default
equational theorems stemming from those are used for generated code,
therefore \qt{naive} code generation can proceed without further
ado.
For example, here a simple \qt{implementation} of amortised queues:
\<close>
datatype %quote 'a queue = AQueue "'a list" "'a list"
definition %quote empty :: "'a queue" where
"empty = AQueue [] []"
primrec %quote enqueue :: "'a \<Rightarrow> 'a queue \<Rightarrow> 'a queue" where
"enqueue x (AQueue xs ys) = AQueue (x # xs) ys"
fun %quote dequeue :: "'a queue \<Rightarrow> 'a option \<times> 'a queue" where
"dequeue (AQueue [] []) = (None, AQueue [] [])"
| "dequeue (AQueue xs (y # ys)) = (Some y, AQueue xs ys)"
| "dequeue (AQueue xs []) =
(case rev xs of y # ys \<Rightarrow> (Some y, AQueue [] ys))" (*<*)
lemma %invisible dequeue_nonempty_Nil [simp]:
"xs \<noteq> [] \<Longrightarrow> dequeue (AQueue xs []) = (case rev xs of y # ys \<Rightarrow> (Some y, AQueue [] ys))"
by (cases xs) (simp_all split: list.splits) (*>*)
text \<open>\noindent Then we can generate code e.g.~for \<open>SML\<close> as follows:\<close>
export_code %quote empty dequeue enqueue in SML module_name Example
text \<open>\noindent resulting in the following code:\<close>
text %quote \<open>
@{code_stmts empty enqueue dequeue (SML)}
\<close>
text \<open>
\noindent The @{command_def export_code} command takes multiple constants
for which code shall be generated; anything else needed for those is
added implicitly. Then follows a target language identifier and a freely
chosen \<^theory_text>\<open>module_name\<close>.
Output is written to a logical file-system within the theory context,
with the theory name and ``\<^verbatim>\<open>code\<close>'' as overall prefix. There is also a
formal session export using the same name: the result may be explored in
the Isabelle/jEdit Prover IDE using the file-browser on the URL
``\<^verbatim>\<open>isabelle-export:\<close>''.
The file name is determined by the target language together with an
optional \<^theory_text>\<open>file_prefix\<close> (the default is ``\<^verbatim>\<open>export\<close>'' with a consecutive
number within the current theory). For \<open>SML\<close>, \<open>OCaml\<close> and \<open>Scala\<close>, the
file prefix becomes a plain file with extension (e.g.\ ``\<^verbatim>\<open>.ML\<close>'' for
SML). For \<open>Haskell\<close> the file prefix becomes a directory that is populated
with a separate file for each module (with extension ``\<^verbatim>\<open>.hs\<close>'').
Consider the following example:
\<close>
export_code %quote empty dequeue enqueue in Haskell
module_name Example file_prefix example
text \<open>
\noindent This is the corresponding code:
\<close>
text %quote \<open>
@{code_stmts empty enqueue dequeue (Haskell)}
\<close>
text \<open>
\noindent For more details about @{command export_code} see
\secref{sec:further}.
\<close>
subsection \<open>Type classes\<close>
text \<open>
Code can also be generated from type classes in a Haskell-like
manner. For illustration here an example from abstract algebra:
\<close>
class %quote semigroup =
fixes mult :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<otimes>" 70)
assumes assoc: "(x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
class %quote monoid = semigroup +
fixes neutral :: 'a ("\<one>")
assumes neutl: "\<one> \<otimes> x = x"
and neutr: "x \<otimes> \<one> = x"
instantiation %quote nat :: monoid
begin
primrec %quote mult_nat where
"0 \<otimes> n = (0::nat)"
| "Suc m \<otimes> n = n + m \<otimes> n"
definition %quote neutral_nat where
"\<one> = Suc 0"
lemma %quote add_mult_distrib:
fixes n m q :: nat
shows "(n + m) \<otimes> q = n \<otimes> q + m \<otimes> q"
by (induct n) simp_all
instance %quote proof
fix m n q :: nat
show "m \<otimes> n \<otimes> q = m \<otimes> (n \<otimes> q)"
by (induct m) (simp_all add: add_mult_distrib)
show "\<one> \<otimes> n = n"
by (simp add: neutral_nat_def)
show "m \<otimes> \<one> = m"
by (induct m) (simp_all add: neutral_nat_def)
qed
end %quote
text \<open>
\noindent We define the natural operation of the natural numbers
on monoids:
\<close>
primrec %quote (in monoid) pow :: "nat \<Rightarrow> 'a \<Rightarrow> 'a" where
"pow 0 a = \<one>"
| "pow (Suc n) a = a \<otimes> pow n a"
text \<open>
\noindent This we use to define the discrete exponentiation
function:
\<close>
definition %quote bexp :: "nat \<Rightarrow> nat" where
"bexp n = pow n (Suc (Suc 0))"
text \<open>
\noindent The corresponding code in Haskell uses that language's
native classes:
\<close>
text %quote \<open>
@{code_stmts bexp (Haskell)}
\<close>
text \<open>
\noindent This is a convenient place to show how explicit dictionary
construction manifests in generated code -- the same example in
\<open>SML\<close>:
\<close>
text %quote \<open>
@{code_stmts bexp (SML)}
\<close>
text \<open>
\noindent Note the parameters with trailing underscore (\<^verbatim>\<open>A_\<close>), which are the dictionary parameters.
\<close>
subsection \<open>How to continue from here\<close>
text \<open>
What you have seen so far should be already enough in a lot of
cases. If you are content with this, you can quit reading here.
Anyway, to understand situations where problems occur or to increase
the scope of code generation beyond default, it is necessary to gain
some understanding how the code generator actually works:
\begin{itemize}
\item The foundations of the code generator are described in
\secref{sec:foundations}.
\item In particular \secref{sec:utterly_wrong} gives hints how to
debug situations where code generation does not succeed as
expected.
\item The scope and quality of generated code can be increased
dramatically by applying refinement techniques, which are
introduced in \secref{sec:refinement}.
\item How to define partial functions such that code can be generated
is explained in \secref{sec:partial}.
\item Inductive predicates can be turned executable using an
extension of the code generator \secref{sec:inductive}.
\item If you want to utilize code generation to obtain fast
evaluators e.g.~for decision procedures, have a look at
\secref{sec:evaluation}.
\item You may want to skim over the more technical sections
\secref{sec:adaptation} and \secref{sec:further}.
\item The target language Scala \<^cite>\<open>"scala-overview-tech-report"\<close>
comes with some specialities discussed in \secref{sec:scala}.
\item For exhaustive syntax diagrams etc. you should visit the
Isabelle/Isar Reference Manual \<^cite>\<open>"isabelle-isar-ref"\<close>.
\end{itemize}
\bigskip
\begin{center}\fbox{\fbox{\begin{minipage}{8cm}
\begin{center}\textit{Happy proving, happy hacking!}\end{center}
\end{minipage}}}\end{center}
\<close>
end
|
subsection \<open>IMO 2008 SL - A2\<close>
theory IMO_2008_SL_A2
imports Complex_Main
begin
theorem IMO_2008_SL_A2_a:
fixes x y z :: real
assumes "x \<noteq> 1" "y \<noteq> 1" "z \<noteq> 1" "x * y * z = 1"
shows "x\<^sup>2 / (x - 1)\<^sup>2 + y\<^sup>2 / (y - 1)\<^sup>2 + z\<^sup>2 / (z - 1)\<^sup>2 \<ge> 1"
sorry
theorem IMO_2008_SL_A2_b:
fixes x y z :: real
shows "\<not> finite {(x, y, z). x \<noteq> 1 \<and> y \<noteq> 1 \<and> z \<noteq> 1 \<and> x * y * z = 1 \<and> x^2 / (x - 1)^2 + y^2 / (y - 1)^2 + z^2 / (z - 1)^2 = 1}"
sorry
end |
subsubsection \<open>Register Equations\<close>
theory Register_Equations imports "../Register_Machine/MultipleStepRegister"
Equation_Setup "../Diophantine/Register_Machine_Sums"
"../Diophantine/Binary_And" "HOL-Library.Rewrite"
begin
context rm_eq_fixes
begin
text \<open>Equation 4.22\<close>
definition register_0 :: "bool" where
"register_0 \<equiv> r 0 = a + b*r 0 + b*\<Sum>R+ p 0 s - b*\<Sum>R- p 0 (\<lambda>k. s k && z 0)"
text \<open>Equation 4.23\<close>
definition register_l :: "bool" where
"register_l \<equiv> \<forall>l>0. l < n \<longrightarrow> r l = b*r l + b*\<Sum>R+ p l s - b*\<Sum>R- p l (\<lambda>k. s k && z l)"
text \<open>Extra equation not in Matiyasevich's book\<close>
definition register_bound :: "bool" where
"register_bound \<equiv> \<forall>l < n. r l < b ^ q"
definition register_equations :: "bool" where
"register_equations \<equiv> register_0 \<and> register_l \<and> register_bound"
end
context register_machine
begin
definition sum_rsub_of_bit_and :: "polynomial \<Rightarrow> nat \<Rightarrow> polynomial list \<Rightarrow> polynomial
\<Rightarrow> relation"
("[_ = \<Sum>R- _ '(_ && _')]") where
"[x = \<Sum>R- d (s && zl)] \<equiv> let x' = push_param x (length p);
s' = push_param_list s (length p);
zl' = push_param zl (length p)
in [\<exists>length p] [\<forall><length p] (\<lambda>i. [Param i = s'!i && zl'])
[\<and>] x' [=] [\<Sum>R-] p d Param"
lemma sum_rsub_of_bit_and_dioph[dioph]:
fixes s :: "polynomial list" and d :: nat and x zl :: polynomial
shows "is_dioph_rel [x = \<Sum>R- d (s && zl)]"
unfolding sum_rsub_of_bit_and_def by (auto simp add: dioph)
lemma sum_rsub_of_bit_and_eval:
fixes z s :: "polynomial list" and d :: nat and x :: polynomial
assumes "length s = Suc m" "length p > 0"
shows "eval [x = \<Sum>R- d (s && zl)] a
\<longleftrightarrow> peval x a = \<Sum>R- p d (\<lambda>k. peval (s!k) a && peval zl a)" (is "?P \<longleftrightarrow> ?Q")
proof -
have invariance: "\<forall>k<length p. y1 k = y2 k \<Longrightarrow> \<Sum>R- p d y1 = \<Sum>R- p d y2" for y1 y2
unfolding sum_rsub.simps apply (intro sum.cong, simp)
using \<open>length p > 0\<close> by auto (metis Suc_pred le_imp_less_Suc length_greater_0_conv)
have len_ps: "length s = length p"
using m_def \<open>length s = Suc m\<close> \<open>length p > 0\<close> by auto
have aux1: "peval ([\<Sum>R-] p l f) a = \<Sum>R- p l (\<lambda>x. peval (f x) a) " for l f
using defs \<open>length p > 0\<close> by auto
show ?thesis
proof (rule)
assume ?P
thus ?Q
unfolding sum_rsub_of_bit_and_def
using aux1 apply simp
apply (auto simp add: aux1 push_push defs)
using push_push_map_i apply (simp add: push_param_list_def len_ps)
unfolding list_eval_def apply (simp add: assms len_ps invariance)
using assms(2) invariance len_ps sum_rsub_polynomial_eval by force
next
assume ?Q
thus ?P
unfolding sum_rsub_of_bit_and_def apply (auto simp add: aux1 defs push_push)
apply (rule exI[of _ "map (\<lambda>k. peval (s ! k) a && peval zl a) [0..<length p]"], simp)
using push_push push_push_map_i apply (simp add: push_param_list_def len_ps)
using invariance len_ps push_list_eval \<open>length p > 0\<close> defs by simp
qed
qed
lemma register_0_dioph[dioph]:
fixes A b :: polynomial
fixes r z s :: "polynomial list"
assumes "length r = n" "length z = n" "length s = Suc m"
defines "DR \<equiv> LARY (\<lambda>ll. rm_eq_fixes.register_0 p (ll!0!0) (ll!0!1)
(nth (ll!1)) (nth (ll!2)) (nth (ll!3))) [[A, b], r, z, s]"
shows "is_dioph_rel DR"
proof -
let ?N = "1"
define A' b' r' z' s' where pushed_def: "A' = push_param A ?N" "b' = push_param b ?N"
"r' = map (\<lambda>x. push_param x ?N) r" "z' = map (\<lambda>x. push_param x ?N) z"
"s' = map (\<lambda>x. push_param x ?N) s"
define DS where "DS \<equiv> [\<exists>] ([Param 0 = \<Sum>R- 0 (s' && (z'!0))] [\<and>]
r'!0 [=] A' [+] b' [*] r'!0 [+] b' [*] ([\<Sum>R+] p 0 (nth s'))
[-] b' [*] (Param 0))"
have "length p > 0" using p_nonempty by auto
have "n > 0" using n_gt_0 by auto
have "length p = length s"
using \<open>length s = Suc m\<close> m_def \<open>length p > 0\<close> by auto
have "length s' = length s"
unfolding pushed_def by auto
have "length z > 0"
using \<open>length z = n\<close> \<open>n > 0\<close> by simp
have "length r > 0"
using \<open>length r = n\<close> \<open>n > 0\<close> by simp
have "eval DS a = eval DR a" for a
proof -
(* the key to this proof is to write these intermediate steps with list_eval on the RHS
because that is needed in the final proof; otherwise showing the equivalence again
re-requires unfolding the sum definitions *)
have sum_radd_push: "\<Sum>R+ p 0 (\<lambda>x. peval (s' ! x) (push a k)) = \<Sum>R+ p 0 (list_eval s a)" for k
unfolding sum_radd.simps pushed_def apply (intro sum.cong, simp)
using push_push_map1 \<open>length p = length s\<close> \<open>length s = Suc m\<close> by simp
have sum_rsub_push: "\<Sum>R- p 0 (\<lambda>x. peval (s' ! x) (push a k) && peval (z' ! 0) (push a k))
= \<Sum>R- p 0 (\<lambda>x. list_eval s a x && peval (z ! 0) a)" for k
unfolding sum_rsub.simps pushed_def apply (intro sum.cong, simp)
using push_push_map1 \<open>length p = length s\<close> \<open>length s = Suc m\<close> \<open>length z > 0\<close>
by (simp add: list_eval_def)
have 1: "peval ([\<Sum>R-] p l f) a = \<Sum>R- p l (\<lambda>x. peval (f x) a) " for f l
using defs \<open>length p > 0\<close> by auto
show ?thesis
unfolding DS_def rm_eq_fixes.register_0_def
register_machine_axioms rm_eq_fixes_def apply (simp add: defs)
using \<open>length p > 0\<close> apply (simp add: sum_rsub_of_bit_and_eval \<open>length s' = length s\<close>
\<open>length s = Suc m\<close>)
apply (simp add: sum_radd_push sum_rsub_push)
unfolding pushed_def using push_push1 push_push_map1 \<open>length r > 0\<close> apply simp
unfolding DR_def assms defs \<open>length p > 0\<close>
using rm_eq_fixes_def rm_eq_fixes.register_0_def register_machine_axioms apply (simp)
using \<open>length z > 0\<close> push_def list_eval_def 1 apply (simp add: 1 defs \<open>length p > 0\<close>)
using One_nat_def sum_radd_push unfolding pushed_def(5) list_eval_def by presburger
qed
moreover have "is_dioph_rel DS"
unfolding DS_def by (simp add: dioph)
ultimately show ?thesis
by (auto simp: is_dioph_rel_def)
qed
lemma register_l_dioph[dioph]:
fixes b :: polynomial
fixes r z s :: "polynomial list"
assumes "length r = n" "length z = n" "length s = Suc m"
defines "DR \<equiv> LARY (\<lambda>ll. rm_eq_fixes.register_l p n (ll!0!0)
(nth (ll!1)) (nth (ll!2)) (nth (ll!3))) [[b], r, z, s]"
shows "is_dioph_rel DR"
proof -
define indices where "indices \<equiv> [Suc 0..<n]" (* for now *)
let ?N = "length indices + 1"
define b' r' z' s' where pushed_def: "b' = push_param b ?N"
"r' = map (\<lambda>x. push_param x ?N) r"
"z' = map (\<lambda>x. push_param x ?N) z"
"s' = map (\<lambda>x. push_param x ?N) s"
define param_l_is_sum_rsub_of_bitand where
"param_l_is_sum_rsub_of_bitand \<equiv> \<lambda>l. [Param l = \<Sum>R- l (s' && (z'!l))]"
define params_are_sum_rsub_of_bitand where
"params_are_sum_rsub_of_bitand \<equiv> [\<forall> in indices] param_l_is_sum_rsub_of_bitand"
define single_register where
"single_register \<equiv> \<lambda>l. r'!l [=] b' [*] r'!l [+] b' [*] ([\<Sum>R+] p l (nth s')) [-] b' [*] (Param l)"
define DS where "DS \<equiv> [\<exists>n] params_are_sum_rsub_of_bitand [\<and>] [\<forall> in indices] single_register"
have "length p > 0" using p_nonempty by auto
have "n > 0" using n_gt_0 by auto
have "length p = length s"
using \<open>length s = Suc m\<close> m_def \<open>length p > 0\<close> by auto
have "length s' = length s"
unfolding pushed_def by auto
have "length z > 0"
using \<open>length z = n\<close> \<open>n > 0\<close> by simp
have "length r > 0"
using \<open>length r = n\<close> \<open>n > 0\<close> by simp
have "length indices + 1 = n"
unfolding indices_def \<open>n>0\<close>
using Suc_pred' \<open>n > 0\<close> length_upt by presburger
have "length s' = Suc m"
using \<open>length s' = length s\<close> \<open>length s = Suc m\<close> by auto
have "eval DS a = eval DR a" for a
proof -
have eval_to_peval:
"eval [polynomial.Param (indices ! k)
= \<Sum>R- indices ! k (s' && z' ! (indices ! k))] y
\<longleftrightarrow>(peval (polynomial.Param (indices ! k)) y
= \<Sum>R- p (indices ! k) (\<lambda>ka. peval (s' ! ka) y && peval (z' ! (indices ! k)) y) )" for k y
using sum_rsub_of_bit_and_eval \<open>length p > 0\<close> \<open>length s' = Suc m\<close> by auto
have b'_unfold: "peval b' (push_list a ks) = peval b a" if "length ks = n" for ks
unfolding pushed_def using indices_def push_push that \<open>length indices + 1 = n\<close> by auto
have r'_unfold: "peval (r' ! (indices ! k)) (push_list a ks) = peval (r!(indices!k)) a"
if "k < length indices" and "length ks = n" for k ks
using indices_def push_push pushed_def that(1) that(2) \<open>length r = n\<close> by auto
have Param_unfold: "peval (Param (indices ! k)) (push_list a ks) = ks!(indices!k)"
if "k < length indices" and "length ks = n" for k ks
using One_nat_def Suc_pred indices_def length_upt nat_add_left_cancel_less
nth_upt peval.simps(2) plus_1_eq_Suc push_list_eval that(1) that(2) by (metis \<open>0 < n\<close>)
have unfold_4: "push_list a ks (indices ! k) = ks!(indices!k)"
if "k < length indices" and "length ks = n" for k ks
using Param_unfold that(1) that(2) by force
have unfold_sum_radd: "\<Sum>R+ p (indices ! k) (\<lambda>x. peval (s' ! x) (push_list a ks))
= \<Sum>R+ p (indices ! k) (list_eval s a)"
if "length ks = n" for k ks
apply (rule sum_radd_cong) unfolding pushed_def
using push_push_map_i[of ks n _ s a] \<open>length indices + 1 = n\<close> that
using \<open>length p = length s\<close>
by (metis \<open>0 < length p\<close> add.left_neutral add_lessD1 le_neq_implies_less less_add_one
less_diff_conv less_diff_conv2 nat_le_linear not_add_less1)
have unfold_sum_rsub: "\<Sum>R- p (indices ! k) (\<lambda>ka. peval (s' ! ka) (push_list a ks)
&& peval (z' ! (indices ! k)) (push_list a ks))
= \<Sum>R- p (indices ! k) (\<lambda>ka. list_eval s a ka
&& peval (z ! (indices ! k)) a)"
if "length ks = n" for k ks
apply (rule sum_rsub_cong) unfolding pushed_def
using push_push_map_i[of ks n _ s a] unfolding \<open>length indices + 1 = n\<close>
using \<open>length p = length s\<close> assms apply simp
using nth_map[of _ z "\<lambda>x. push_param x (Suc (length indices))"]
using modifies_yields_valid_register \<open>length z = n\<close>
by (smt assms le_imp_less_Suc nth_map push_push_simp that)
have indices_unfold: "(\<forall>k < length indices. P (indices!k)) \<longleftrightarrow> (\<forall>l>0. l<n \<longrightarrow> P l)" for P
unfolding indices_def apply auto
using \<open>n>0\<close> by (metis Suc_diff_Suc diff_zero not_less_eq)
have alternative_sum_rsub:
"(\<Sum>R- p l (\<lambda>ka. list_eval s a ka && peval (z ! l) a))
=(\<Sum>R- p l (\<lambda>k. map (\<lambda>P. peval P a) s ! k && map (\<lambda>P. peval P a) z ! l))" for l
apply (rule sum_rsub_cong) unfolding list_eval_def apply simp
using modifies_yields_valid_register
One_nat_def assms(3) nth_map \<open>length z = n\<close> \<open>length s = Suc m\<close>
by (metis \<open>length p = length s\<close> le_imp_less_Suc m_def)
(* Start of chain of equalities *)
have "(eval DS a) = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices. eval [Param (indices ! k)
= \<Sum>R- (indices ! k) (s' && z' ! (indices ! k))] (push_list a ks)) \<and>
(\<forall>k<length indices. eval (single_register (indices ! k)) (push_list a ks)))"
unfolding DS_def params_are_sum_rsub_of_bitand_def param_l_is_sum_rsub_of_bitand_def
by (simp add: defs)
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices.
peval (Param (indices ! k)) (push_list a ks)
= \<Sum>R- p (indices ! k) (\<lambda>ka. peval (s' ! ka) (push_list a ks)
&& peval (z' ! (indices ! k)) (push_list a ks)) \<and>
peval (r' ! (indices ! k)) (push_list a ks)
= peval b' (push_list a ks) * peval (r' ! (indices ! k)) (push_list a ks)
+ peval b' (push_list a ks) * \<Sum>R+ p (indices ! k)
(\<lambda>x. peval (s' ! x) (push_list a ks))
- peval b' (push_list a ks) * (push_list a ks (indices ! k))))"
using eval_to_peval unfolding single_register_def
using sum_radd_polynomial_eval \<open>length p > 0\<close> by (simp add: defs) (blast)
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices.
ks!(indices!k)
= \<Sum>R- p (indices ! k) (\<lambda>ka. peval (s' ! ka) (push_list a ks)
&& peval (z' ! (indices ! k)) (push_list a ks)) \<and>
peval (r!(indices!k)) a
= peval b a * peval (r!(indices!k)) a
+ peval b a * \<Sum>R+ p (indices ! k) (\<lambda>x. peval (s' ! x) (push_list a ks))
- peval b a * (ks!(indices!k))))"
using b'_unfold r'_unfold Param_unfold unfold_4 by (smt (z3))
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices.
ks!(indices!k)
= (\<Sum>R- p (indices ! k) (\<lambda>ka. peval (s' ! ka) (push_list a ks)
&& peval (z' ! (indices ! k)) (push_list a ks))) \<and>
peval (r!(indices!k)) a
= peval b a * peval (r!(indices!k)) a
+ peval b a * (\<Sum>R+ p (indices ! k) (list_eval s a))
- peval b a * (ks!(indices!k))))"
using unfold_sum_radd by (smt (z3))
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices.
ks!(indices!k)
= \<Sum>R- p (indices ! k) (\<lambda>ka. list_eval s a ka && peval (z ! (indices ! k)) a)
\<and> peval (r!(indices!k)) a
= peval b a * peval (r!(indices!k)) a
+ peval b a * (\<Sum>R+ p (indices ! k) (list_eval s a))
- peval b a * (ks!(indices!k))))"
using unfold_sum_rsub by auto
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<length indices.
ks!(indices!k)
= \<Sum>R- p (indices ! k) (\<lambda>ka. list_eval s a ka && peval (z ! (indices ! k)) a)
\<and> peval (r!(indices!k)) a
= peval b a * peval (r!(indices!k)) a
+ peval b a * (\<Sum>R+ p (indices ! k) (list_eval s a))
- peval b a *
(\<Sum>R- p (indices ! k) (\<lambda>ka. list_eval s a ka && peval (z ! (indices ! k)) a))))"
by smt
also have "... = (\<forall>k<length indices.
peval (r!(indices!k)) a
= peval b a * peval (r!(indices!k)) a
+ peval b a * (\<Sum>R+ p (indices ! k) (list_eval s a))
- peval b a *
(\<Sum>R- p (indices ! k) (\<lambda>ka. list_eval s a ka && peval (z ! (indices ! k)) a)))"
unfolding indices_def apply auto
apply (rule exI[of _
"map (\<lambda>k. \<Sum>R- p k (\<lambda>ka. list_eval s a ka && peval (z ! k) a)) [0..<n]"])
by auto
also have "... = (\<forall>l>0. l < n \<longrightarrow>
peval (r!l) a
= peval b a * peval (r!l) a
+ peval b a * (\<Sum>R+ p l (list_eval s a))
- peval b a *
(\<Sum>R- p l (\<lambda>ka. list_eval s a ka && peval (z ! l) a)))"
using indices_unfold[of "\<lambda>x. peval (r ! x) a =
peval b a * peval (r ! x) a + peval b a * (\<Sum>R+ p x (list_eval s a)) -
peval b a * (\<Sum>R- p x (\<lambda>ka. (list_eval s a ka) && peval (z ! x) a))"]
by auto
also have "... = (\<forall>l>0. l < n \<longrightarrow>
peval (r!l) a =
peval b a * map (\<lambda>P. peval P a) r ! l
+ peval b a * (\<Sum>R+ p l ((!) (map (\<lambda>P. peval P a) s)))
- peval b a * (\<Sum>R- p l (\<lambda>k. map (\<lambda>P. peval P a) s ! k && map (\<lambda>P. peval P a) z ! l)))"
using nth_map[of _ r "(\<lambda>P. peval P a)"] unfolding \<open>length r = n\<close>
using alternative_sum_rsub list_eval_def by auto
also have "... = (eval DR a)"
apply (simp add: DR_def defs) using rm_eq_fixes_def rm_eq_fixes.register_l_def
local.register_machine_axioms
using nth_map[of _ r "\<lambda>P. peval P a"] unfolding \<open>length r = n\<close> by auto
finally show "eval DS a = eval DR a" by auto
qed
moreover have "is_dioph_rel DS"
proof -
have "list_all (is_dioph_rel \<circ> param_l_is_sum_rsub_of_bitand) indices"
unfolding param_l_is_sum_rsub_of_bitand_def indices_def list_all_def by (auto simp:dioph)
hence "is_dioph_rel params_are_sum_rsub_of_bitand"
unfolding params_are_sum_rsub_of_bitand_def by (auto simp: dioph)
have "list_all (is_dioph_rel \<circ> single_register) indices"
unfolding single_register_def list_all_def indices_def by (auto simp: dioph)
thus ?thesis
unfolding DS_def using \<open>is_dioph_rel params_are_sum_rsub_of_bitand\<close> by (auto simp: dioph)
qed
ultimately show ?thesis
by (auto simp: is_dioph_rel_def)
qed
lemma register_bound_dioph:
fixes b q :: polynomial
fixes r :: "polynomial list"
assumes "length r = n"
defines "DR \<equiv> LARY (\<lambda>ll. rm_eq_fixes.register_bound n (ll!0!0) (ll!0!1) (nth (ll!1)))
[[b, q], r]"
shows "is_dioph_rel DR"
proof -
define indices where "indices \<equiv> [0..<n]" (* for now *)
hence "length indices = n" by auto
let ?N = "length indices"
define b' q' r' where pushed_def: "b' = push_param b ?N"
"q' = push_param q ?N"
"r' = map (\<lambda>x. push_param x ?N) r"
define bound where
"bound \<equiv> \<lambda>l. (r'!l [<] (Param l) [\<and>] [Param l = b' ^ q'])"
define DS where "DS \<equiv> [\<exists>n] [\<forall> in indices] bound"
have "eval DS a = eval DR a" for a
proof -
have r'_unfold: "peval (r' ! k) (push_list a ks) = peval (r ! k) a"
if "length ks = n" and "k < length ks" for k ks
unfolding pushed_def \<open>length indices = n\<close>
using push_push_map_i[of ks n k r] that \<open>length r = n\<close> list_eval_def by auto
have b'_unfold: "peval b' (push_list a ks) = peval b a"
and q'_unfold: "peval q' (push_list a ks) = peval q a"
if "length ks = n" and "k < length ks" for k ks
unfolding pushed_def \<open>length indices = n\<close>
using push_push_simp that \<open>length r = n\<close> list_eval_def by auto
have "eval DS a = (\<exists>ks. n = length ks \<and>
(\<forall>k<n. peval (r' ! k) (push_list a ks) < push_list a ks k \<and>
push_list a ks k = peval b' (push_list a ks) ^ peval q' (push_list a ks)))"
unfolding DS_def indices_def bound_def by (simp add: defs)
also have "... = (\<exists>ks. n = length ks \<and>
(\<forall>k<n. peval (r ! k) a < peval b a ^ peval q a \<and>
push_list a ks k = peval b a ^ peval q a))"
using r'_unfold b'_unfold q'_unfold by (metis (full_types))
also have "... = (\<forall>k<n. peval (r ! k) a < peval b a ^ peval q a)"
apply auto apply (rule exI[of _ "map (\<lambda>k. peval b a ^ peval q a) [0..<n]"])
unfolding indices_def push_list_def by auto
also have "... = (\<forall>l<n. map (\<lambda>P. peval P a) r ! l < peval b a ^ peval q a)"
using nth_map[of _ r "\<lambda>P. peval P a"] \<open>length r = n\<close> by force
finally show ?thesis unfolding DR_def
using rm_eq_fixes.register_bound_def rm_eq_fixes_def register_machine_def
p_nonempty n_gt_0 valid_program by (auto simp add: defs)
qed
moreover have "is_dioph_rel DS"
proof -
have "list_all (is_dioph_rel \<circ> bound) indices"
unfolding bound_def indices_def list_all_def by (auto simp:dioph)
thus ?thesis unfolding DS_def indices_def bound_def by (auto simp: dioph)
qed
ultimately show ?thesis
by (auto simp: is_dioph_rel_def)
qed
definition register_equations_relation :: "polynomial \<Rightarrow> polynomial \<Rightarrow> polynomial
\<Rightarrow> polynomial list \<Rightarrow> polynomial list \<Rightarrow> polynomial list \<Rightarrow> relation" ("[REG] _ _ _ _ _ _") where
"[REG] a b q r z s \<equiv> LARY (\<lambda>ll. rm_eq_fixes.register_equations p n (ll!0!0) (ll!0!1) (ll!0!2)
(nth (ll!1)) (nth (ll!2)) (nth (ll!3))) [[a, b, q], r, z, s]"
lemma reg_dioph:
fixes A b q r z s
assumes "length r = n" "length z = n" "length s = Suc m"
defines "DR \<equiv> [REG] A b q r z s"
shows "is_dioph_rel DR"
proof -
define DS where "DS \<equiv> (LARY (\<lambda>ll. rm_eq_fixes.register_0 p (ll!0!0) (ll!0!1)
(nth (ll!1)) (nth (ll!2)) (nth (ll!3))) [[A, b], r, z, s])
[\<and>] (LARY (\<lambda>ll. rm_eq_fixes.register_l p n (ll!0!0)
(nth (ll!1)) (nth (ll!2)) (nth (ll!3))) [[b], r, z, s])
[\<and>] (LARY (\<lambda>ll. rm_eq_fixes.register_bound n (ll!0!0) (ll!0!1) (nth (ll!1)))
[[b, q], r])"
have "eval DS a = eval DR a" for a
unfolding DS_def DR_def register_equations_relation_def rm_eq_fixes.register_equations_def
apply (simp add: defs)
by (simp add: register_machine_axioms rm_eq_fixes.intro rm_eq_fixes.register_equations_def)
moreover have "is_dioph_rel DS"
unfolding DS_def using assms register_0_dioph[of r z s] register_l_dioph[of r z s]
register_bound_dioph by (auto simp: dioph)
ultimately show ?thesis by (auto simp: is_dioph_rel_def)
qed
end
end |
function y = acot(x)
%ACOT Implements acot(x) for intervals
%
% y = acot(x)
%
%interval standard function implementation
%
% written 10/16/98 S.M. Rump
% modified 06/24/99 S.M. Rump complex allowed, sparse input,
% major revision, improved accuracy
% modified 04/04/04 S.M. Rump set round to nearest for safety
% accelaration for sparse input
% modified 04/06/05 S.M. Rump rounding unchanged
% modified 09/06/07 S.M. Rump improved performance
% modified 10/20/08 S.M. Rump check for zero
% modified 08/26/12 S.M. Rump global variables removed
% modified 10/13/12 S.M. Rump INTLAB_INTVAL_STDFCTS
%
index = ( x==0 );
y = atan(1./x);
if ~isempty(find(index)) % treat zero indices
INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');
PI2 = intval(INTLAB_STDFCTS_PI.PI2INF,INTLAB_STDFCTS_PI.PI2SUP,'infsup');
%VVVV y(index) = PI2;
s.type = '()'; s.subs = {index}; y = subsasgn(y,s,PI2);
%AAAA Matlab bug fix
end
|
/*
* Software License Agreement (BSD License)
*
* Robot Operating System code by the University of Osnabrück
* Copyright (c) 2015, University of Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*
* MapDisplay.hpp
*
*
* authors:
*
* Kristin Schmidt <[email protected]>
* Jan Philipp Vogtherr <[email protected]>
*/
#ifndef MAP_DISPLAY_HPP
#define MAP_DISPLAY_HPP
#include <Types.hpp>
#include "RvizFileProperty.hpp"
#include <vector>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
#include <QMessageBox>
#include <QApplication>
#include <QIcon>
#include <ros/ros.h>
#include <ros/console.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/visualization_manager.h>
#include <rviz/visualization_frame.h>
#include <rviz/geometry.h>
#include <rviz/display_context.h>
#include <rviz/frame_manager.h>
#include <rviz/display.h>
#include <rviz/tool.h>
#include <rviz/tool_manager.h>
#include <rviz/display_group.h>
#include <std_msgs/Int32.h>
#include <geometry_msgs/Point32.h>
#include <geometry_msgs/PoseStamped.h>
#include <mesh_msgs/MeshGeometryStamped.h>
#include <mesh_msgs/MeshGeometry.h>
#include <mesh_msgs/GetGeometry.h>
#include <mesh_msgs/GetLabeledClusters.h>
#include <hdf5_map_io/hdf5_map_io.h>
#ifndef Q_MOC_RUN
#include <rviz/mesh_loader.h>
#include <OGRE/OgreManualObject.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreStringConverter.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreRay.h>
#include <OGRE/OgreSceneQuery.h>
#include <OGRE/OgreColourValue.h>
#endif
#include <ClusterLabelDisplay.hpp>
#include <MeshDisplay.hpp>
namespace rviz
{
// Forward declaration
class BoolProperty;
class ColorProperty;
class FloatProperty;
class IntProperty;
class EnumProperty;
class StringProperty;
} // End namespace rviz
namespace rviz_map_plugin
{
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
/**
* @class MapDisplay
* @brief Master display for the Mesh- and Cluster- subdisplays. THis implementation uses HDF5 as it's data source
*/
class MapDisplay : public rviz::Display
{
Q_OBJECT
public:
/**
* @brief Constructor
*/
MapDisplay();
/**
* @brief Destructor
*/
~MapDisplay();
public Q_SLOTS:
/**
* @brief Saves a label to HDF5
* @param cluster The cluster to be saved
*/
void saveLabel(Cluster cluster);
/**
* @brief Get the geometry
* @return The geometry
*/
shared_ptr<Geometry> getGeometry();
private Q_SLOTS:
/**
* @brief Update the map, based on the current data state
*/
void updateMap();
private:
/**
* @brief RViz callback on initialize
*/
void onInitialize();
/**
* @brief RViz callback on enable
*/
void onEnable();
/**
* @brief RViz callback on disable
*/
void onDisable();
/**
* @brief Read all data from the HDF5 file and save it in the member variables
* @return true, if successful
*/
bool loadData();
// TODO: make more efficient - currently everything is stored in the MapDisplay, the MeshDisplay and the MeshVisual
/// Geometry
shared_ptr<Geometry> m_geometry;
/// Materials
vector<Material> m_materials;
/// Textures
vector<Texture> m_textures;
/// Colors
vector<Color> m_colors;
/// Vertex normals
vector<Normal> m_normals;
/// Texture coordinates
vector<TexCoords> m_texCoords;
/// Clusters
vector<Cluster> m_clusterList;
std::map<std::string, std::vector<float>> m_costs;
/// Path to map file
rviz::FileProperty* m_mapFilePath;
/// Subdisplay: ClusterLabel (for showing the clusters)
rviz_map_plugin::ClusterLabelDisplay* m_clusterLabelDisplay;
/// Subdisplay: MeshDisplay (for showing the mesh)
rviz_map_plugin::MeshDisplay* m_meshDisplay;
/**
* @brief Create a RViz display from it's unique class_id
* @param class_id The class ID
* @return Pointer to RViz display
*/
rviz::Display* createDisplay(const QString& class_id);
};
} // end namespace rviz_map_plugin
#endif
|
@testset "7.2 Inverse hyperbolic cosine" begin
include("(d+e x)^p (-d+e x)^q (a+b arccosh(c x))^n.jl")
include("7.2.2 (d x)^m (a+b arccosh(c x))^n.jl")
include("7.2.4 (f x)^m (d+e x^2)^p (a+b arccosh(c x))^n.jl")
include("7.2.5 Inverse hyperbolic cosine functions.jl")
end
|
import algebraic_topology.alternating_face_map_complex
import algebraic_topology.simplicial_set
import algebra.category.Module.abelian
import algebra.category.Module.adjunctions
import algebra.homology.homology
import algebra.homology.Module
import algebra.homology.homotopy
import topology.homotopy.basic
import algebraic_topology.simplex_category
import algebraic_topology.topological_simplex
import topology.constructions
import topology.algebra.group_with_zero
import topology.category.CompHaus.default
import topology.homotopy.product topology.homotopy.contractible
import analysis.convex.contractible
import analysis.convex.topology
import data.opposite data.finset.pointwise
import .simplices .instances .general_topology .homological_algebra .linear_algebra
import .acyclic_models_theorem .singular_homology_definitions
open category_theory algebraic_topology
notation `I` := unit_interval
section
local attribute [instance]
category_theory.concrete_category.has_coe_to_sort
category_theory.concrete_category.has_coe_to_fun
-- The following proof is taken from Tom Dieck's book
def q_map (n : ℕ) (t : I) (x : topological_simplex n) : topological_simplex (n + 1) :=
⟨λ k, if k = 0
then t
else unit_interval.symm t * x.val (simplex_category.σ 0 k),
begin
dsimp [topological_simplex, simplex_category.to_Top'_obj, std_simplex],
rw finset.sum_ite,
split,
{ intro k, split_ifs, exact t.property.left,
exact mul_nonneg (unit_interval.symm t).property.left (x.property.left _) },
transitivity (t : ℝ) + finset.univ.sum (λ k, unit_interval.symm t * x.val k),
{ apply congr_arg2,
{ rw finset.sum_const,
refine eq.trans _ (one_smul ℕ _),
congr,
rw finset.card_eq_one,
existsi (0 : simplex_category.mk (n + 1)),
ext, simp },
{ rw sum_over_n_simplices_eq, refl } },
{ transitivity (t : ℝ) + unit_interval.symm t * 1,
{ congr, cases x with x hx, rw ← hx.right,
symmetry, apply finset.mul_sum },
{ cases t, simp [unit_interval.symm] } }
end⟩
lemma q_map_on_zero (n : ℕ) (t : unit_interval) (x : topological_simplex n)
: @coe_fn _ _ (simplex_category.to_Top'_obj.has_coe_to_fun (simplex_category.mk (n + 1)))
(q_map n t x) 0 = t := rfl
lemma q_map_on_nonzero (n : ℕ) (t : unit_interval) (x : topological_simplex n)
(k : simplex_category.mk (n + 1)) (h : k ≠ 0)
: @coe_fn _ _ (simplex_category.to_Top'_obj.has_coe_to_fun (simplex_category.mk (n + 1)))
(q_map n t x) k
= (unit_interval.symm t).val * x.val (simplex_category.σ 0 k) :=
by { dsimp [q_map, coe_fn, simplex_category.to_Top'_obj.has_coe_to_fun],
rw ite_eq_right_iff, intro, contradiction }
lemma q_continuous (n : ℕ) : continuous (function.uncurry (q_map n)) :=
begin
apply continuous_subtype_mk,
continuity, cases i with i hi,
apply continuous_if_const; intro h,
{ continuity },
{ cases i with i, trivial,
continuity,
apply @continuous.snd' _ _ _ _ _ _
(λ x : topological_simplex n, x.val (simplex_category.σ 0 ⟨i.succ, hi⟩)),
have : continuous (λ (x : simplex_category.mk n → ℝ), x (simplex_category.σ 0 ⟨i.succ, hi⟩)),
{ apply continuous_apply },
apply continuous.congr (this.comp continuous_subtype_val),
intro, refl }
end
lemma q_map_zero_left (n : ℕ) (x : topological_simplex n)
: q_map n 0 x = inclusion n x :=
begin
cases x with x hx,
ext j, cases j with j hj, cases j with j,
{ transitivity (0 : ℝ), refl, symmetry,
simp [inclusion],
apply finset.sum_eq_zero,
intros i H,
exfalso,
refine fin.succ_ne_zero i _,
simp at H, exact H },
{ rw q_map_on_nonzero,
simp [inclusion],
symmetry, apply finset.sum_eq_single_of_mem,
{ simp, ext, refl },
{ intros b hb H,
exfalso,
cases b with b hb',
simp at hb,
apply H, rw ← hb,
refl },
{ intro H, apply nat.succ_ne_zero j, apply congr_arg subtype.val H } }
end
lemma q_map_one_left (n : ℕ) (x : topological_simplex n)
: q_map n 1 x = const_vertex n 0 x :=
begin
rw const_desc, apply eq_vertex, refl
end
def q (n : ℕ) : continuous_map.homotopy (inclusion n) (const_vertex n 0) := {
to_fun := function.uncurry (q_map n),
continuous_to_fun := q_continuous n,
map_zero_left' := q_map_zero_left n,
map_one_left' := q_map_one_left n
}
noncomputable
def q_section (n : ℕ)
: C({ σ : topological_simplex (n + 1) // σ.val 0 ≠ 1 }, I × topological_simplex n) := {
to_fun := λ x,
let t : ℝ := x.val.val 0,
ht : t ≠ 1 := x.property,
y' : simplex_category.mk n → ℝ := λ i, x.val.val (i + 1) / (1 - t) in
have t_le_one : t ≤ 1, from topological_simplex.coord_le_one (n+1) 0 x,
have denom_pos : 0 < 1 - t,
from lt_of_le_of_ne (le_sub.mp (le_of_le_of_eq t_le_one (sub_zero 1).symm))
(λ h, ht (sub_eq_zero.mp h.symm).symm),
have denom_nonzero : 1 - (t : ℝ) ≠ 0, from ne.symm (ne_of_lt denom_pos),
have hy1 : ∀ i, 0 ≤ y' i, from λ i, div_nonneg (x.val.property.left _) (le_of_lt denom_pos),
have hy2 : finset.univ.sum y' = 1,
by { rw ← div_self denom_nonzero,
rw eq_div_iff denom_nonzero,
rw finset.sum_mul,
rw eq_sub_iff_add_eq,
refine eq.trans _ x.val.property.right,
rw ← finset.insert_erase (finset.mem_univ (0 : simplex_category.mk (n + 1))),
rw finset.sum_insert (finset.not_mem_erase _ _),
rw add_comm,
apply congr_arg2, refl,
rw sum_over_n_simplices_eq,
apply finset.sum_congr,
{ ext, rw finset.mem_filter, simp },
{ intros k hk,
rw finset.mem_erase at hk, simp at hk,
rw div_mul_cancel _ denom_nonzero,
congr,
symmetry, transitivity, symmetry, exact succ_sigma_of_nonzero n k hk,
simp } },
(⟨t, x.val.property.left 0, t_le_one⟩, ⟨y', (λ i, hy1 i), hy2⟩),
continuous_to_fun := by {
continuity,
{ refine continuous.congr (((continuous_apply 0).comp continuous_subtype_val).comp
continuous_subtype_val) _,
intro, refl },
change continuous
(λ x, (λ x' : {σ : topological_simplex (n + 1) // σ.val 0 ≠ 1}, x'.val.val (i + 1)) x
/ (λ x' : {σ : topological_simplex (n + 1) // σ.val 0 ≠ 1}, 1 - x'.val.val 0) x),
apply continuous.div,
{ refine continuous.congr (((continuous_apply (↑i + 1)).comp continuous_subtype_val).comp
continuous_subtype_val) _,
intro, refl },
{ suffices : continuous (λ x : simplex_category.mk (n + 1) → ℝ, 1 - x 0),
{ apply continuous.congr ((this.comp continuous_subtype_val).comp continuous_subtype_val),
intro, refl },
continuity },
{ intros x hx, exact x.property (sub_eq_zero.mp hx).symm }
}
}
lemma q_section_is_section (n : ℕ) (σ : topological_simplex (n + 1)) (h : σ.val 0 ≠ 1)
: function.uncurry (q_map n) (q_section n ⟨σ, h⟩) = σ :=
begin
dsimp [function.uncurry],
ext k,
by_cases h' : (k = 0),
{ rw h', refl },
{ rw q_map_on_nonzero _ _ _ _ h',
simp [q_section, unit_interval.symm],
rw [subtype.coe_mk, mul_comm, div_mul_cancel _ _],
{ congr, apply succ_sigma_of_nonzero, assumption },
{ intro h'', apply h, symmetry, rw ← sub_eq_zero, exact h'' } }
end
lemma q_section_on_preimage_of_image
(n : ℕ) (p : I × topological_simplex n) (h : (function.uncurry (q_map n) p).val 0 ≠ 1)
: q_section n ⟨function.uncurry (q_map n) p, h⟩ = p :=
begin
cases p with t σ, ext,
{ simp [q_map, q_section] },
{ simp [q_section],
change (q_map n t σ).val (fin.succ x) / (1 - t) = σ.val x,
apply div_eq_of_eq_mul (λ h', h.symm (sub_eq_zero.mp h')),
transitivity, apply q_map_on_nonzero n t σ (fin.succ x) (fin.succ_ne_zero x),
simp [q_map], rw mul_comm, congr,
exact eq.trans (fin.pred_above_zero (fin.succ_ne_zero x)) (fin.pred_succ _) }
end
lemma q_surj (n : ℕ) : function.surjective (function.uncurry (q_map n)) :=
begin
intro x,
by_cases (x.val 0 = 1),
{ existsi ((1 : unit_interval), vertex n 0),
dsimp [function.uncurry],
rw q_map_one_left,
symmetry,
rw const_desc,
apply eq_vertex,
assumption },
{ exact ⟨q_section n ⟨x, h⟩, q_section_is_section n x h⟩ }
end
lemma q_quot (n : ℕ) : quotient_map (function.uncurry (q_map n)) :=
begin
-- why doesn't this get found by typeclass instance resolution :(
have : compact_space (I × topological_simplex n),
{ change compact_space (I × std_simplex ℝ (fin (n + 1))),
refine @prod.compact_space I (std_simplex ℝ (fin (n + 1))) _ _ _
(is_compact_iff_compact_space.mp (compact_std_simplex (fin (n + 1)))) },
apply @surjection_of_compact_hausdorff_is_quot_map _ _ _ _ this,
apply q_surj,
apply q_continuous
end
lemma q_fiber_desc {n : ℕ} {x y : I × topological_simplex n}
(H : function.uncurry (q_map n) x = function.uncurry (q_map n) y)
: (x.fst = (1 : unit_interval) ∧ y.fst = (1 : unit_interval)) ∨ x = y :=
begin
cases x with t a, cases y with s b,
dsimp, dsimp [function.uncurry] at H,
cases t with t ht, cases s with s hs,
have : t = s,
{ change ((q_map n ⟨t, ht⟩ a).val 0 = (q_map n ⟨s, hs⟩ b).val 0),
congr, assumption },
by_cases (t = 1),
{ left, split; ext; simp, assumption, rw ← this, assumption },
{ right, simp, split, assumption,
transitivity (q_section n ⟨function.uncurry (q_map n) (⟨t, ht⟩, a), h⟩).snd,
{ symmetry, exact congr_arg prod.snd (q_section_on_preimage_of_image n (⟨t, ht⟩, a) h) },
{ have h' := this.subst h,
transitivity (q_section n ⟨function.uncurry (q_map n) (⟨s, hs⟩, b), h'⟩).snd,
{ congr' 3 },
{ exact congr_arg prod.snd (q_section_on_preimage_of_image n (⟨s, hs⟩, b) h') } } }
end
lemma q_of_coface {n : ℕ} (j : fin (n + 2))
(t : unit_interval) (x : topological_simplex n)
: q_map (n + 1) t (simplex_category.to_Top'_map (simplex_category.δ j) x)
= simplex_category.to_Top'_map (simplex_category.δ j.succ) (q_map n t x) :=
begin
ext k : 2, by_cases (k = 0),
{ subst h,
rw q_map_on_zero,
simp only [fin.coe_eq_cast_succ, simplex_category.coe_to_Top'_map],
transitivity ({0} : finset (simplex_category.mk (n + 1))).sum (q_map n t x).val,
{ rw finset.sum_singleton, refl },
{ congr, symmetry,
rw finset.eq_singleton_iff_unique_mem,
split,
{ rw finset.mem_filter,
simp only [true_and, finset.mem_univ],
refine (fin.succ_above_eq_zero_iff _).mpr rfl,
apply fin.succ_ne_zero },
{ intros k hk,
rw finset.mem_filter at hk,
refine (fin.succ_above_eq_zero_iff _).mp hk.right,
apply fin.succ_ne_zero } } },
{ rw q_map_on_nonzero _ _ _ _ h,
simp only [fin.coe_eq_cast_succ, simplex_category.coe_to_Top'_map, subtype.val_eq_coe],
dsimp [simplex_category.to_Top'_map],
rw finset.mul_sum,
refine @finset.sum_bij' ℝ (simplex_category.mk n) (simplex_category.mk (n + 1)) _
_ _
_ _
(λ t _, simplex_category.δ 0 t) --i
_
_
(λ t _, simplex_category.σ 0 t) --j
_
_
_,
{ intros i hi,
simp only [true_and, finset.mem_univ, finset.mem_filter] at hi ⊢,
transitivity (simplex_category.δ 0 ≫ simplex_category.δ (fin.succ j)) i,
refl,
rw simplex_category.δ_comp_δ (fin.zero_le _),
transitivity simplex_category.δ 0 (simplex_category.σ 0 k),
rw ← hi,
refl,
exact succ_sigma_of_nonzero _ k h },
{ intros i hi, simp, split_ifs,
{ exfalso, apply coface_map_misses_output, assumption },
{ congr, symmetry,
transitivity (simplex_category.δ (fin.cast_succ 0) ≫ simplex_category.σ 0) i, refl,
rw simplex_category.δ_comp_σ_self, refl } },
{ intros i hi,
simp only [true_and, finset.mem_univ, finset.mem_filter] at hi ⊢,
rw ← hi,
apply fourth_simplicial_identity_modified,
intro H, cases H with H1 H2, subst H1, subst H2,
apply h, rw ← hi, refl },
{ intros i hi,
simp only [true_and, finset.mem_univ, finset.mem_filter],
transitivity (simplex_category.δ (fin.cast_succ 0) ≫ simplex_category.σ 0) i, refl,
rw simplex_category.δ_comp_σ_self, refl },
{ intros i hi,
simp only [true_and, finset.mem_univ, finset.mem_filter] at hi ⊢,
apply succ_sigma_of_nonzero,
intro h', apply h,
rw ← hi, rw h',
apply fin.succ_above_ne_zero_zero,
apply fin.succ_ne_zero } }
end
end
section
noncomputable
def ε_map (R : Type*) [comm_ring R] {X : Top} (x0 : X) : Π (n : ℕ),
((singular_chain_complex R).obj X).X n → ((singular_chain_complex R).obj X).X n
| 0 := λ x, finsupp.sum x (λ _ n, n • simplex_to_chain (singular_zero_simplex_of_pt x0) R)
| _ := 0
noncomputable
def ε_hom (R : Type*) [comm_ring R] {X : Top} (x0 : X) (n : ℕ) :
((singular_chain_complex R).obj X).X n ⟶ ((singular_chain_complex R).obj X).X n := {
to_fun := ε_map R x0 n,
map_add' := by { intros, cases n; dsimp [ε_map],
{ apply finsupp.sum_add_index',
{ intro, simp },
{ intros, apply add_smul } },
{ rw zero_add } },
map_smul' := by {
intros, cases n; dsimp [ε_map],
{ rw [finsupp.smul_sum, finsupp.sum_smul_index'],
congr, ext, rw smul_assoc,
intro, apply zero_smul },
symmetry, apply smul_zero }
}
noncomputable
def ε (R : Type*) [comm_ring R] {X : Top} (x0 : X)
: (singular_chain_complex R).obj X ⟶ (singular_chain_complex R).obj X := {
f := ε_hom R x0,
comm' := by {
intros i j h, simp at h, subst h,
cases j; ext σ σ'; simp [ε_hom, ε_map],
{ rw singular_chain_complex_differential_desc_deg_0,
rw finsupp.sum_sub_index,
{ symmetry, rw sub_eq_zero, dsimp [simplex_to_chain],
rw [finsupp.sum_single_index, finsupp.sum_single_index]; simp },
{ intros, rw sub_mul } } }
}
noncomputable
def cone_construction_lift_simplex {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0)) (i : ℕ)
(σ : Top.of (topological_simplex i) ⟶ X) : Top.of (topological_simplex (i + 1)) ⟶ X :=
let σ' : (Top.of (I × topological_simplex i)) ⟶ (Top.of (I × X)) :=
category_theory.functor.map cylinder.{0} σ,
Hσ' : Top.of (I × topological_simplex i) ⟶ X := σ' ≫ H.to_continuous_map
in @lift_along_quot_map (Top.of (I × topological_simplex i)) (Top.of (topological_simplex (i + 1))) X
⟨function.uncurry (q_map i), q_continuous i⟩
Hσ' (q_quot i)
(by { intros x y Hxy,
cases q_fiber_desc Hxy,
{ dsimp [Hσ', σ', cylinder],
rw [h.left, h.right],
transitivity, apply H.map_one_left',
symmetry, transitivity, apply H.map_one_left',
refl },
{ rw h } })
noncomputable
def cone_construction_hom (R : Type*) [comm_ring R] {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0)) (i : ℕ)
: ((singular_chain_complex R).obj X).X i ⟶ ((singular_chain_complex R).obj X).X (i + 1) :=
(Module.free R).map (cone_construction_lift_simplex x0 H i)
lemma cone_construction_hom_naturality (R : Type*) [comm_ring R] {X Y : Top} (x0 : X) (y0 :Y)
(f : X ⟶ Y)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0))
(H' : continuous_map.homotopy (continuous_map.id Y) (continuous_map.const Y y0)) (i : ℕ)
(hf : cylinder.map f ≫ H'.to_continuous_map = H.to_continuous_map ≫ f)
: cone_construction_hom R x0 H i ≫ ((singular_chain_complex R).map f).f (i + 1)
= ((singular_chain_complex R).map f).f i ≫ cone_construction_hom R y0 H' i :=
begin
delta singular_chain_complex free_complex_on_sset,
simp [cone_construction_hom],
refine eq.trans (finsupp.lmap_domain_comp R R _ _).symm
(eq.trans _ (finsupp.lmap_domain_comp R R _ _)),
apply congr_arg,
ext σ : 1,
symmetry, dsimp [Top.to_sSet'],
dsimp [cone_construction_lift_simplex],
rw lift_along_quot_map_comm_square,
congr' 1,
rw [category.assoc, ← hf], simp
end
noncomputable
def cone_construction_complex_hom (R : Type*) [comm_ring R] {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0))
(i j : ℕ) : ((singular_chain_complex R).obj X).X i ⟶ ((singular_chain_complex R).obj X).X j :=
if h : i + 1 = j
-- Should make this use eq_to_hom
then @eq.rec _ _ (λ n, ((singular_chain_complex R).obj X).X i
⟶ ((singular_chain_complex R).obj X).X n)
(cone_construction_hom R x0 H i) _ h
else 0
lemma cone_construction_hom_on_face {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0)) (i : ℕ)
(j : fin (i + 2))
(σ : Top.of (topological_simplex (i + 1)) ⟶ X)
: cone_construction_lift_simplex x0 H i
(simplex_category.to_Top'.map (simplex_category.δ j) ≫ σ)
= simplex_category.to_Top'.map (simplex_category.δ j.succ)
≫ cone_construction_lift_simplex x0 H (i + 1) σ :=
begin
ext p, simp,
cases (q_surj i p) with p',
subst h,
transitivity H (p'.fst, σ (simplex_category.to_Top'.map (simplex_category.δ j) p'.snd)),
{ refine @lift_along_quot_map_spec (Top.of (I × topological_simplex i))
(Top.of (topological_simplex (i + 1))) X
⟨function.uncurry (q_map i), q_continuous i⟩
_ _ _
(function.uncurry (q_map i) p')
_
_,
refl },
{ symmetry,
refine @lift_along_quot_map_spec (Top.of (I × topological_simplex (i+1)))
(Top.of (topological_simplex (i + 2))) X
⟨function.uncurry (q_map (i + 1)), q_continuous (i + 1)⟩
_ _ _
(simplex_category.to_Top'_map (simplex_category.δ j.succ)
(function.uncurry (q_map i) p'))
(p'.fst, simplex_category.to_Top'.map (simplex_category.δ j)
p'.snd)
_,
cases p' with p1 p2, simp,
apply q_of_coface }
end
lemma cone_construction_hom_at_vertex {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0)) (i : ℕ)
(σ : Top.of (topological_simplex i) ⟶ X)
: (cone_construction_lift_simplex x0 H i σ) (vertex (i + 1) 0)
= x0 :=
begin
transitivity H (1, σ (vertex i 0)),
{ refine @lift_along_quot_map_spec (Top.of (I × topological_simplex i))
(Top.of (topological_simplex (i + 1))) X
⟨function.uncurry (q_map i), q_continuous i⟩
_ _ _ (vertex (i + 1) 0) ((1 : unit_interval), vertex i 0) _,
simp, rw q_map_one_left,
rw const_desc },
{ transitivity, exact H.map_one_left' _, refl }
end
lemma cone_construction_complex_hom_desc_base {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0)) (i : ℕ)
(p : topological_simplex i) (σ : Top.of (topological_simplex i) ⟶ X)
: (cone_construction_lift_simplex x0 H i σ) (inclusion i p)
= σ p :=
begin
transitivity H (0, σ p),
{ refine @lift_along_quot_map_spec (Top.of (I × topological_simplex i))
(Top.of (topological_simplex (i + 1))) X
⟨function.uncurry (q_map i), q_continuous i⟩
_ _ _ (inclusion i p) ((0 : unit_interval), p) _,
simp, rw q_map_zero_left },
{ transitivity, exact H.map_zero_left' _, refl }
end
lemma cone_construction_comm_zero (R : Type*) [comm_ring R] {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0))
(σ : Top.of (topological_simplex 0) ⟶ X)
: finsupp.single σ 1
= d_next 0 (cone_construction_complex_hom R x0 H) (finsupp.single σ 1)
+ prev_d 0 (cone_construction_complex_hom R x0 H) (finsupp.single σ 1)
+ simplex_to_chain (singular_zero_simplex_of_pt x0) R :=
begin
simp,
dsimp [cone_construction_complex_hom],
split_ifs, swap, contradiction,
dsimp [cone_construction_hom],
rw finsupp.map_domain_single,
rw singular_chain_complex_differential_desc_deg_0,
dsimp [simplex_to_chain],
rw [sub_eq_add_neg, add_assoc, add_comm (-_), ← sub_eq_add_neg],
rw (sub_eq_zero.mpr _),
{ rw add_zero, congr,
apply @continuous_map.ext (topological_simplex 0),
rw unique.forall_iff,
dsimp [default],
rw deg_zero_zeroth_coface_map_is_vertex_one,
rw (_ : vertex _ _ = inclusion 0 topological_simplex.point),
{ rw cone_construction_complex_hom_desc_base },
{ symmetry, exact deg_zero_zeroth_coface_map_is_vertex_one } },
{ congr,
apply @continuous_map.ext (topological_simplex 0),
rw unique.forall_iff,
dsimp [default],
rw deg_zero_oneth_coface_map_is_vertex_zero,
rw cone_construction_hom_at_vertex,
refl }
end
lemma cone_construction_comm_higher_deg (R : Type*) [comm_ring R] {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0))
(i : ℕ) (σ : Top.of (topological_simplex (i + 1)) ⟶ X)
: finsupp.single σ 1
= d_next (i + 1) (cone_construction_complex_hom R x0 H) (finsupp.single σ 1)
+ prev_d (i + 1) (cone_construction_complex_hom R x0 H) (finsupp.single σ 1) :=
begin
simp,
dsimp [cone_construction_complex_hom],
split_ifs, swap, contradiction,
symmetry, rw ← eq_sub_iff_add_eq',
transitivity, exact congr_arg _ finsupp.map_domain_single,
rw singular_chain_complex_differential_desc,
rw fin.sum_univ_succ,
rw sub_eq_add_neg, apply congr_arg2,
{ simp [simplex_to_chain],
congr,
ext p,
apply cone_construction_complex_hom_desc_base },
{ rw [singular_chain_complex_differential_desc, map_sum],
rw ← finset.sum_neg_distrib,
congr,
ext j,
rw linear_map.map_smul_of_tower,
apply congr_fun, apply congr_arg,
rw ← neg_smul,
apply congr_arg2,
{ rw fin.coe_succ,
rw pow_succ,
simp only [neg_mul, one_mul, eq_self_iff_true, neg_inj] },
{ delta simplex_to_chain,
symmetry, transitivity, exact finsupp.map_domain_single,
apply congr_fun, apply congr_arg,
apply cone_construction_hom_on_face } }
end
noncomputable
def cone_construction (R : Type*) [comm_ring R] {X : Top} (x0 : X)
(H : continuous_map.homotopy (continuous_map.id X) (continuous_map.const X x0))
: homotopy (homological_complex.id _) (ε R x0) := {
hom := cone_construction_complex_hom R x0 H,
zero' := by { intros i j h, dsimp at h, dsimp [cone_construction_complex_hom],
split_ifs, contradiction, refl },
comm := by {
intros, ext σ : 2, dsimp [homological_complex.id],
cases i; dsimp [ε, ε_hom, ε_map],
{ rw [finsupp.sum_single_index, one_smul],
apply cone_construction_comm_zero,
apply zero_smul },
{ rw [add_zero],
apply cone_construction_comm_higher_deg }
}
}
end
section
universe u
local attribute [instance] category_theory.limits.has_zero_object.has_zero
local attribute [instance]
category_theory.concrete_category.has_coe_to_sort
category_theory.concrete_category.has_coe_to_fun
open category_theory.limits
lemma homology_of_contractible_space (R : Type*) [comm_ring R] (X : Top) (h : contractible_space X)
: ∀ (i : ℕ), 0 < i → is_isomorphic ((singular_homology R i).obj X) 0 :=
begin
intros i h,
apply iso_zero_of_id_eq_zero,
transitivity (homology_functor _ _ i).map
(homological_complex.id ((singular_chain_complex R).obj X)),
symmetry, apply category_theory.functor.map_id,
cases (id_nullhomotopic X) with x0 H,
cases H with H,
rw homology_map_eq_of_homotopy (cone_construction R x0 H),
cases i, { exfalso, exact lt_irrefl _ h },
apply homology_at_ith_index_zero,
ext, simp,
dsimp [ε, ε_hom, ε_map],
refl
end
noncomputable
def singular_chain_complex_basis (R : Type*) [comm_ring R]
: complex_functor_basis (singular_chain_complex R) :=
λ n, { indices := unit,
models := λ _, Top.of (topological_simplex n),
basis_elem := λ _, simplex_to_chain (𝟙 (Top.of (topological_simplex n))) R,
lin_indep := λ X, let g : (Top.of (topological_simplex n) ⟶ X)
→ ((singular_chain_complex R).obj X).X n
:= λ f, ((singular_chain_complex R).map f).f n
(simplex_to_chain (𝟙 (Top.of (topological_simplex n))) R),
e : (Σ (i : unit), Top.of (topological_simplex n) ⟶ X)
≃ (Top.of (topological_simplex n) ⟶ X) :=
equiv.trans (equiv.sigma_equiv_prod unit _)
(equiv.punit_prod _) in
have H : linear_independent R g,
by { have : g = (λ f, simplex_to_chain f R),
{ apply funext, intro f,
transitivity, apply finsupp.map_domain_single,
apply congr_fun, apply congr_arg,
ext, refl },
rw this,
dsimp [simplex_to_chain],
apply free_module_basis_linear_independent },
(linear_independent_equiv' e.symm rfl).mp H,
spanning := λ X, by { transitivity submodule.span R (set.range (λ f, (finsupp.single f (1 : R)))),
{ congr, ext, split,
{ rintro ⟨i, f, h⟩,
existsi f,
rw ← h, symmetry,
transitivity, apply finsupp.map_domain_single,
congr, ext, refl },
{ rintro ⟨f, h⟩,
existsi unit.star, existsi f,
rw ← h,
transitivity, apply finsupp.map_domain_single,
congr, ext, refl } },
apply free_module_basis_spanning } }
/-
Should move this
-/
-- noncomputable
-- def singular_homology0_basis_of_path_component (R : Type*) [comm_ring R] [nontrivial R] (X : Top)
-- : (zeroth_homotopy X) → (singular_homology R 0).obj X
-- := @quotient.lift X ((singular_homology R 0).obj X) (path_setoid X)
-- (λ x, Module.to_homology ⟨(simplex_to_chain (continuous_map.const (topological_simplex 0) x) R : ((singular_chain_complex R).obj X).X 0),
-- by { rw homological_complex.d_from_eq_zero,
-- simp, simp [complex_shape.down] }⟩)
-- (by { intros a b h, obtain ⟨p⟩ := h, dsimp,
-- let f : C(topological_simplex 1, X) := ⟨λ x, p ⟨x.val 0, ⟨x.property.left 0, topological_simplex.coord_le_one _ _ x⟩⟩, _⟩,
-- { refine Module.to_homology_ext (simplex_to_chain f R) _,
-- dsimp [simplex_to_chain],
-- rw singular_chain_complex_differential_desc_deg_0,
-- rw [add_sub, add_comm, ← add_sub],
-- symmetry, convert add_zero _; dsimp [simplex_to_chain];
-- try { rw sub_eq_zero, congr };
-- ext x;
-- have := @unique.eq_default _ topological_simplex.point_unique x;
-- subst this;
-- dsimp [simplex_category.to_Top', simplex_category.to_Top'_map,
-- simplex_category.δ];
-- symmetry,
-- { convert p.target,
-- convert (_ : ({0} : finset (fin 1)).sum topological_simplex.point.val = 1),
-- simp, refl },
-- { exact p.source } },
-- { dsimp, continuity,
-- exact (continuous_apply (0 : fin 2)).comp continuous_subtype_coe } }).
lemma simplex_to_chain_is_basis (R : Type*) [comm_ring R] (n : ℕ) (X : Top)
(σ : Top.of (topological_simplex n) ⟶ X)
: @simplex_to_chain n (Top.to_sSet'.obj X) σ R _
= ((singular_chain_complex_basis R n).get_basis X) ⟨(), σ⟩ :=
begin
intros, dsimp [functor_basis.get_basis, simplex_to_chain], rw basis.mk_apply,
symmetry, refine eq.trans finsupp.map_domain_single _,
congr, apply category.id_comp
end
noncomputable
def singular_homology0_basis (R : Type*) [comm_ring R] [nontrivial R] (X : Top)
: basis (zeroth_homotopy X) R ((singular_homology R 0).obj X) :=
have hrel : (complex_shape.down ℕ).rel 1 0, by { rw complex_shape.down_rel },
have hnone : (complex_shape.down ℕ).next 0 = none,
by { dsimp [complex_shape.next],
apply_with option.choice_eq_none {instances:=ff},
constructor, rintro ⟨i, hi⟩,
simp [complex_shape.down] at hi,
exact hi },
have hnat : homological_complex.d_to ((singular_chain_complex R).obj X) 0
≫ (iso.refl (((singular_chain_complex R).obj X).X 0)).hom
= (homological_complex.X_prev_iso ((singular_chain_complex R).obj X) hrel).hom
≫ ((singular_chain_complex R).obj X).d 1 0,
by { simp [iso.refl], exact homological_complex.d_to_eq _ hrel },
have hs : set.range (quot.mk (path_setoid X).r ∘ λ (x : Σ (i : unit), C(↥(topological_simplex 0), X)), x.snd topological_simplex.point)
= set.univ,
by { rw set.eq_univ_iff_forall, intro x, induction x,
{ rw set.range_comp,
refine set.mem_image_of_mem _ _,
exact ⟨⟨(), continuous_map.const _ x⟩, rfl⟩ },
{ refl } },
let f1 := homology_iso_cokernel 0 hnone ((singular_chain_complex R).obj X),
f2 := cokernel.map_iso (((singular_chain_complex R).obj X).d_to 0)
(((singular_chain_complex R).obj X).d 1 0)
(((singular_chain_complex R).obj X).X_prev_iso hrel)
(iso.refl _) hnat,
f3 := Module.cokernel_iso_range_quotient (((singular_chain_complex R).obj X).d 1 0),
L := (f1 ≪≫ f2 ≪≫ f3).to_linear_equiv,
s : setoid (Σ (i : unit), C(topological_simplex 0, X)) :=
(path_setoid X).comap (λ x, x.snd topological_simplex.point),
e : quotient s ≃ zeroth_homotopy X :=
(setoid.comap_quotient_equiv _ _).trans ((equiv.set_congr hs).trans (equiv.set.univ _))
in by { refine basis.reindex ⟨L.trans (((singular_chain_complex_basis R 0).get_basis X).quotient_basis _ _ _ _ s _).repr⟩ e,
rw linear_map.range_eq_map,
rw ← (singular_chain_complex_basis R 1).spanning,
rw linear_map.map_span,
congr' 1,
ext, split; rintro ⟨i, hi, Hi⟩; subst Hi,
{ obtain ⟨j, σ, Hi⟩ := hi, cases j, subst Hi,
dsimp [singular_chain_complex R, homological_complex.eval],
refine ⟨(⟨(), simplex_category.to_Top'.map (@simplex_category.δ 0 0) ≫ σ⟩,
⟨(), simplex_category.to_Top'.map (@simplex_category.δ 0 1) ≫ σ⟩), _⟩,
rw [← simplex_to_chain_is_basis, ← simplex_to_chain_is_basis],
dsimp [singular_chain_complex_basis, simplex_to_chain],
rw singular_chain_complex_map,
rw (_ : 𝟙 (Top.of (topological_simplex 1)) ≫ σ = σ), swap, exact category.id_comp σ,
refine ⟨⟨_⟩, (singular_chain_complex_differential_desc_deg_0 R σ).symm⟩,
dsimp,
rw [deg_zero_oneth_coface_map_is_vertex_zero, deg_zero_zeroth_coface_map_is_vertex_one],
refine ⟨(@Top.iso_of_homeo (Top.of (topological_simplex 1)) (Top.of unit_interval)
one_simplex_homeo_interval).inv ≫ σ, _, _⟩,
{ simp [Top.iso_of_homeo, one_simplex_homeo_interval],
congr,
ext i, fin_cases i; simp [vertex],
{ symmetry,
apply finset.sum_eq_zero,
intro x, fin_cases x,
simp [simplex_category.mk, simplex_category.const, simplex_category.hom.mk],
exact ne.symm fin.zero_ne_one },
{ split_ifs, cases h,
rw finset.filter_true_of_mem,
{ rw fin.univ_def,
delta simplex_category.mk simplex_category.len,
simp [finset.fin_range, list.fin_range, list.range, list.range_core, list.pmap],
refl },
{ intros x hx, fin_cases x, ext, refl } } },
{ simp [Top.iso_of_homeo, one_simplex_homeo_interval],
congr,
ext i, fin_cases i; simp [vertex],
{ symmetry,
rw fin.univ_def,
delta simplex_category.mk simplex_category.len,
simp [finset.fin_range, list.fin_range, list.range, list.range_core, list.pmap],
transitivity finset.sum {(0 : fin 1)} topological_simplex.point.val,
{ congr }, { simp [topological_simplex.point] } },
{ split_ifs, cases h,
transitivity finset.sum ∅ topological_simplex.point.val,
{ simp },
{ congr } } } },
{ rcases i with ⟨⟨i1, σ⟩, ⟨i2, τ⟩⟩, cases i1, cases i2,
obtain ⟨⟨f, hf1, hf2⟩⟩ := hi,
refine ⟨simplex_to_chain ((@Top.iso_of_homeo (Top.of (topological_simplex 1))
(Top.of unit_interval)
one_simplex_homeo_interval).hom ≫ f) R, _⟩,
refine ⟨⟨(), (@Top.iso_of_homeo (Top.of (topological_simplex 1)) (Top.of unit_interval)
one_simplex_homeo_interval).hom ≫ f, _⟩, _⟩,
{ dsimp [singular_chain_complex_basis, simplex_to_chain],
convert singular_chain_complex_map R 1 _ _ },
{ dsimp [simplex_to_chain],
rw singular_chain_complex_differential_desc_deg_0,
rw [← simplex_to_chain_is_basis, ← simplex_to_chain_is_basis],
congr; ext p;
have : p = topological_simplex.point
:= @unique.eq_default _ topological_simplex.point_unique p; subst this,
{ exact hf1 },
{ refine eq.trans _ hf2,
simp [simplex_category.to_Top', simplex_category.to_Top'_map,
Top.iso_of_homeo, one_simplex_homeo_interval,
topological_simplex.point],
refine congr_arg _ _,
ext, dsimp,
transitivity finset.sum {(0 : fin 1)} topological_simplex.point.val,
{ congr },
{ simp, refl } } } } }.
/-
Move this
-/
lemma setoid.quotient_ker_equiv_range_symm_apply {α : Type*} {β : Type*} (f : α → β)
(x : α) (y : set.range f) (h : f x = y.val)
: (setoid.quotient_ker_equiv_range f).symm y = quot.mk (setoid.ker f).r x :=
begin
dsimp [setoid.quotient_ker_equiv_range, equiv.of_bijective],
have := setoid.quotient_ker_equiv_range._proof_2 f,
refine this.left _,
refine eq.trans (function.surj_inv_eq this.right y) _,
ext, symmetry, exact h
end.
lemma singular_homology0_basis_apply (R : Type*) [comm_ring R] [nontrivial R] (X : Top) (x : X)
: singular_homology0_basis R X (quot.mk (path_setoid X).r x)
= Module.to_homology ⟨simplex_to_chain (continuous_map.const _ x) R, by simp⟩ :=
begin
simp only [singular_homology0_basis, basis.reindex, basis.coe_of_repr, linear_equiv.trans_symm,
category_theory.iso.to_linear_equiv_symm_apply,
linear_equiv.trans_apply,
finsupp.dom_lcongr_symm,
equiv.symm_trans_apply,
category_theory.iso.trans_inv,
category_theory.iso.refl_inv,
basis.repr_symm_apply,
function.comp_app,
one_smul,
finsupp.total_single,
category_theory.category.assoc,
finsupp.dom_lcongr_single,
Module.coe_comp, homology_iso_cokernel,
Module.cokernel_iso_range_quotient],
rw [← category_theory.comp_apply (iso.inv _) (iso.inv _), ← category_theory.iso.trans_inv],
rw cokernel_map_iso_trans_iso_colimit_cocone,
simp only [],
delta cokernel.desc,
rw ← category_theory.comp_apply,
rw colimit_iso_colimit_cocone_desc,
simp [is_colimit.precompose_hom_equiv],
delta cokernel_cofork.of_π,
dsimp [cofork.of_π],
dsimp [cocones.precompose_equivalence, cocones.precompose],
simp [Module.cokernel_is_colimit, cofork.is_colimit.mk, Module.cokernel_cocone],
-- dsimp [cofork.π],
delta cofork.π,
simp only [nat_trans.comp_app, parallel_pair.ext, nat_iso.of_components],
simp only [quot.congr.equations._eqn_1,
equiv.subtype_equiv_symm,
equiv.symm_trans_apply,
quotient.congr_right.equations._eqn_1,
equiv.coe_fn_symm_mk,
setoid.comap_quotient_equiv.equations._eqn_1,
id.def,
equiv.set.univ.equations._eqn_1,
equiv.set_congr.equations._eqn_1,
equiv.refl_symm,
equiv.subtype_equiv_prop.equations._eqn_1,
subtype.coe_mk,
equiv.subtype_equiv_apply,
quot.congr_right.equations._eqn_1,
equiv.coe_refl,
quot.map],
rw @setoid.quotient_ker_equiv_range_symm_apply (Σ (i : unit), C(topological_simplex 0, X)) _ _
⟨(), continuous_map.const _ x⟩,
swap, { refl },
simp only [basis.mk_apply, basis.quotient_basis.equations._eqn_1, submodule.liftq_apply,
function.comp_app, Module.coe_comp],
rw ← simplex_to_chain_is_basis,
dsimp [iso.refl],
have hnone : (complex_shape.down ℕ).next 0 = none,
{ simp },
transitivity Module.as_hom_right (@is_linear_map.mk' R (linear_map.ker (((singular_chain_complex R).obj X).d_from 0))
(((singular_chain_complex R).obj X).homology 0)
_ _ _ _ _
Module.to_homology
(Module.to_homology.homomorphism _ 0))
(Module.to_cycles_terminal_hom hnone
(simplex_to_chain (continuous_map.const (topological_simplex 0) x) R
: ((singular_chain_complex R).obj X).X 0)),
swap, { refl },
rw [← category_theory.comp_apply],
refine congr_fun _ _,
refine congr_arg _ _,
transitivity cokernel.π (((singular_chain_complex R).obj X).d_to 0) ≫
(homology_iso_cokernel 0 hnone ((singular_chain_complex R).obj X)).inv,
{ simp [homology_iso_cokernel] },
exact Module.homology_iso_cokernel_spec hnone,
end.
lemma singular_homology0_map_matrix (R : Type*) [comm_ring R] [nontrivial R]
{X Y : Top} (f : X ⟶ Y) (x : X)
: (singular_homology R 0).map f (singular_homology0_basis R X (quot.mk (path_setoid X).r x))
= singular_homology0_basis R Y (quot.mk (path_setoid Y).r (f x)) :=
begin
rw [singular_homology0_basis_apply, singular_homology0_basis_apply],
dsimp [singular_homology],
delta Module.to_homology,
rw ← category_theory.comp_apply,
simp,
refine congr_arg _ _,
refine eq.trans (Module.cycles_map_to_cycles _ _) _,
congr,
refine eq.trans (singular_chain_complex_map _ _ _ _) _,
delta simplex_to_chain,
congr
end
lemma prod_of_contractible_contractible (X Y : Type*) [topological_space X] [topological_space Y]
(hX : contractible_space X) (hY : contractible_space Y) : contractible_space (X × Y) :=
begin
rw contractible_iff_id_nullhomotopic at *,
rcases hX with ⟨x0, ⟨H_X⟩⟩, rcases hY with ⟨y0, ⟨H_Y⟩⟩,
existsi (x0, y0),
have : continuous_map.homotopic _ _ :=
⟨continuous_map.homotopy.prod ((continuous_map.homotopy.refl ⟨@prod.fst X Y⟩).hcomp H_X)
((continuous_map.homotopy.refl ⟨@prod.snd X Y⟩).hcomp H_Y)⟩,
refine eq.mp _ this,
congr; ext; cases a; refl
end
def inclusion_at_t_nat_trans (t : unit_interval) : category_theory.functor.id Top ⟶ cylinder := {
app := λ X, ⟨λ x, (t, x), by continuity⟩
}
lemma inclusion_at_t_nat_trans_on_chain (R : Type*) [comm_ring R]
(t : unit_interval) (n : ℕ)
: ((singular_chain_complex R).map
((inclusion_at_t_nat_trans t).app
((singular_chain_complex_basis R n).models unit.star))).f n
((singular_chain_complex_basis R n).basis_elem unit.star)
= simplex_to_chain ⟨prod.mk t, by continuity⟩ R :=
begin
delta singular_chain_complex, delta free_complex_on_sset,
simp,
delta singular_chain_complex_basis,
simp [simplex_to_chain],
refl
end
lemma inclusion_at_0_nat_trans_app_comp_homotopy (R : Type*) [comm_ring R]
{X Y : Top} {f g : X ⟶ Y} (H : continuous_map.homotopy f g)
: (whisker_right (inclusion_at_t_nat_trans 0) (singular_chain_complex R)).app X
≫ (singular_chain_complex R).map H.to_continuous_map
= (singular_chain_complex R).map f :=
eq.trans ((singular_chain_complex R).map_comp ((inclusion_at_t_nat_trans 0).app X)
H.to_continuous_map).symm
(congr_arg (@category_theory.functor.map _ _ _ _ (singular_chain_complex R) X Y)
(continuous_map.ext H.map_zero_left'))
lemma inclusion_at_1_nat_trans_app_comp_homotopy (R : Type*) [comm_ring R]
{X Y : Top} {f g : X ⟶ Y} (H : continuous_map.homotopy f g)
: (whisker_right (inclusion_at_t_nat_trans 1) (singular_chain_complex R)).app X
≫ (singular_chain_complex R).map H.to_continuous_map
= (singular_chain_complex R).map g :=
eq.trans ((singular_chain_complex R).map_comp ((inclusion_at_t_nat_trans 1).app X)
H.to_continuous_map).symm
(congr_arg (@category_theory.functor.map _ _ _ _ (singular_chain_complex R) X Y)
(continuous_map.ext H.map_one_left'))
noncomputable
def singular_homology.chain_homotopy_of_homotopy (R : Type*) [comm_ring R]
{X Y : Top} {f g : X ⟶ Y} (H : continuous_map.homotopy f g)
: homotopy ((singular_chain_complex R).map f) ((singular_chain_complex R).map g) :=
have h : whisker_right (whisker_right (inclusion_at_t_nat_trans 0) (singular_chain_complex R))
(homology_functor (Module R) (complex_shape.down ℕ) 0) =
whisker_right (whisker_right (inclusion_at_t_nat_trans 1) (singular_chain_complex R))
(homology_functor (Module R) (complex_shape.down ℕ) 0),
by { apply functor_basis.homology_ext (singular_chain_complex_basis R 0),
intro i, cases i,
refine exists.intro (simplex_to_chain _ R) _,
{ refine ⟨(λ p, (one_simplex_homeo_interval.to_fun p, topological_simplex.point)), _⟩,
continuity,
change continuous one_simplex_homeo_interval.to_fun,
exact one_simplex_homeo_interval.continuous_to_fun },
dsimp [simplex_to_chain],
rw singular_chain_complex_differential_desc_deg_0,
rw [inclusion_at_t_nat_trans_on_chain, inclusion_at_t_nat_trans_on_chain],
delta simplex_category.to_Top',
simp,
rw add_sub_left_comm,
refine eq.trans (add_zero _).symm _,
congr,
{ ext, simp [simplex_category.to_Top'_map],
transitivity ((∅ : finset (fin 1)).sum (λ i, x.val i)),
simp, refl,
simp, congr,
apply @unique.eq_default _ topological_simplex.point_unique },
{ symmetry, rw sub_eq_zero, congr,
ext : 3,
{ simp [simplex_category.to_Top'_map],
refine eq.trans x.property.right.symm _,
dsimp [one_simplex_homeo_interval],
congr },
{ simp, apply @unique.eq_default _ topological_simplex.point_unique } } },
let s := (lift_nat_trans_unique
(singular_chain_complex_basis R)
(cylinder ⋙ singular_chain_complex R)
(λ n hn,
have H : ∀ k, contractible_space (unit_interval × topological_simplex k),
by { intro k, apply prod_of_contractible_contractible,
{ apply convex.contractible_space,
apply @convex_Icc ℝ ℝ _ _ _ _ 0 1,
existsi (0 : ℝ), simp },
{ apply convex.contractible_space,
{ exact convex_std_simplex ℝ _ },
{ exact ⟨(vertex k 1).val, (vertex k 1).property⟩ } } },
let H' (k : ℕ) (hk : k > 0) (i : (singular_chain_complex_basis R k).indices) :=
homology_of_contractible_space R (Top.of (unit_interval × topological_simplex k))
(H k) n hn
in ⟨H' n hn, H' (n + 1) (nat.zero_lt_succ n)⟩)
(whisker_right (inclusion_at_t_nat_trans 0) (singular_chain_complex R))
(whisker_right (inclusion_at_t_nat_trans 1) (singular_chain_complex R))
h).to_chain_htpy X,
s' := s.comp_right ((singular_chain_complex R).map H.to_continuous_map)
in ((homotopy.of_eq (inclusion_at_0_nat_trans_app_comp_homotopy R H).symm).trans s').trans
(homotopy.of_eq (inclusion_at_1_nat_trans_app_comp_homotopy R H))
lemma singular_homology.chain_homotopy_of_homotopy_natural (R : Type*) [comm_ring R]
{A X B Y : Top} (i : A ⟶ X) (j : B ⟶ Y)
(f' g' : A ⟶ B) (f g : X ⟶ Y)
(w1 : f' ≫ j = i ≫ f) (w2 : g' ≫ j = i ≫ g)
(H' : continuous_map.homotopy f' g') (H : continuous_map.homotopy f g)
(h : cylinder.map i ≫ H.to_continuous_map = H'.to_continuous_map ≫ j)
: homotopy.comp_right (singular_homology.chain_homotopy_of_homotopy R H')
((singular_chain_complex R).map j)
= (homotopy.of_eq (eq.trans ((singular_chain_complex R).map_comp f' j).symm
(eq.trans (congr_arg _ w1)
((singular_chain_complex R).map_comp i f)))).trans
((homotopy.comp_left (singular_homology.chain_homotopy_of_homotopy R H)
((singular_chain_complex R).map i)).trans
(homotopy.of_eq (eq.trans ((singular_chain_complex R).map_comp i g).symm
(eq.trans (congr_arg _ w2.symm)
((singular_chain_complex R).map_comp g' j))))) :=
begin
ext p q : 3, simp [singular_homology.chain_homotopy_of_homotopy],
by_cases h' : p + 1 = q,
{ rw [← homological_complex.comp_f, ← category_theory.functor.map_comp],
rw ← h,
rw [category_theory.functor.map_comp, homological_complex.comp_f, ← category.assoc,
← category_theory.functor.comp_map],
rw ← (lift_nat_trans_unique (singular_chain_complex_basis R)
(cylinder ⋙ singular_chain_complex R) _ _ _ _).naturality,
apply category.assoc,
exact h' },
{ rw ← complex_shape.down_rel _ q p at h', rw [homotopy.zero _ _ _ h', homotopy.zero _ _ _ h'],
simp }
end
lemma singular_homology.homotopy_invariant (R : Type*) [comm_ring R]
(n : ℕ) {X Y : Top} {f g : X ⟶ Y} (H : continuous_map.homotopy f g)
: (singular_homology R n).map f = (singular_homology R n).map g :=
homology_map_eq_of_homotopy (singular_homology.chain_homotopy_of_homotopy R H) n
lemma singular_homology_of_pair.homotopy_invariant (R : Type*) [comm_ring R]
(n : ℕ) (A X B Y : Top) (i : A ⟶ X) (j : B ⟶ Y)
(f' g' : A ⟶ B) (f g : X ⟶ Y)
(w1 : f' ≫ j = i ≫ f) (w2 : g' ≫ j = i ≫ g)
(H' : continuous_map.homotopy f' g') (H : continuous_map.homotopy f g)
(h : cylinder.map i ≫ H.to_continuous_map = H'.to_continuous_map ≫ j)
: (singular_homology_of_pair R n).map (arrow.hom_mk w1 : arrow.mk i ⟶ arrow.mk j)
= (singular_homology_of_pair R n).map (arrow.hom_mk w2 : arrow.mk i ⟶ arrow.mk j) :=
homology_map_eq_of_homotopy
(chain_homotopy_on_coker_of_compatible_chain_homotopies
((singular_chain_complex R).map i) ((singular_chain_complex R).map j)
((singular_chain_complex R).map f') ((singular_chain_complex R).map g')
((singular_chain_complex R).map f) ((singular_chain_complex R).map g)
(eq.trans ((singular_chain_complex R).map_comp f' j).symm
(eq.trans (congr_arg _ w1)
((singular_chain_complex R).map_comp i f)))
(eq.trans ((singular_chain_complex R).map_comp g' j).symm
(eq.trans (congr_arg _ w2)
((singular_chain_complex R).map_comp i g)))
(singular_homology.chain_homotopy_of_homotopy R H')
(singular_homology.chain_homotopy_of_homotopy R H)
(singular_homology.chain_homotopy_of_homotopy_natural R i j f' g' f g w1 w2 H' H h))
n
end |
From aneris.aneris_lang Require Import lang resources.
From stdpp Require Import gmap.
From aneris.prelude Require Import misc.
From aneris.examples.ccddb.spec Require Import base.
From aneris.examples.ccddb.model Require Import model_update_prelude model_lst
model_gst model_update_lhst model_update_lst.
Section Gst_update.
Context `{!anerisG Mdl Σ, !DB_params}.
(** Global and local state coherence *)
Lemma DBM_gs_ls_coh (i: nat) (gs : Gst) (ls : Lst) :
i < length DB_addresses →
DBM_Gst_valid gs →
DBM_Lst_valid i ls →
gs.(Gst_hst) !! i = Some ls.(Lst_hst) →
dom ls.(Lst_mem) ⊆ dom gs.(Gst_mem) ∧
∀ k v, k ∈ DB_keys → ls.(Lst_mem) !! k = Some v →
∃ a h, gs.(Gst_mem) !! k = Some h ∧ a ∈ h ∧ a.(we_val) = v.
Proof.
intros.
split.
{ erewrite DBM_GstValid_dom; last done; by eapply DBM_LSTV_dom_keys. }
intros k v Hk Hkv.
eapply DBM_LSTV_vals_Some in Hkv as [Hv1 Hkv2]; eauto.
set (Observe_lhst (restrict_key k (Lst_hst ls))) as e in *.
apply compute_maximals_correct in Hkv2 as ([He Hem2]%elem_of_filter & Hem').
eapply DBM_GV_hst_in_mem in Hem2 as (h & Hh & Heh);
eauto using elem_of_list_lookup_2.
simplify_eq/=.
eexists (erase e), h; split_and!;
[by rewrite -He|done|by rewrite -erase_val].
Qed.
Lemma DBM_mem_dom_update {A: Type} k (v : A) (d: gmap Key A) :
k ∈ DB_keys →
dom d = DB_keys →
dom (<[k:=v]> d) = DB_keys.
Proof. by set_solver. Qed.
Lemma DBM_gs_hst_valid_update gs i s m:
DBM_Gst_valid gs →
DBM_lhst_valid i s →
DBM_gs_hst_valid
{| Gst_mem := m; Gst_hst := <[i:=s]> (Gst_hst gs) |}.
Proof.
intros Hgv Hsv j sj Hgs; simpl.
destruct (decide (j = i)) as [-> | ].
- rewrite list_lookup_insert in Hgs.
+ by simplify_eq.
+ pose proof (DBM_GV_hst_size Hgv).
epose proof DBM_LHV_bound_at.
erewrite (DBM_GV_hst_size Hgv); eauto.
- rewrite list_lookup_insert_ne in Hgs; last done.
eapply DBM_GV_hst_lst_valid; eauto.
Qed.
Lemma DBM_gs_hst_size_update gs i s m:
DBM_Gst_valid gs →
DBM_gs_hst_size
{| Gst_mem := m; Gst_hst := <[i:=s]> (Gst_hst gs) |}.
Proof.
intros Hgv. rewrite /DBM_gs_hst_size //=.
rewrite insert_length.
by eapply DBM_GV_hst_size.
Qed.
Lemma DBM_system_write_update_gst
(k : Key) (v : val) (i : nat) (gs : Gst) (ls : Lst) mk :
k ∈ DB_keys →
DBM_Lst_valid i ls →
DBM_Gst_valid gs →
gs.(Gst_hst) !! i = Some ls.(Lst_hst) →
gs.(Gst_mem) !! k = Some mk →
let t := incr_time ls.(Lst_time) i in
let e := ApplyEvent k v t i (S (size ls.(Lst_hst))) in
let s := ls.(Lst_hst) ∪ {[ e ]} in
let m := (<[ k := mk ∪ {[erase e]} ]> gs.(Gst_mem)) in
let Ss := <[i := s]> gs.(Gst_hst) in
DBM_Gst_valid (GST m Ss).
Proof.
intros Hk Hvl Hvg Hgs Hgm t e s m Ss.
pose proof (DBM_LSTV_at Hvl) as Hi.
pose proof DBM_LSTV_hst_valid Hvl as Hvlh.
assert (update_condition i e (Lst_time ls)) as Hcond.
eapply update_condition_write; eauto.
pose proof Hcond as
(Hi' & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').
split.
- by eapply DBM_mem_dom_update; eauto; eapply DBM_GV_dom.
- eapply DBM_gs_hst_size_update; eauto.
- eapply DBM_gs_hst_valid_update; eauto.
rewrite /DBM_lst_hst_valid in Hvlh.
eapply DBM_lhst_update.
+ eauto.
+ eauto.
+ eauto.
+ eauto using DBM_Lst_valid_time_le; eauto.
+ rewrite (DBM_LSTV_time Hvl (ae_orig e) Heorig).
symmetry.
pose proof (lsec_lsup_length (ae_orig e)); eauto.
+ intros ? j0 Hj0.
rewrite (DBM_LSTV_time Hvl j0 Hj0).
symmetry.
pose proof (lsec_lsup_length (ae_orig e)); eauto.
+ intros j0 Hj0.
rewrite (DBM_LSTV_time Hvl j0 Hj0).
pose proof (lsec_lsup_length
i j0 (Lst_hst ls) Hvlh Hj0)
as Hll. rewrite Hll.
eauto with lia.
- intros s1 Hs1 e1 He1. simpl in Hs1.
subst Ss. apply elem_of_list_lookup in Hs1 as (j & Hs1).
destruct (decide (i = j)) as [<-|Hneqij].
+ rewrite list_lookup_insert in Hs1. inversion Hs1. subst s1.
clear Hs1. apply elem_of_union in He1 as [He1|?%elem_of_singleton_1].
* destruct (λ H, DBM_GV_hst_in_mem Hvg (Lst_hst ls) H e1)
as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.
destruct (decide (k = ae_key e1)) as [->|Hneq].
** subst m; setoid_rewrite lookup_insert.
exists (mk ∪ {[erase e]}); split; first done.
rewrite Hgm // in Hh'. set_solver.
** subst m; setoid_rewrite lookup_insert_ne; last done.
eexists; eauto.
* simpl. subst e1 m.
assert (k = ae_key e) as <- by eauto.
setoid_rewrite lookup_insert.
exists (mk ∪ {[erase e]}); split; first done.
set_solver.
* rewrite (DBM_GV_hst_size Hvg) //.
+ rewrite list_lookup_insert_ne in Hs1.
destruct (λ H, DBM_GV_hst_in_mem Hvg s1 H e1)
as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.
destruct (decide (k = ae_key e1)) as [->|Hneq]; simpl.
* subst m.
setoid_rewrite lookup_insert.
rewrite Hh' in Hgm.
eexists _. split_and!; eauto with set_solver.
* exists h'; split_and!; eauto.
by rewrite lookup_insert_ne; last done.
* done.
- intros a h Hm Hah.
subst m Ss s. simpl in Hm. simpl.
destruct (decide ((we_key a) = k)) as [ <- | Hneq0 ].
+ rewrite lookup_insert in Hm.
simplify_eq.
apply elem_of_union in Hah as[ Hamk| Ha1%elem_of_singleton_1].
* destruct (DBM_GV_mem_in_hst Hvg a mk Hgm Hamk)
as (sa & saa & ea & Hsa & Hsaa & Hea & Hear).
destruct (decide (i = we_orig a)) as [Heq|Hneq].
** eexists (Lst_hst ls ∪ {[e]}), (saa ∪ {[e]}), ea.
split_and!.
*** subst; rewrite list_lookup_insert; first done.
rewrite (DBM_GV_hst_size Hvg) //.
*** subst; rewrite //. set_solver.
*** set_solver.
*** done.
** eexists _, _, _.
split_and!; eauto.
by rewrite list_lookup_insert_ne.
* eexists _, _, e.
split_and!; eauto.
** rewrite Ha1. rewrite list_lookup_insert //=.
rewrite (DBM_GV_hst_size Hvg) //.
** rewrite DBM_lsec_union DBM_lsec_singleton_in.
*** set_solver.
*** by rewrite Ha1.
+ rewrite lookup_insert_ne //= in Hm.
destruct (decide (i = we_orig a)) as [Heq|Hneq].
* assert
(∃ (s0 si : gset apply_event) (e0 : apply_event),
Gst_hst gs !! we_orig a =
Some s0 ∧ DBM_lsec (we_orig a) s0 = si
∧ e0 ∈ si ∧ erase e0 = a)
as (s0 & si & e0 & Hs0 & Hs1 & Hs2 & Hs3)
by by eapply DBM_GV_mem_in_hst.
rewrite -!Heq. rewrite -!Heq in Hs0 Hs1.
rewrite list_lookup_insert.
** do 3 eexists. repeat split; eauto.
rewrite /s0. set_solver.
** eapply lookup_lt_is_Some_1; eauto.
* rewrite //=.
simpl in Hm.
rewrite list_lookup_insert_ne; eauto.
eapply DBM_GV_mem_in_hst; eauto.
- intros k1 h1 a1 Hh1 Ha1.
rewrite /m //= in Hh1.
destruct (decide (k1 = k)) as [-> | ].
+ rewrite lookup_insert //= in Hh1.
simplify_eq.
apply elem_of_union in Ha1 as [| ?%elem_of_singleton_1];
[|set_solver].
eapply DBM_GV_mem_elements_key; eauto.
+ rewrite lookup_insert_ne //= in Hh1.
eapply DBM_GV_mem_elements_key; eauto.
Qed.
Lemma DBM_system_apply_update_gst
(i : nat) (gs : Gst) (ls : Lst)
(a : write_event) (h: gset write_event) :
DBM_Gst_valid gs →
DBM_Lst_valid i ls →
gs.(Gst_hst) !! i = Some ls.(Lst_hst) →
gs.(Gst_mem) !! a.(we_key) = Some h →
a ∈ h →
a.(we_orig) ≠ i →
let t := incr_time ls.(Lst_time) a.(we_orig) in
let e := ApplyEvent (we_key a) (we_val a) (we_time a) (we_orig a)
(S (size ls.(Lst_hst))) in
let s := ls.(Lst_hst) ∪ {[ e ]} in
let d := (<[ a.(we_key) := a.(we_val) ]> ls.(Lst_mem)) in
let Ss := (<[i := s]> gs.(Gst_hst)) in
update_condition i e ls.(Lst_time) →
DBM_Gst_valid (GST gs.(Gst_mem) Ss).
Proof.
intros Hvg Hvl Hgsi ?????????.
split.
- apply (DBM_GV_dom Hvg); eauto.
- eapply DBM_gs_hst_size_update; eauto.
- eapply DBM_gs_hst_valid_update; eauto.
assert (DBM_Lst_valid i {|Lst_mem := d; Lst_time := t; Lst_hst := s|})
as Hvlst.
{ apply (DBM_lst_update e i ls Hvl); eauto. }
eapply (DBM_LSTV_hst_valid Hvlst).
- intros s1 Hs1 e1 He1. simpl in Hs1.
subst Ss. apply elem_of_list_lookup in Hs1 as (j & Hs1).
destruct (decide (i = j)) as [<-|Hneqij].
+ rewrite list_lookup_insert in Hs1. inversion Hs1. subst s1.
clear Hs1. apply elem_of_union in He1 as [He1|?%elem_of_singleton_1].
* destruct (λ H, DBM_GV_hst_in_mem Hvg (Lst_hst ls) H e1)
as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.
* simpl. subst e1.
assert (a = erase e) as <- by by destruct a.
eauto.
* rewrite (DBM_GV_hst_size Hvg) //.
by eapply DBM_LSTV_at.
+ rewrite list_lookup_insert_ne in Hs1.
destruct (λ H, DBM_GV_hst_in_mem Hvg s1 H e1)
as (h' & Hh' & He''h'); eauto using elem_of_list_lookup_2.
done.
- intros a1 h1 Hm Ha1.
destruct (decide (i = we_orig a1)) as [Heq|Hneq].
+ assert
(∃ (s0 si : gset apply_event) (e0 : apply_event),
Gst_hst gs !! we_orig a1 =
Some s0 ∧ DBM_lsec (we_orig a1) s0 = si
∧ e0 ∈ si ∧ erase e0 = a1)
as (s0 & si & e0 & Hs0 & Hs1 & Hs2 & Hs3)
by by eapply DBM_GV_mem_in_hst.
rewrite -!Heq. rewrite -!Heq in Hs0 Hs1.
rewrite list_lookup_insert.
* do 3 eexists. repeat split; eauto.
rewrite /s. set_solver.
* eapply lookup_lt_is_Some_1; eauto.
+ rewrite /Ss //=.
simpl in Hm.
rewrite list_lookup_insert_ne; eauto.
eapply DBM_GV_mem_in_hst; eauto.
- rewrite /DBM_gs_gmem_elements_key /=.
eapply DBM_GV_mem_elements_key; eauto.
Qed.
End Gst_update.
|
lemma content_dvd_coeff [simp]: "content p dvd coeff p n" |
example : mynat → mynat :=
begin
intro n, exact 3*n+2,
end |
The best hockey players on their high school team , Ross and the Patrick brothers were invited to play occasional games for local league teams in Montreal . Ross first played in an organized league in 1905 , joining Montreal Westmount of the Canadian Amateur Hockey League ( CAHL ) , the top amateur league in Canada . He scored ten goals in eight games during the season . His opponents regarded him as one of the best rushing defencemen . Most defenders at the time either shot the puck down the ice or passed to a forward ; in contrast , Ross skated up the ice , taking the puck into the offensive zone . Later that year , wishing to pursue a career in banking , he moved to Brandon , Manitoba , where he joined the Brandon Elks of the Manitoba Hockey League , the senior league in the province . In 1906 , his first season , he scored six goals in seven games while he recorded six goals in ten games in 1907 . Around this time , the Kenora Thistles , the Manitoba League champions , wanted to strengthen their team for the Stanley Cup challenge against the Montreal Wanderers in Montreal during January 1907 . They paid Ross $ 1 @,@ 000 to play both matches , a common practice at the time , and the Thistles won the Cup . While failing to score , Ross started many plays and proved an important part of the team . Although he played for the opposing team , he received a good reception from the Montreal crowd . Ross did not play for the Thistles when the two teams played for the Cup again in March , which the Wanderers won to take back the Cup .
|
[GOAL]
n : ℕ
src✝ : Mul (Fin n) := inferInstanceAs (Mul (Fin n))
x✝² x✝¹ x✝ : Fin n
a : ℕ
ha : a < n
b : ℕ
hb : b < n
c : ℕ
hc : c < n
⊢ a * b * c ≡ a * (b * c) [MOD n]
[PROOFSTEP]
rw [mul_assoc]
[GOAL]
n : ℕ
x✝² x✝¹ x✝ : Fin n
a : ℕ
ha : a < n
b : ℕ
hb : b < n
c : ℕ
hc : c < n
⊢ a * (b + c) ≡ a * b + a * c [MOD n]
[PROOFSTEP]
rw [mul_add]
[GOAL]
n : ℕ
src✝¹ : AddCommSemigroup (Fin n) := addCommSemigroup n
src✝ : CommSemigroup (Fin n) := instCommSemigroup n
a b c : Fin n
⊢ (a + b) * c = a * c + b * c
[PROOFSTEP]
rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]
[GOAL]
⊢ Repr (ZMod 0)
[PROOFSTEP]
dsimp [ZMod]
[GOAL]
⊢ Repr ℤ
[PROOFSTEP]
infer_instance
[GOAL]
n : ℕ
⊢ Repr (ZMod (n + 1))
[PROOFSTEP]
dsimp [ZMod]
[GOAL]
n : ℕ
⊢ Repr (Fin (n + 1))
[PROOFSTEP]
infer_instance
[GOAL]
n : ℕ
inst✝ : Fintype (ZMod n)
⊢ Fintype.card (ZMod n) = n
[PROOFSTEP]
cases n with
| zero => exact (not_finite (ZMod 0)).elim
| succ n => convert Fintype.card_fin (n + 1) using 2
[GOAL]
n : ℕ
inst✝ : Fintype (ZMod n)
⊢ Fintype.card (ZMod n) = n
[PROOFSTEP]
cases n with
| zero => exact (not_finite (ZMod 0)).elim
| succ n => convert Fintype.card_fin (n + 1) using 2
[GOAL]
case zero
inst✝ : Fintype (ZMod Nat.zero)
⊢ Fintype.card (ZMod Nat.zero) = Nat.zero
[PROOFSTEP]
| zero => exact (not_finite (ZMod 0)).elim
[GOAL]
case zero
inst✝ : Fintype (ZMod Nat.zero)
⊢ Fintype.card (ZMod Nat.zero) = Nat.zero
[PROOFSTEP]
exact (not_finite (ZMod 0)).elim
[GOAL]
case succ
n : ℕ
inst✝ : Fintype (ZMod (Nat.succ n))
⊢ Fintype.card (ZMod (Nat.succ n)) = Nat.succ n
[PROOFSTEP]
| succ n => convert Fintype.card_fin (n + 1) using 2
[GOAL]
case succ
n : ℕ
inst✝ : Fintype (ZMod (Nat.succ n))
⊢ Fintype.card (ZMod (Nat.succ n)) = Nat.succ n
[PROOFSTEP]
convert Fintype.card_fin (n + 1) using 2
|
module Main
import Package.IpkgAst
import Package.IkanAssets
import System
ikanSettingsDir : String
ikanSettingsDir = "~/.idris-ikan"
echo : String -> IO ()
echo = putStrLn
echo0 : String -> IO ()
echo0 = putStr
rawcmd : String -> IO ()
rawcmd c = do system c ; pure ()
ikanInit : IO ()
ikanInit = do
r<-createDir ikanSettingsDir
case r of
(Left l)=> echo "error ikanInit"
(Right x)=> pure ()
cmds : List (String,String,IO ())
cmds = [("np","create new template project ",do
echo "project name ?"
fn<-getLine
r<-createDir fn
case r of
(Left l)=> echo "error !"
(Right x)=> do
writeFile (fn++"/"++ fn++".ipkg") (ipkgPackage fn)
writeFile (fn++"/.gitignore") (IkanAssets.flGitignore)
echo $ "ok,project created : "++ fn
echo "create main.idr? n for not "
x<-getLine
if (x=="n") then pure () else do writeFile (fn++"/Main.idr") IkanAssets.flMain;pure ()
) ,
("iinit","initialize ikan package manager(write files to "++ikanSettingsDir++")",do
r<-dirOpen ikanSettingsDir
case r of
(Left l)=> ikanInit
(Right r)=> echo "dir ok!"
),
("clr","clean this project,delete all .ibc file",do
rawcmd "rm **/*.ibc"
echo "ok,project cleaned"
--rawcmd "idris clean ipkg"
),
("nf","new file/module",
do
echo0 "new file/module name:"
s<-getLine
writeFile (s++".idr") $ concat ["module ",s," \n"]
pure ()
)
]
showHelp : IO ()
showHelp = do
let lns=map (\(c,desc,_) => concat [" ",c," : ",desc," \n"]) cmds
echo $ "showing help : "
putStrLn $ "avail commands : \n" ++ (foldl1 (\x,y=>x++y) lns)
listDirs : String->IO ()
listDirs s = do
d<-dirOpen s
case d of
Left l => echo "failed dirOpen "
(Right d1)=> do
echo $ "dirOpen "++s ++" ok !"
nextdir<-dirEntry d1
case nextdir of
(Left l)=> do print l; echo "dirEntry failed"
(Right r)=> do
echo $ "dir dirEntry " ++ s ++ " ok!"
listDirs r
main : IO ()
main = do
-- let
echo "welcome to ikan , a idris package manager in idris ! "
-- listDirs "src"
args<-getArgs
case args of
(_ :: x :: xs) => doAct x
y => do
showHelp
echo0 "input cmd:"
ln<-getLine
doAct ln
pure ()
where
doAct : String->IO ()
doAct = (\x => let act = find (\cmd=> let (nm,_,_)=cmd in nm==x) cmds
in (case act of
Nothing=> do echo "cmd not found"
showHelp
Just (_, _,io)=> io))
|
function val= froNormMatn(x,y)
val =sqrt(sum( (x(:)-y(:)).^2)); |
#include "FileGenerator.h"
#include "JSMin.h"
#include <boost/filesystem.hpp>
#include <iosfwd>
bool FileGenerator::DoJSExtensionGeneration(
string input, string output, const std::string& name)
{
// There should be no '"' characters //
// Create folders
try {
boost::filesystem::create_directories(boost::filesystem::path(output).parent_path());
// If the output exists we set it to be writeable again
if(boost::filesystem::exists(output)) {
// Set file to writeable. Deleting a read only file doesn't seem to work on windows
{
using namespace boost::filesystem;
permissions(output, add_perms | owner_write | others_write | group_write);
}
}
} catch(const boost::filesystem::filesystem_error& e) {
std::cout << "Error occurred while making sure output target is fine: " << e.what()
<< std::endl;
}
// Write stuff over the file //
ofstream writer(output);
ifstream reader(input);
if(!reader.is_open()) {
cout << "Failed to open input file:" << input << endl;
return false;
}
if(!writer.is_open()) {
cout << "Failed to open output file:" << output << endl;
return false;
}
const auto lastSlash = input.find_last_of('/') + 1;
const auto lastDot = input.find_last_of('.') - 1;
const auto inputName = input.substr(lastSlash, lastDot - lastSlash + 1);
// Write the heading stuff //
writer << "#pragma once" << endl << endl;
writer << "// Generated by Leviathan FileGenerator for " << name
<< ", using JSMin "
"Copyright (c) 2002 Douglas Crockford //"
<< endl;
writer << "// From: " << input << " //" << endl;
writer << "namespace " << name << "{" << endl;
writer << "const char* " << inputName << "Str = \"\"" << endl;
// Read from the input and put to output //
std::stringstream fileText;
fileText << reader.rdbuf();
reader.close();
// The file is now read, minimize it //
JSMin minifier;
minifier.SetInput(fileText.str());
try {
minifier.jsmin();
} catch(...) {
// Probably is bad //
cout << "Parsing error" << endl;
return false;
}
stringstream minstr(minifier.GetOutputString());
// stringstream minstr(filetext);
while(minstr.good()) {
std::string line;
std::getline(minstr, line, '\n');
if(line.size() == 0)
continue;
writer << "\"";
// Quite an ugly hack to remove all quotes //
for(size_t i = 0; i < line.length(); i++) {
if(line[i] == '"') {
writer << "\\\"";
continue;
}
writer << line[i];
}
// Write the final line //
writer << "\\n\"" << endl;
}
writer << endl << ";";
writer << endl << "}";
writer.close();
// Set file to read-only after we're done with it
{
using namespace boost::filesystem;
permissions(output, remove_perms | owner_write | others_write | group_write);
}
cout << "Done generating file: " << output << endl;
return true;
}
|
# provides a text summary of a word, potentially missing
summarise_word <- function(word, is_missing) {
if(nchar(word) == 0) {
return("")
}
if(is_missing) {
return(paste0("Word \"", word, "\" not found in norms."))
}
else {
return("")
}
}
# Provides a text summary of list of words
summarise_words <- function(words, missing) {
message = ""
if (length(words) == 0) {
return(message)
}
if (length(missing) > 0) {
message = paste0(message, prettyNum(length(missing)), " concepts not found (including \"", missing[1], "\"). ")
}
message = paste0(prettyNum(length(words)), " unique words entered. ", message)
return(message)
}
# Provides a text summary of a list of words, with a min/max limit
summarise_words_count_limit <- function(words, missing, min = -Inf, max = Inf, clip_max = FALSE) {
message = summarise_words(words, missing)
if (length(words) < min) {
message = paste0(message, " Please supply at least ", min, " words. ")
}
else if (length(words) > max) {
message = paste0(message, " Please supply at most ", max, " words. ")
if (clip_max) {
message = paste0(message, "Using only the first ", max, " words. ")
}
}
return(message)
}
# Provides a text summary of word pairs
summarise_pairs <- function(left_words, right_words, words_not_in_norms, malformed_lines) {
# Validate
if (length(left_words) != length(right_words)) { stop('Pairs not matched') }
message = ""
if (length(malformed_lines) > 0) {
message = paste0(message, prettyNum(length(malformed_lines)), " invalid lines (including \"", malformed_lines[1], "\"). ")
}
if (length(words_not_in_norms) > 0) {
message = paste0(message, prettyNum(length(words_not_in_norms)), " concepts not found (including \"", words_not_in_norms[1], "\"). ")
}
message = paste0(prettyNum(length(left_words)), " valid pairs entered. ", message)
return(message)
}
# Provides a text summary of an attempt to parse a positive float
summarise_positive_float <- function(f, original_input, parse_success) {
if (! parse_success) {
return(paste0("\"", original_input, "\" not a valid distance."))
}
if (f <= 0) {
return("Please enter a positive distance.")
}
return("")
}
|
(** This file implements finite as unordered lists without duplicates.
Although this implementation is slow, it is very useful as decidable equality
is the only constraint on the carrier set. *)
From stdpp Require Export sets list.
From stdpp Require Import options.
Record listset_nodup A := ListsetNoDup {
listset_nodup_car : list A; listset_nodup_prf : NoDup listset_nodup_car
}.
Arguments ListsetNoDup {_} _ _ : assert.
Arguments listset_nodup_car {_} _ : assert.
Arguments listset_nodup_prf {_} _ : assert.
Section list_set.
Context `{EqDecision A}.
Notation C := (listset_nodup A).
Global Instance listset_nodup_elem_of: ElemOf A C := λ x l, x ∈ listset_nodup_car l.
Global Instance listset_nodup_empty: Empty C := ListsetNoDup [] (@NoDup_nil_2 _).
Global Instance listset_nodup_singleton: Singleton A C := λ x,
ListsetNoDup [x] (NoDup_singleton x).
Global Instance listset_nodup_union: Union C :=
λ '(ListsetNoDup l Hl) '(ListsetNoDup k Hk),
ListsetNoDup _ (NoDup_list_union _ _ Hl Hk).
Global Instance listset_nodup_intersection: Intersection C :=
λ '(ListsetNoDup l Hl) '(ListsetNoDup k Hk),
ListsetNoDup _ (NoDup_list_intersection _ k Hl).
Global Instance listset_nodup_difference: Difference C :=
λ '(ListsetNoDup l Hl) '(ListsetNoDup k Hk),
ListsetNoDup _ (NoDup_list_difference _ k Hl).
Instance listset_nodup_set: Set_ A C.
Proof.
split; [split | | ].
- by apply not_elem_of_nil.
- by apply elem_of_list_singleton.
- intros [??] [??] ?. apply elem_of_list_union.
- intros [??] [??] ?. apply elem_of_list_intersection.
- intros [??] [??] ?. apply elem_of_list_difference.
Qed.
Global Instance listset_nodup_elems: Elements A C := listset_nodup_car.
Global Instance listset_nodup_fin_set: FinSet A C.
Proof. split; [apply _|done|]. by intros [??]. Qed.
End list_set.
|
Require Export P03.
(** **** Problem #4 : 1 star (zero_nbeq_plus_1) *)
(* See the base file for the definition of [beq_nat]. *)
Theorem zero_nbeq_plus_1 : forall n : nat,
beq_nat 0 (n + 1) = false.
Proof.
intros n.
destruct n as [|n'].
- reflexivity.
- reflexivity.
Qed.
|
"""
Based on:
https://medium.com/vooban-ai/hyperopt-tutorial-for-optimizing-neural-networks-hyperparameters-e3102814b919
"""
module TestFindMin
using Test
using TreeParzen
function objective_min(space)
x = space[:x]
y = space[:y]
return x^2 + y^2
end
space = Dict(
:x => HP.Uniform(:x, -5.0, 5.0),
:y => HP.Uniform(:y, -5.0, 5.0)
)
best = fmin(objective_min, space, 100)
@test isapprox(best[:x], 0.013181950926553512, rtol = 1e2)
@test isapprox(best[:y], 0.0364742933684085, rtol = 1e2)
end
true
|
State Before: Ω : Type u_1
ι : Type u_2
inst✝ : MeasurableSpace Ω
s : ι → Set (Set Ω)
s' : Set (Set Ω)
μ : MeasureTheory.Measure Ω
h : ∃ n, IndepSets (s n) s'
⊢ IndepSets (⋂ (n : ι), s n) s' State After: Ω : Type u_1
ι : Type u_2
inst✝ : MeasurableSpace Ω
s : ι → Set (Set Ω)
s' : Set (Set Ω)
μ : MeasureTheory.Measure Ω
h : ∃ n, IndepSets (s n) s'
t1 t2 : Set Ω
ht1 : t1 ∈ ⋂ (n : ι), s n
ht2 : t2 ∈ s'
⊢ ↑↑μ (t1 ∩ t2) = ↑↑μ t1 * ↑↑μ t2 Tactic: intro t1 t2 ht1 ht2 State Before: Ω : Type u_1
ι : Type u_2
inst✝ : MeasurableSpace Ω
s : ι → Set (Set Ω)
s' : Set (Set Ω)
μ : MeasureTheory.Measure Ω
h : ∃ n, IndepSets (s n) s'
t1 t2 : Set Ω
ht1 : t1 ∈ ⋂ (n : ι), s n
ht2 : t2 ∈ s'
⊢ ↑↑μ (t1 ∩ t2) = ↑↑μ t1 * ↑↑μ t2 State After: case intro
Ω : Type u_1
ι : Type u_2
inst✝ : MeasurableSpace Ω
s : ι → Set (Set Ω)
s' : Set (Set Ω)
μ : MeasureTheory.Measure Ω
t1 t2 : Set Ω
ht1 : t1 ∈ ⋂ (n : ι), s n
ht2 : t2 ∈ s'
n : ι
h : IndepSets (s n) s'
⊢ ↑↑μ (t1 ∩ t2) = ↑↑μ t1 * ↑↑μ t2 Tactic: cases' h with n h State Before: case intro
Ω : Type u_1
ι : Type u_2
inst✝ : MeasurableSpace Ω
s : ι → Set (Set Ω)
s' : Set (Set Ω)
μ : MeasureTheory.Measure Ω
t1 t2 : Set Ω
ht1 : t1 ∈ ⋂ (n : ι), s n
ht2 : t2 ∈ s'
n : ι
h : IndepSets (s n) s'
⊢ ↑↑μ (t1 ∩ t2) = ↑↑μ t1 * ↑↑μ t2 State After: no goals Tactic: exact h t1 t2 (Set.mem_iInter.mp ht1 n) ht2 |
(*
* Copyright 2014, NICTA
*
* 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(NICTA_BSD)
*)
(* Port of Anthony Fox's HOL4 realisation of John Harrison's paper
in TPHOLs 2005 on finite cartesian products *)
theory Arrays
imports
"~~/src/HOL/Main"
"~~/src/HOL/Library/Numeral_Type"
begin
definition
has_size :: "'a set => nat => bool" where
"has_size s n == finite(s) \<and> card(s) = n"
definition
finite_index :: "nat => 'a::finite" where
"finite_index ==
SOME f. ALL x::'a. EX! n. n < CARD('a::finite) & f n = x"
lemma card_image_inj[rule_format]:
"finite s ==> (ALL x y. x : s & y : s & f x = f y --> x = y) -->
(card (f ` s) = card s)"
apply (erule finite_induct)
apply (simp_all add: card_insert_if)
apply clarsimp
apply blast
done
lemma has_size_image_inj:
"[| has_size s n ;
(!!x y. x \<in> s \<and> y \<in> s \<and> f x = f y ==> x = y) |]
==>
has_size (f ` s) n"
apply (simp add: has_size_def card_image_inj)
done
lemma has_size_0[simp]:
"has_size s 0 = (s = {})"
apply(simp_all add: has_size_def)
apply(rule iffI)
apply clarsimp
apply simp
done
lemma has_size_suc:
"has_size s (Suc n) =
(s ~= {} & (ALL a. a : s --> has_size (s - {a}) n))"
apply (simp add: has_size_def)
apply (case_tac "s = {}", simp_all)
apply (simp add: card_Diff_singleton cong: conj_cong)
apply (case_tac "finite s", simp_all)
apply (subgoal_tac "EX a. a : s")
apply simp
apply (subgoal_tac "card s ~= 0")
apply arith
apply (erule contrapos_nn)
apply simp
apply (simp add: ex_in_conv)
done
lemma has_index[rule_format]:
"ALL s. finite s & card s = n -->
(EX f. (ALL m. m < n --> f m : s) &
(ALL x. x : s --> (EX! m. m < n & f m = x)))"
apply (rule nat.induct)
apply (simp add: card_eq_0_iff cong: conj_cong)
apply clarsimp
apply (simp add: card_Suc_eq )
apply clarsimp
apply (erule_tac x = "B" in allE)
apply simp
apply clarsimp
apply (rule_tac x = "%n. if n = card B then b else f n" in exI)
apply clarsimp
apply rule
apply rule
apply (rule ex_ex1I)
apply (rule_tac x = "card B" in exI)
apply simp
apply (subgoal_tac "m = card B")
apply (subgoal_tac "y = card B")
apply simp
apply (rule ccontr)
apply (subgoal_tac "y < Suc (card B) & f y = b")
apply (subgoal_tac "y < card B")
apply fast
apply arith
apply fast
apply (rule ccontr)
apply (subgoal_tac "m < Suc (card B) & f m = b")
apply (subgoal_tac "m < card B")
apply fast
apply arith
apply fast
apply rule
apply (rule ex_ex1I)
apply (erule_tac x = x in allE)
apply (erule_tac impE)
apply simp
apply (drule ex1_implies_ex)
apply clarsimp
apply (rule_tac x = m in exI)
apply simp
apply (subgoal_tac "b ~= x")
apply simp
apply clarsimp
apply (subgoal_tac "y < card B & m < card B")
apply clarsimp
apply blast
apply arith
apply blast
done
lemma finite_index_works[rule_format]:
"ALL i :: 'a. EX! n. n < CARD('a::finite) & finite_index n = i"
apply (simp add: finite_index_def)
apply (rule someI_ex[where 'a = "nat => 'a"])
apply (insert has_index[where s = "UNIV :: 'a set"])
apply (simp add: finite)
done
lemma finite_index_inj:
"[| i < CARD('a::finite); j < CARD('a) |] ==>
((finite_index i :: 'a) = finite_index j) = (i = j)"
apply (insert finite_index_works[where i = "finite_index j"])
apply blast
done
lemma forall_finite_index:
"(ALL k::('a::finite). P k) =
(ALL i. i < CARD('a) --> P (finite_index i))"
apply rule
apply simp
apply rule+
apply (insert finite_index_works[where 'a = 'a])
apply (erule_tac x = "k::'a" in meta_allE)
apply blast
done
section {* Finite Cartesian Products *}
typedef ('a,'b) array ("_[_]" [30,0] 31)
= "UNIV :: ('b::finite => 'a) set"
by simp
lemma array_inject:
"(Abs_array x = Abs_array y) = (x = y)"
by (metis Abs_array_inverse UNIV_I)
lemma array_induct:
"(!!f. P (Abs_array f)) \<Longrightarrow> P x"
apply (drule_tac allI)
apply (drule_tac spec[where ?x = "Rep_array x"])
apply (simp add: Rep_array_inverse)
done
rep_datatype "Abs_array"
by (auto simp: array_inject intro: array_induct)
(* should add nice syntax for index *)
definition index :: "('a,'b::finite)array => nat => 'a" where
"index x i == Rep_array x (finite_index i)"
lemma my_ext: "(ALL x. f x = g x) = (f = g)"
apply (rule+, simp+)
done
theorem cart_eq:
"((x::('a,'b::finite)array) = y) =
(ALL i. i < CARD('b) --> index x i = index y i)"
apply (rule, simp)
apply (simp add: index_def)
apply (drule forall_finite_index[THEN iffD2])
apply (simp add: my_ext Rep_array_inject)
done
(* should make FCP a binder, and perhaps call it something else.
Maybe "ARRAY" ? *)
definition FCP :: "(nat => 'a) => ('a,'b::finite) array" where
"FCP == \<lambda> g.
SOME f.
ALL i. i < CARD('b) --> index f i = g i"
definition
update :: "('a,'b::finite) array \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> ('a,'b) array"
where
"update f i x \<equiv> FCP ((index f)(i := x))"
definition
fupdate :: "nat => ('a => 'a) => ('a,'b::finite) array =>
('a,'b::finite) array"
where
"fupdate i f x \<equiv> update x i (f (index x i))"
lemma fcp_beta[rule_format]:
"ALL i. i < CARD('b::finite) -->
index (FCP g :: ('a,'b) array) i = g i"
apply (simp add: FCP_def)
apply (rule someI_ex)
apply (rule_tac x =
"Abs_array (%k. g (SOME i. i < CARD('b) &
finite_index i = k))"
in exI)
apply (simp add: index_def Abs_array_inverse)
apply rule+
apply (rule arg_cong[where 'a = nat])
apply (rule some_equality)
apply simp
apply (erule conjE)
apply (rule finite_index_inj[THEN iffD1])
apply simp_all
done
lemma fcp_unique:
"(ALL i. i < CARD('b::finite) --> (index f i = g i)) =
(FCP g = (f :: ('a,'b) array))"
by (fastforce simp: cart_eq fcp_beta)
lemma fcp_eta:
"FCP (%i. index g i) = g"
by (simp add: cart_eq fcp_beta)
lemma index_update [simp]:
"n < CARD('b::finite) \<Longrightarrow> index (update (f::('a,'b) array) n x) n = x"
by (simp add: update_def fcp_beta)
lemma index_update2 [simp]:
"\<lbrakk> k < CARD('b::finite); n \<noteq> k \<rbrakk>
\<Longrightarrow>
index (update (f::('a,'b) array) n x) k = index f k"
by (simp add: update_def fcp_beta)
lemma update_update [simp]:
"update (update f n x) n y = update f n y"
apply(subst cart_eq)
apply clarsimp
apply(case_tac "i=n")
apply simp+
done
lemma update_comm [simp]:
"n \<noteq> m \<Longrightarrow> update (update f m v) n v' = update (update f n v') m v"
apply(subst cart_eq)
apply clarsimp
apply(case_tac "i=n")
apply simp
apply(case_tac "i=m")
apply simp
apply simp
done
lemma update_index_same [simp]:
"update v n (index v n) = v"
apply(subst cart_eq)
apply clarsimp
apply(case_tac "i=n")
apply simp+
done
function
foldli0 :: "(nat => 'acc => 'a => 'acc) => 'acc => nat => ('a,'index::finite)array => 'acc"
where
"foldli0 f a i (arr::('a,'index::finite)array) =
(if CARD('index::finite) <= i then a
else foldli0 f (f i a (index arr i)) (i+1) arr)"
by pat_completeness auto
termination
apply (relation "measure (% (f,a,i,(arr::('b,'c::finite)array)). CARD('c) - i)")
apply auto
done
definition
foldli :: "(nat => 'acc => 'a => 'acc) => 'acc => ('a,'i::finite) array => 'acc"
where
"foldli f a arr == foldli0 f a 0 arr"
(* for a traditional word presentation, with MSB on the left, you'd
want a fold that numbered in the reverse direction (with element 0
on the right rather than the left) *)
end
|
import ch7
universe u
namespace Set
local attribute [irreducible] mem
lemma card_nat {n : Set} (hn : n ∈ ω) : n.card = n :=
have hf : n.is_finite := ⟨n, hn, equin_refl⟩,
unique_of_exists_unique (exists_unique_equiv_nat_of_finite hf) (card_finite hf) ⟨hn, equin_refl⟩
lemma eq_empty_of_card_empty {A : Set} (Acard : A.card = ∅) : A = ∅ :=
begin
rw [←card_nat (zero_nat), card_equiv] at Acard,
exact empty_of_equin_empty Acard,
end
lemma ne_empty_of_zero_mem_card {A : Set} (zA : ∅ ∈ A.card) : A ≠ ∅ :=
begin
intro Ae, subst Ae, rw card_nat zero_nat at zA, exact mem_empty _ zA,
end
lemma finite_iff {A : Set} : A.is_finite ↔ ∃ n : Set, n ∈ ω ∧ A.card = n :=
begin
simp only [is_finite, ←card_equiv, subst_right_of_and card_nat],
end
lemma nat_finite {n : Set} (hn : n ∈ ω) : n.is_finite := finite_iff.mpr ⟨_, hn, card_nat hn⟩
theorem nat_is_cardinal {n : Set} (hn : n ∈ ω) : n.is_cardinal := ⟨_, card_nat hn⟩
theorem card_omega_not_nat : ¬ ∃ n : Set, n ∈ ω ∧ card ω = n :=
begin
rintro ⟨n, hn, he⟩, apply nat_infinite, rw [←card_nat hn, card_equiv] at he, exact ⟨_, hn, he⟩,
end
lemma not_empty_of_card_not_empty {κ : Set} (hnz : κ ≠ ∅) {X : Set} (he : X.card = κ) : X ≠ ∅ :=
begin
intro hee, rw [hee, card_nat (nat_induct.zero)] at he, apply hnz, rw he,
end
lemma prod_singleton_equin {X Y : Set} : X.equinumerous (X.prod {Y}) :=
begin
let f : Set := pair_sep (λ a b, b = a.pair Y) X (X.prod {Y}),
have ffun : f.is_function := pair_sep_eq_is_fun,
have fdom : f.dom = X, apply pair_sep_eq_dom_eq, intros a ha,
simp only [mem_prod, exists_prop, mem_singleton], exact ⟨_, ha, _, rfl, rfl⟩,
have fran : f.ran = X.prod {Y}, apply pair_sep_eq_ran_eq, intros b hb,
simp only [mem_prod, exists_prop, mem_singleton] at hb, rcases hb with ⟨a, ha, b', hb', hp⟩, rw hb' at hp,
exact ⟨_, ha, hp⟩,
have foto : f.one_to_one, apply pair_sep_eq_oto, intros a ha a' ha' he, exact (pair_inj he).left,
exact ⟨_, ⟨ffun, fdom, fran⟩, foto⟩,
end
lemma singleton_equin {x y : Set} : equinumerous {x} {y} :=
⟨{x.pair y}, single_pair_onto, single_pair_oto⟩
lemma prod_disj_of_right_disj {A B C D : Set} (h : C ∩ D = ∅) : A.prod C ∩ B.prod D = ∅ :=
begin
rw rel_eq_empty (inter_rel_is_rel prod_is_rel), simp [mem_inter, pair_mem_prod],
intros x y hA hC hB hD, apply mem_empty y, rw [←h, mem_inter], exact ⟨hC, hD⟩,
end
lemma prod_empty_eq_empty {A : Set} : A.prod ∅ = ∅ :=
begin
rw rel_eq_empty prod_is_rel, intros x y h, rw pair_mem_prod at h, exact mem_empty _ h.right,
end
lemma empty_prod_eq_empty {A : Set} : prod ∅ A = ∅ :=
begin
rw rel_eq_empty prod_is_rel, intros x y h, rw pair_mem_prod at h, exact mem_empty _ h.left,
end
-- excercise 6
theorem card_not_set {κ : Set} (hc : κ.is_cardinal) (hnz : κ ≠ ∅) : ¬ ∃ Κ : Set, ∀ X : Set, X ∈ Κ ↔ card X = κ :=
begin
rintro ⟨Κ, h⟩, apply univ_not_set,
existsi Κ.Union.Union.Union, intro X,
rcases hc with ⟨Y, hY⟩,
let Z : Set := Y.prod {X},
have hZ : Z ∈ Κ, rw [h _, ←hY, card_equiv], apply equin_symm, exact prod_singleton_equin,
have hin : Y.inhab := inhabited_of_ne_empty (not_empty_of_card_not_empty hnz hY),
rcases hin with ⟨u, hu⟩,
simp only [mem_Union, exists_prop], refine ⟨{u, X}, ⟨u.pair X, ⟨Z, hZ, _⟩, _⟩, _⟩,
{ simp only [mem_prod, exists_prop, mem_singleton], exact ⟨_, hu, _, rfl, rfl⟩, },
{ rw [pair, mem_insert, mem_singleton], exact or.inr rfl, },
{ rw [mem_insert, mem_singleton], exact or.inr rfl, },
end
def finite_cardinal (κ : Set) : Prop := ∃ X : Set, X.is_finite ∧ card X = κ
lemma fin_card_is_card {κ : Set} (κfin : κ.finite_cardinal) : κ.is_cardinal :=
exists.elim κfin (λ K hK, ⟨_, hK.right⟩)
theorem one_finite_all_finite {κ : Set} (hf : κ.finite_cardinal) {X : Set} (hc : card X = κ) : X.is_finite :=
begin
rcases hf with ⟨X', ⟨n, hn, hX'n⟩, hc'⟩, rw [←hc', card_equiv] at hc, exact ⟨_, hn, equin_trans hc hX'n⟩
end
lemma card_finite_iff_finite {A : Set} : A.card.finite_cardinal ↔ A.is_finite :=
⟨λ h, one_finite_all_finite h rfl, λ h, ⟨_, h, rfl⟩⟩
theorem finite_cardinal_iff_nat {X : Set} : X.finite_cardinal ↔ X ∈ ω :=
begin
simp only [finite_cardinal, is_finite], split,
{ rintro ⟨Y, ⟨n, hn, hYn⟩, hc⟩, rw ←card_equiv at hYn, rw [hYn, card_nat hn] at hc, rw ←hc, exact hn, },
{ rintro hX, refine ⟨X, ⟨X, hX, equin_refl⟩, card_nat hX⟩, },
end
theorem aleph_null_infinite_cardinal : ¬ finite_cardinal (card ω) :=
begin
rintro ⟨X, ⟨n, hn, hXn⟩, hc⟩, apply nat_infinite, rw [card_equiv] at hc, refine ⟨_, hn, equin_trans (equin_symm hc) hXn⟩,
end
lemma Lemma_6F : ∀ {n : Set}, n ∈ ω → ∀ {C : Set}, C ⊂ n → ∃ m : Set, m ∈ n ∧ C.equinumerous m :=
begin
apply @induction (λ n, ∀ {C : Set}, C ⊂ n → ∃ m : Set, m ∈ n ∧ C.equinumerous m),
{ rintros C ⟨hs, hne⟩, exfalso, apply hne, rw eq_iff_subset_and_subset, refine ⟨hs, λ x hx, _⟩, exfalso, exact mem_empty _ hx, },
{ intros k hk hi C hCk, by_cases heCk : C = k,
{ refine ⟨_, self_mem_succ, _⟩, rw heCk, exact equin_refl, },
{ by_cases hkmC : k ∈ C,
{ have hCe : C = (C ∩ k) ∪ {k}, apply ext, simp only [mem_union, mem_inter, mem_singleton], intro x, split,
{ intro hxC,
have hxk : x ∈ k.succ := hCk.left hxC,
rw [mem_succ_iff_le, le_iff] at hxk, cases hxk,
{ left, exact ⟨hxC, hxk⟩, },
{ right, exact hxk, }, },
{ rintro (⟨hxC, hxk⟩|hxk),
{ exact hxC, },
{ rw ←hxk at hkmC, exact hkmC, }, },
have hCkp : C ∩ k ⊂ k, refine ⟨λ x hx, _, _⟩,
{ rw mem_inter at hx, exact hx.right, },
{ intro hCke, apply hCk.right, rw eq_iff_subset_and_subset, refine ⟨hCk.left, λ x hxk, _⟩,
rw [mem_succ_iff_le, le_iff] at hxk, cases hxk,
{ rw ←hCke at hxk, rw mem_inter at hxk, exact hxk.left, },
{ rw ←hxk at hkmC, exact hkmC, }, },
specialize hi hCkp, rcases hi with ⟨m, hmk, f, fonto, foto⟩,
let g : Set := f ∪ {k.pair m},
have ginto : g.into_fun C m.succ, rw fun_def_equiv,
have hf : (C ∩ k).is_func m f, rw ←fun_def_equiv, exact into_of_onto fonto,
refine ⟨λ p hp, _, λ x hxC, _⟩,
{ simp only [mem_prod, exists_prop, mem_succ_iff_le, le_iff], rw [mem_union, mem_singleton] at hp,
cases hp,
{ replace hp := hf.left hp, simp only [mem_prod, exists_prop] at hp,
rcases hp with ⟨x, hx, y, hy, hp⟩, rw mem_inter at hx, exact ⟨_, hx.left, _, or.inl hy, hp⟩, },
{ exact ⟨_, hkmC, _, or.inr rfl, hp⟩, }, },
{ rw [hCe, mem_union, mem_singleton] at hxC, simp only [mem_union, mem_singleton], cases hxC,
{ have he : ∃ y : Set, x.pair y ∈ f := exists_of_exists_unique (hf.right _ hxC),
rcases he with ⟨y, hxyf⟩, refine exists_unique_of_exists_of_unique ⟨_, or.inl hxyf⟩ _,
rintros z z' (hz|hz) (hz'|hz'),
{ exact unique_of_exists_unique (hf.right _ hxC) hz hz', },
{ exfalso, rw mem_inter at hxC, rw (pair_inj hz').left at hxC, exact nat_not_mem_self hk hxC.right, },
{ exfalso, rw mem_inter at hxC, rw (pair_inj hz).left at hxC, exact nat_not_mem_self hk hxC.right, },
{ rw [(pair_inj hz).right, (pair_inj hz').right], }, },
{ rw hxC, refine ⟨_, or.inr rfl, _⟩, rintros y (hy|hy),
{ exfalso, apply nat_not_mem_self hk,
have hkd : k ∈ f.dom, rw mem_dom, exact ⟨_, hy⟩,
rw [fonto.right.left, mem_inter] at hkd, exact hkd.right, },
{ exact (pair_inj hy).right, }, }, },
have gran : g.ran = m.succ, rw [ran_union, fonto.right.right, ran_single_pair, succ], rw union_comm,
have goto : g.one_to_one, apply union_one_to_one foto single_pair_oto, rw [fonto.right.right, ran_single_pair],
rw eq_empty, intros x hx, rw [mem_inter, mem_singleton] at hx, apply nat_not_mem_self ((mem_nat_iff hk).mp hmk).left,
cases hx with hxmm hxem, rw hxem at hxmm, exact hxmm,
existsi m.succ, rw ←mem_iff_succ_mem_succ, exact ⟨hmk, _, ⟨ginto.left, ginto.right.left, gran⟩, goto⟩,
exact ((mem_nat_iff hk).mp hmk).left, exact hk, },
{ have hCpk : C ⊂ k, refine ⟨λ x hxC, _, heCk⟩,
have hxk : x ∈ k.succ := hCk.left hxC,
rw [mem_succ_iff_le, le_iff] at hxk, cases hxk,
{ exact hxk, },
{ exfalso, rw hxk at hxC, exact hkmC hxC, },
specialize hi hCpk, rcases hi with ⟨m, hmk, hCm⟩,
simp only [mem_succ_iff_le, le_iff], exact ⟨_, or.inl hmk, hCm⟩, }, }, },
end
-- Corollary 6G
theorem subset_finite_of_finite {A : Set.{u}} (hA : A.is_finite) {B : Set} (hBA : B ⊆ A) : B.is_finite :=
begin
by_cases he : A = B,
{ rw ←he, exact hA, },
{ rcases hA with ⟨n, hn, f, fonto, foto⟩,
have hBeq : B.equinumerous (f.img B),
let g : Set := f.restrict B,
have gfun : g.is_function := restrict_is_function fonto.left,
have gdom : g.dom = B, refine restrict_dom _, rw fonto.right.left, exact hBA,
have gran : g.ran = f.img B := restrict_ran,
have goto : g.one_to_one, refine restrict_one_to_one fonto.left foto _, rw fonto.right.left, exact hBA,
exact ⟨_, ⟨gfun, gdom, gran⟩, goto⟩,
have hfimgne : f.img B ≠ n, rw ←fonto.right.right, refine img_ne_ran_of_ne_dom fonto.left foto _ _,
{ rw fonto.right.left, exact hBA, },
rw fonto.right.left, symmetry, exact he,
have hfimgsub : f.img B ⊆ n, rw ←fonto.right.right, exact img_subset_ran,
obtain ⟨m, hmn, hfimgeqm⟩ := Lemma_6F hn ⟨hfimgsub, hfimgne⟩,
have hm : m ∈ (ω : Set.{u}) := ((mem_nat_iff hn).mp hmn).left,
exact ⟨_, hm, equin_trans hBeq hfimgeqm⟩, },
end
lemma inf_of_sup_inf {X : Set} (Xinf : ¬ X.is_finite) {Y : Set} (XY : X ⊆ Y) : ¬ Y.is_finite :=
λ Yfin, Xinf (subset_finite_of_finite Yfin XY)
-- All of the excericises at the end of the section on finite sets are worth doing
theorem T6H_a {K₁ K₂ : Set} (hK : K₁.equinumerous K₂) {L₁ L₂ : Set} (hL : L₁.equinumerous L₂) (hd₁ : K₁ ∩ L₁ = ∅) (hd₂ : K₂ ∩ L₂ = ∅) : (K₁ ∪ L₁).equinumerous (K₂ ∪ L₂) :=
begin
rcases hK with ⟨f, fonto, foto⟩,
rcases hL with ⟨g, gonto, goto⟩,
let h : Set := f ∪ g,
have honto : h.onto_fun (K₁ ∪ L₁) (K₂ ∪ L₂), rw [←fonto.right.left, ←gonto.right.left, ←fonto.right.right, ←gonto.right.right],
apply union_fun fonto.left gonto.left,
rw [fonto.right.left, gonto.right.left], exact hd₁,
have hoto : h.one_to_one, apply union_one_to_one foto goto,
rw [fonto.right.right, gonto.right.right], exact hd₂,
exact ⟨h, honto, hoto⟩,
end
lemma T6H_b_lemma {K₁ K₂ f : Set} (fc : K₁.correspondence K₂ f) {L₁ L₂ g : Set} (gc : L₁.correspondence L₂ g) :
correspondence (K₁.prod L₁) (K₂.prod L₂) (pair_sep_eq (K₁.prod L₁) (K₂.prod L₂) (λ a, (f.fun_value a.fst).pair (g.fun_value a.snd))) :=
begin
rcases fc with ⟨fonto, foto⟩, rcases gc with ⟨gonto, goto⟩,
refine ⟨⟨pair_sep_eq_is_fun, pair_sep_eq_dom_eq _, pair_sep_eq_ran_eq _⟩, pair_sep_eq_oto _⟩,
{ intros z hz, dsimp,
rw [pair_mem_prod, ←fonto.right.right, ←gonto.right.right], split,
{ apply fun_value_def'' fonto.left, rw fonto.right.left, exact (fst_snd_mem_dom_ran hz).left, },
{ apply fun_value_def'' gonto.left, rw gonto.right.left, exact (fst_snd_mem_dom_ran hz).right, }, },
{ intros b hb, rw mem_prod at hb,
rcases hb with ⟨k, hk, l, hl, hb⟩,
rw [←fonto.right.right, mem_ran_iff fonto.left] at hk, rw [←gonto.right.right, mem_ran_iff gonto.left] at hl,
rcases hk with ⟨k', hk', hk⟩, rcases hl with ⟨l', hl', hl⟩,
refine ⟨k'.pair l', _, _⟩,
{ rw pair_mem_prod, rw [←fonto.right.left, ←gonto.right.left], finish, },
{ dsimp, rw [fst_congr, snd_congr, hb, hk, hl], }, },
{ intros p hp q hq he,
have he' := pair_inj he,
rw [fst_snd_spec (is_pair_of_mem_prod hp), fst_snd_spec (is_pair_of_mem_prod hq)],
have feq : p.fst = q.fst, refine from_one_to_one fonto.left foto _ _ he'.left,
{ rw fonto.right.left, exact (fst_snd_mem_dom_ran hp).left, },
{ rw fonto.right.left, exact (fst_snd_mem_dom_ran hq).left, },
have seq : p.snd = q.snd, refine from_one_to_one gonto.left goto _ _ he'.right,
{ rw gonto.right.left, exact (fst_snd_mem_dom_ran hp).right, },
{ rw gonto.right.left, exact (fst_snd_mem_dom_ran hq).right, },
rw [feq, seq], },
end
theorem T6H_b {K₁ K₂ : Set} (hK : K₁.equinumerous K₂) {L₁ L₂ : Set} (hL : L₁.equinumerous L₂) : (K₁.prod L₁).equinumerous (K₂.prod L₂) :=
begin
rcases hK with ⟨f, fc⟩, rcases hL with ⟨g, gc⟩, exact ⟨_, T6H_b_lemma fc gc⟩,
end
theorem T6H_c {K₁ K₂ : Set} (hK : K₁.equinumerous K₂) {L₁ L₂ : Set} (hL : L₁.equinumerous L₂) : (L₁.into_funs K₁).equinumerous (L₂.into_funs K₂) :=
begin
rcases hK with ⟨f, fonto, foto⟩,
rcases hL with ⟨g, gonto, goto⟩,
let H : Set := pair_sep (λ j h, h = f.comp (j.comp g.inv)) (L₁.into_funs K₁) (L₂.into_funs K₂),
have Hfun : H.is_function := pair_sep_eq_is_fun,
have Hdom : H.dom = L₁.into_funs K₁, apply pair_sep_eq_dom_eq, intros h hh, rw mem_into_funs at hh, rw mem_into_funs,
apply comp_into_fun,
{ apply comp_into_fun (inv_into_fun gonto goto) hh, },
{ exact into_of_onto fonto, },
have Hran : H.ran = L₂.into_funs K₂, apply pair_sep_eq_ran_eq, intros d hd, rw mem_into_funs at hd,
let j := f.inv.comp (d.comp g), refine ⟨j, _, _⟩,
{ rw mem_into_funs, apply comp_into_fun,
{ apply comp_into_fun (into_of_onto gonto) hd, },
{ exact inv_into_fun fonto foto, }, },
{ rw [←Set.comp_assoc, ←Set.comp_assoc, eq_inv_id fonto.left foto, Set.comp_assoc, Set.comp_assoc, eq_inv_id gonto.left goto],
rw [gonto.right.right, ←hd.right.left, comp_id hd.left, fonto.right.right], symmetry, exact id_comp hd.right.right hd.left, },
have hoto : H.one_to_one, apply pair_sep_eq_oto, intros j hj j' hj' he,
rw mem_into_funs at hj hj',
have h : (f.comp (j.comp g.inv)).comp g = (f.comp (j'.comp g.inv)).comp g, rw he,
rw [comp_assoc, comp_assoc, comp_assoc, comp_assoc, eq_id gonto.left goto, gonto.right.left] at h,
nth_rewrite 0 ←hj.right.left at h, rw [←hj'.right.left, comp_id hj.left, comp_id hj'.left] at h,
apply fun_ext hj.left hj'.left,
{ rw [hj.right.left, hj'.right.left], },
{ intros t ht, apply from_one_to_one fonto.left foto,
{ rw fonto.right.left, apply hj.right.right, apply fun_value_def'' hj.left ht, },
{ rw fonto.right.left, apply hj'.right.right, rw [hj.right.left, ←hj'.right.left] at ht,
apply fun_value_def'' hj'.left ht, },
{ rw [←T3H_c fonto.left hj.left, ←T3H_c fonto.left hj'.left, h],
{ rw [dom_comp, hj'.right.left, ←hj.right.left], exact ht, rw [fonto.right.left], exact hj'.right.right, },
{ rw [dom_comp], exact ht, rw [fonto.right.left], exact hj.right.right, }, }, },
exact ⟨_, ⟨Hfun, Hdom, Hran⟩, hoto⟩,
end
lemma same_card {A x : Set} : (A.prod {x}).card = A.card :=
begin
rw card_equiv, apply equin_symm, exact prod_singleton_equin,
end
lemma disj {A B x y : Set} (hne : x ≠ y) : (A.prod {x}) ∩ (B.prod {y}) = ∅ :=
prod_disj (singleton_disj_of_ne hne)
lemma exists_add {κ μ : Set} : ∃ ν : Set, ∀ (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → K ∩ M = ∅ → (K ∪ M).card = ν :=
begin
let K' := κ.prod {∅},
let M' := μ.prod {one},
have hK' : K'.card = κ.card := same_card,
have hM' : M'.card = μ.card := same_card,
have hdisj : K' ∩ M' = ∅ := disj zero_ne_one,
existsi (K' ∪ M').card, intros J hJ N hN hd,
rw card_equiv, refine T6H_a _ _ hd hdisj,
{ rw [←card_equiv, hJ, hK', card_of_cardinal_eq_self ⟨_, hJ⟩], },
{ rw [←card_equiv, hN, hM', card_of_cardinal_eq_self ⟨_, hN⟩], },
end
lemma exists_mul {κ μ : Set} : ∃ ν : Set, ∀ (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → (K.prod M).card = ν :=
begin
existsi (κ.prod μ).card, intros K' hK' M' hM', rw card_equiv,
apply T6H_b,
{ rw [←card_equiv, hK', card_of_cardinal_eq_self ⟨_, hK'⟩], },
{ rw [←card_equiv, hM', card_of_cardinal_eq_self ⟨_, hM'⟩], },
end
lemma exists_exp {κ μ : Set} : ∃ ν : Set, ∀ (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → (M.into_funs K).card = ν :=
begin
existsi (μ.into_funs κ).card, intros K' hK' M' hM', rw card_equiv,
apply T6H_c,
{ rw [←card_equiv, hK', card_of_cardinal_eq_self ⟨_, hK'⟩], },
{ rw [←card_equiv, hM', card_of_cardinal_eq_self ⟨_, hM'⟩], },
end
lemma exists_add_fun : ∃ (add : Set → Set → Set), ∀ (κ μ : Set) (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → K ∩ M = ∅ → (K ∪ M).card = add κ μ :=
choice_2_arg @exists_add
lemma exists_mul_fun : ∃ (mul : Set → Set → Set), ∀ (κ μ : Set) (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → (K.prod M).card = mul κ μ :=
choice_2_arg @exists_mul
lemma exists_exp_fun : ∃ (exp : Set → Set → Set), ∀ (κ μ : Set) (K : Set), K.card = κ → ∀ (M : Set), M.card = μ → (M.into_funs K).card = exp κ μ :=
choice_2_arg @exists_exp
noncomputable def card_add : Set.{u} → Set.{u} → Set.{u} := classical.some exists_add_fun
noncomputable def card_mul : Set.{u} → Set.{u} → Set.{u} := classical.some exists_mul_fun
noncomputable def card_exp : Set.{u} → Set.{u} → Set.{u} := classical.some exists_exp_fun
lemma card_add_spec : ∀ {κ μ : Set} {K : Set}, K.card = κ → ∀ {M : Set}, M.card = μ → K ∩ M = ∅ → (K ∪ M).card = card_add κ μ :=
classical.some_spec exists_add_fun
lemma card_mul_spec : ∀ {κ μ : Set} {K : Set}, K.card = κ → ∀ {M : Set}, M.card = μ → (K.prod M).card = card_mul κ μ :=
classical.some_spec exists_mul_fun
lemma card_exp_spec : ∀ {κ μ : Set} {K : Set}, K.card = κ → ∀ {M : Set}, M.card = μ → (M.into_funs K).card = card_exp κ μ :=
classical.some_spec exists_exp_fun
lemma add_cardinal {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : (κ.card_add μ).is_cardinal :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩,
let K' := K.prod {∅},
let M' := M.prod {one},
have hK' : K'.card = κ, rw same_card, exact hK,
have hM' : M'.card = μ, rw same_card, exact hM,
have hdisj : K' ∩ M' = ∅ := disj zero_ne_one,
rw ←card_add_spec hK' hM' hdisj, exact ⟨_, rfl⟩,
end
lemma mul_cardinal {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : (κ.card_mul μ).is_cardinal :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩,
rw ←card_mul_spec hK hM, exact ⟨_, rfl⟩,
end
lemma exp_cardinal {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : (κ.card_exp μ).is_cardinal :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩,
rw ←card_exp_spec hK hM, exact ⟨_, rfl⟩,
end
theorem aleph_mul_aleph_eq_aleph : card_mul (card ω) (card ω) = card ω :=
begin
rw [←card_mul_spec rfl rfl, card_equiv], exact nat_prod_nat_equin_nat,
end
-- example 4, part c, page 141
theorem card_mul_one_eq_self {κ : Set} (hκ : κ.is_cardinal) : κ.card_mul one = κ :=
begin
rcases hκ with ⟨K, hK⟩, rw [←card_mul_spec hK (card_nat one_nat), ←hK, card_equiv, one, succ, union_empty],
apply equin_symm, exact prod_singleton_equin,
end
-- example 6, page 141
theorem card_power {A : Set} : A.powerset.card = two.card_exp A.card :=
begin
have h : A.powerset.card = (A.into_funs two).card, rw card_equiv, exact powerset_equinumerous_into_funs,
rw h, apply card_exp_spec (card_nat two_nat) rfl,
end
-- example 7, page 142
theorem card_ne_power {κ : Set} (hκ : κ.is_cardinal) : κ ≠ two.card_exp κ :=
begin
intro he, rcases hκ with ⟨K, hK⟩, rw [←hK, ←card_power, card_equiv] at he,
exact not_equin_powerset he,
end
-- Theorem 6I part 1 part a
theorem card_add_comm {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : κ.card_add μ = μ.card_add κ :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
let K' := K.prod {∅},
let M' := M.prod {one},
have hK' : K'.card = K.card := same_card,
have hM' : M'.card = M.card := same_card,
have hdisj : K' ∩ M' = ∅ := disj zero_ne_one,
rw hK at hK', rw hM at hM', rw ←card_add_spec hK' hM' hdisj,
rw inter_comm at hdisj, rw ←card_add_spec hM' hK' hdisj, rw union_comm,
end
-- Theorem 6I part 1 part b
theorem card_mul_comm {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : κ.card_mul μ = μ.card_mul κ :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rw [←card_mul_spec hK hM, ←card_mul_spec hM hK, card_equiv],
let f : Set := pair_sep_eq (K.prod M) (M.prod K) (λ z, z.snd.pair z.fst),
refine ⟨f, ⟨pair_sep_eq_is_fun, pair_sep_eq_dom_eq _, pair_sep_eq_ran_eq _⟩, pair_sep_eq_oto _⟩,
{ intros z hz, rw mem_prod at hz, rcases hz with ⟨k, hk, m, hm, he⟩, subst he,
rw [pair_mem_prod, snd_congr, fst_congr], exact ⟨hm, hk⟩, },
{ intros z hz, rw mem_prod at hz, rcases hz with ⟨m, hm, k, hk, he⟩, subst he, use k.pair m,
simp only [pair_mem_prod, snd_congr, fst_congr],
exact ⟨⟨hk, hm⟩, rfl⟩, },
{ intros z hz z' hz' he,
obtain ⟨snde, fste⟩ := pair_inj he,
rw mem_prod at hz, rw mem_prod at hz',
rcases hz with ⟨k, hk, m, hm, hze⟩, rcases hz' with ⟨k', hk', m', hm', hze'⟩,
subst hze, subst hze', simp only [snd_congr] at snde, simp only [fst_congr] at fste,
subst snde, subst fste, },
end
-- Theorem 6I part 2 part a
theorem card_add_assoc {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) {ν : Set} (hν : ν.is_cardinal) :
κ.card_add (μ.card_add ν) = (κ.card_add μ).card_add ν :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rcases hν with ⟨N, hN⟩,
let K' := K.prod {∅},
let M' := M.prod {one},
let N' := N.prod {two},
have hK' : K'.card = K.card := same_card,
have hM' : M'.card = M.card := same_card,
have hN' : N'.card = N.card := same_card,
have hKM : K' ∩ M' = ∅ := disj zero_ne_one,
have hKN : K' ∩ N' = ∅ := disj zero_ne_two,
have hMN : M' ∩ N' = ∅ := disj one_ne_two,
have hK_MN : K' ∩ (M' ∪ N') = ∅, rw [inter_union, hKM, hKN, union_empty],
have hKM_N : (K' ∪ M') ∩ N' = ∅, rw [union_inter, hKN, hMN, union_empty],
rw hK at hK', rw hM at hM', rw hN at hN',
rw ←card_add_spec hM' hN' hMN,
rw ←card_add_spec hK' rfl hK_MN,
rw ←card_add_spec hK' hM' hKM,
rw ←card_add_spec rfl hN' hKM_N,
rw union_assoc,
end
-- Theorem 6I part 3
theorem card_mul_add {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) {ν : Set} (hν : ν.is_cardinal) :
κ.card_mul (μ.card_add ν) = (κ.card_mul μ).card_add (κ.card_mul ν) :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rcases hν with ⟨N, hN⟩,
let K' := K.prod {∅},
let M' := M.prod {one},
let N' := N.prod {two},
have hK' : K'.card = K.card := same_card,
have hM' : M'.card = M.card := same_card,
have hN' : N'.card = N.card := same_card,
have hKM : K' ∩ M' = ∅ := disj zero_ne_one,
have hKN : K' ∩ N' = ∅ := disj zero_ne_two,
have hMN : M' ∩ N' = ∅ := disj one_ne_two,
have hK_MN : K' ∩ (M' ∪ N') = ∅, rw [inter_union, hKM, hKN, union_empty],
have hKM_N : (K' ∪ M') ∩ N' = ∅, rw [union_inter, hKN, hMN, union_empty],
rw hK at hK', rw hM at hM', rw hN at hN',
rw ←card_add_spec hM' hN' hMN,
rw ←card_mul_spec hK' rfl,
rw ←card_mul_spec hK' hM',
rw ←card_mul_spec hK' hN',
rw ←card_add_spec rfl rfl (prod_disj_of_right_disj hMN),
rw prod_union,
end
-- Theorem 6I part 4
theorem card_exp_add {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) {ν : Set} (hν : ν.is_cardinal) :
κ.card_exp (μ.card_add ν) = (κ.card_exp μ).card_mul (κ.card_exp ν) :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rcases hν with ⟨N, hN⟩,
let M' := M.prod {∅},
let N' := N.prod {one},
have hM' : M'.card = M.card := same_card,
have hN' : N'.card = N.card := same_card,
have hMN : M' ∩ N' = ∅ := disj zero_ne_one,
rw hM at hM', rw hN at hN',
rw ←card_add_spec hM' hN' hMN,
rw ←card_exp_spec hK rfl,
rw ←card_exp_spec hK hM',
rw ←card_exp_spec hK hN',
rw ←card_mul_spec rfl rfl,
rw card_equiv,
let f : Set := pair_sep_eq ((M' ∪ N').into_funs K) ((M'.into_funs K).prod (N'.into_funs K)) (λ g, (g.restrict M').pair (g.restrict N')),
have hfun : f.is_function := pair_sep_eq_is_fun,
have hdom : f.dom = (M' ∪ N').into_funs K, apply pair_sep_eq_dom_eq,
intros g hg, simp only [pair_mem_prod, mem_into_funs], rw mem_into_funs at hg, split,
{ exact restrict_into_fun hg subset_union_left, },
{ exact restrict_into_fun hg subset_union_right, },
have hran : f.ran = (M'.into_funs K).prod (N'.into_funs K), apply pair_sep_eq_ran_eq,
intros p hp, simp only [mem_prod, exists_prop, mem_into_funs] at hp,
rcases hp with ⟨g, hg, g', hg', he⟩, use g ∪ g', rw mem_into_funs,
refine ⟨union_fun_into_fun hg hg' hMN, _⟩, rw he, congr,
{ symmetry, rw ←hg.right.left, apply restrict_union_eq hg.left.left, rw [hg.right.left, hg'.right.left], exact hMN, },
{ symmetry, rw [←hg'.right.left, union_comm], apply restrict_union_eq hg'.left.left, rw [hg.right.left, hg'.right.left], rw inter_comm, exact hMN, },
have hoto : f.one_to_one, apply pair_sep_eq_oto, intros g hg g' hg' he, simp only [mem_into_funs] at hg hg',
apply fun_ext hg.left hg'.left,
{ rw [hg.right.left, hg'.right.left], },
intros i hi, rw [hg.right.left, mem_union] at hi, cases hi,
{ have hs : M' ⊆ g.dom, rw hg.right.left, exact subset_union_left,
have hs' : M' ⊆ g'.dom, rw hg'.right.left, exact subset_union_left,
rw ←@restrict_fun_value _ hg.left M' hs _ hi,
rw ←@restrict_fun_value _ hg'.left M' hs' _ hi,
rw (pair_inj he).left, },
{ have hs : N' ⊆ g.dom, rw hg.right.left, exact subset_union_right,
have hs' : N' ⊆ g'.dom, rw hg'.right.left, exact subset_union_right,
rw ←@restrict_fun_value _ hg.left N' hs _ hi,
rw ←@restrict_fun_value _ hg'.left N' hs' _ hi,
rw (pair_inj he).right, },
exact ⟨_, ⟨hfun, hdom, hran⟩, hoto⟩,
end
-- theorem 6I part 6
theorem card_exp_exp {κ : Set.{u}} (hκ : κ.is_cardinal) {μ : Set.{u}} (hμ : μ.is_cardinal) {ν : Set.{u}} (hν : ν.is_cardinal) :
(κ.card_exp μ).card_exp ν = κ.card_exp (μ.card_mul ν) :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rcases hν with ⟨N, hN⟩,
rw [←card_exp_spec hK hM, ←card_exp_spec rfl hN, ←card_mul_spec hM hN, ←card_exp_spec hK rfl, card_equiv],
let H : Set.{u} := pair_sep_eq (N.into_funs (M.into_funs K)) ((M.prod N).into_funs K) (λ f, pair_sep_eq (M.prod N) K (λ z, (f.fun_value z.snd).fun_value z.fst)),
refine ⟨H, ⟨pair_sep_eq_is_fun, pair_sep_eq_dom_eq _, pair_sep_eq_ran_eq _⟩, pair_sep_eq_oto _⟩,
{ intros f hf, rw mem_into_funs at *, dsimp, apply pair_sep_eq_into, intros z hz, rw mem_prod at hz,
rcases hz with ⟨m, hm, n, hn, he⟩, subst he, rw [fst_congr, snd_congr],
have hfn : (f.fun_value n).into_fun M K, rw ←mem_into_funs, apply hf.right.right,
apply fun_value_def'' hf.left, rw hf.right.left, exact hn,
apply hfn.right.right, apply fun_value_def'' hfn.left, rw hfn.right.left, exact hm, },
{ intros f hf, dsimp,
use pair_sep_eq N (M.into_funs K) (λ n, pair_sep_eq M K (λ m, f.fun_value (m.pair n))), split,
{ rw mem_into_funs, apply pair_sep_eq_into, intros n hn, rw mem_into_funs, apply pair_sep_eq_into,
intros m hm, rw mem_into_funs at hf, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], exact ⟨hm, hn⟩, },
{ rw mem_into_funs at hf, apply fun_ext hf.left pair_sep_eq_is_fun,
{ rw hf.right.left, symmetry, apply pair_sep_eq_dom_eq, intros z hz, rw mem_prod at hz, dsimp,
obtain ⟨a, aM, b, bN, zab⟩ := hz, subst zab, simp only [fst_congr, snd_congr],
have dom : (N.pair_sep_eq (M.into_funs K) (λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).dom = N,
apply pair_sep_eq_dom_eq, intros n nN, rw mem_into_funs, dsimp, apply pair_sep_eq_into,
intros m mM, apply hf.right.right, apply fun_value_def'' hf.left, rw [hf.right.left, pair_mem_prod],
exact ⟨mM, nN⟩,
rw ←dom at bN, rw pair_sep_eq_fun_value bN, dsimp,
have dom' : (M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair b))).dom = M,
apply pair_sep_eq_dom_eq, intros m mM, dsimp, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], rw dom at bN, exact ⟨mM, bN⟩,
rw ←dom' at aM, rw pair_sep_eq_fun_value aM, dsimp, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], rw dom at bN, rw dom' at aM, exact ⟨aM, bN⟩, },
{ intros z hz,
have hz' : z ∈ (pair_sep_eq (M.prod N) K (λ (z : Set),
((N.pair_sep_eq (M.into_funs K)
(λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).fun_value
z.snd).fun_value
z.fst)).dom,
have hd : (pair_sep_eq (M.prod N) K (λ (z : Set),
((N.pair_sep_eq (M.into_funs K)
(λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).fun_value
z.snd).fun_value
z.fst)).dom = (M.prod N),
apply pair_sep_eq_dom_eq, intros z hz, rw mem_prod at hz, dsimp,
obtain ⟨a, aM, b, bN, zab⟩ := hz, subst zab, simp only [snd_congr, fst_congr],
have dom : (N.pair_sep_eq (M.into_funs K) (λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).dom = N,
apply pair_sep_eq_dom_eq, intros n nN, rw mem_into_funs, dsimp, apply pair_sep_eq_into,
intros m mM, apply hf.right.right, apply fun_value_def'' hf.left, rw [hf.right.left, pair_mem_prod],
exact ⟨mM, nN⟩,
rw ←dom at bN, rw pair_sep_eq_fun_value bN, dsimp,
have dom' : (M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair b))).dom = M,
apply pair_sep_eq_dom_eq, intros m mM, dsimp, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], rw dom at bN, exact ⟨mM, bN⟩,
rw ←dom' at aM, rw pair_sep_eq_fun_value aM, dsimp, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], rw dom at bN, rw dom' at aM, exact ⟨aM, bN⟩,
rw hd, rw hf.right.left at hz, exact hz,
change f.fun_value z = (pair_sep_eq (M.prod N) K (λ (z : Set),
((N.pair_sep_eq (M.into_funs K)
(λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).fun_value
z.snd).fun_value
z.fst)).fun_value z,
rw pair_sep_eq_fun_value hz', rw [hf.right.left, mem_prod] at hz, rcases hz with ⟨m, hm, n, hn, he⟩, subst he,
dsimp, rw [fst_congr, snd_congr],
have hfn : n ∈ (pair_sep_eq N (M.into_funs K) (λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).dom,
have hd : (pair_sep_eq N (M.into_funs K) (λ (n : Set), M.pair_sep_eq K (λ (m : Set), f.fun_value (m.pair n)))).dom = N,
apply pair_sep_eq_dom_eq, intros n' hn', rw mem_into_funs, apply pair_sep_eq_into,
intros m' hm', apply hf.right.right, apply fun_value_def'' hf.left, rw [hf.right.left, pair_mem_prod], exact ⟨hm', hn'⟩,
rw hd, exact hn,
rw pair_sep_eq_fun_value hfn, dsimp,
have hfm : m ∈ (pair_sep_eq M K (λ (m : Set), f.fun_value (m.pair n))).dom,
have hd : (pair_sep_eq M K (λ (m : Set), f.fun_value (m.pair n))).dom = M,
apply pair_sep_eq_dom_eq, intros m' hm', dsimp, apply hf.right.right, apply fun_value_def'' hf.left,
rw [hf.right.left, pair_mem_prod], exact ⟨hm', hn⟩,
rw hd, exact hm,
rw pair_sep_eq_fun_value hfm, }, }, },
{ simp only [mem_into_funs], intros f hf g hg he, apply fun_ext hf.left hg.left,
{ rw [hf.right.left, hg.right.left], },
{ intros n hn,
have hf' : (f.fun_value n).into_fun M K, rw ←mem_into_funs, exact hf.right.right (fun_value_def'' hf.left hn),
have hg' : (g.fun_value n).into_fun M K, rw ←mem_into_funs, refine hg.right.right (fun_value_def'' hg.left _),
rw [hg.right.left, ←hf.right.left], exact hn,
apply fun_ext hf'.left hg'.left,
rw [hf'.right.left, hg'.right.left],
intros m hm,
have hf'' : (pair_sep_eq (M.prod N) K (λ (z : Set), (f.fun_value z.snd).fun_value z.fst)).fun_value (m.pair n)
= (f.fun_value (m.pair n).snd).fun_value (m.pair n).fst,
apply pair_sep_eq_fun_value,
have hd : (pair_sep_eq (M.prod N) K (λ (z : Set), (f.fun_value z.snd).fun_value z.fst)).dom = (M.prod N),
apply pair_sep_eq_dom_eq, intros z hz, dsimp, rw mem_prod at hz, rcases hz with ⟨m, hm, n', hn', he⟩, subst he,
rw [fst_congr, snd_congr],
have hfn' : (f.fun_value n').into_fun M K, rw ←mem_into_funs, refine hf.right.right (fun_value_def'' hf.left _),
rw hf.right.left, exact hn',
apply hfn'.right.right, apply fun_value_def'' hfn'.left, rw hfn'.right.left, exact hm,
rw [hd, pair_mem_prod], rw hf.right.left at hn, rw hf'.right.left at hm, exact ⟨hm, hn⟩,
have hg'' : (pair_sep_eq (M.prod N) K (λ (z : Set), (g.fun_value z.snd).fun_value z.fst)).fun_value (m.pair n)
= (g.fun_value (m.pair n).snd).fun_value (m.pair n).fst,
apply pair_sep_eq_fun_value,
have hd : (pair_sep_eq (M.prod N) K (λ (z : Set), (g.fun_value z.snd).fun_value z.fst)).dom = (M.prod N),
apply pair_sep_eq_dom_eq, intros z hz, dsimp, rw mem_prod at hz, rcases hz with ⟨m, hm, n', hn', he⟩, subst he,
rw [fst_congr, snd_congr],
have hgn' : (g.fun_value n').into_fun M K, rw ←mem_into_funs, refine hg.right.right (fun_value_def'' hg.left _),
rw hg.right.left, exact hn',
apply hgn'.right.right, apply fun_value_def'' hgn'.left, rw hgn'.right.left, exact hm,
rw [hd, pair_mem_prod], rw hf.right.left at hn, rw hf'.right.left at hm, exact ⟨hm, hn⟩,
rw [fst_congr, snd_congr] at hf'' hg'',
rw [←hf'', ←hg'', he], }, },
end
theorem one_card_mul_eq_self {κ : Set} (hκ : κ.is_cardinal) : one.card_mul κ = κ :=
begin
rw card_mul_comm (nat_is_cardinal one_nat) hκ, exact card_mul_one_eq_self hκ,
end
lemma card_add_empty {κ : Set} (hκ : κ.is_cardinal) : κ.card_add ∅ = κ :=
begin
rcases hκ with ⟨K, hK⟩,
rw ←card_add_spec hK (card_nat zero_nat) inter_empty, rw union_empty, exact hK,
end
lemma card_empty_add {κ : Set} (hκ : κ.is_cardinal) : card_add ∅ κ = κ :=
begin
rw card_add_comm (nat_is_cardinal zero_nat) hκ, exact card_add_empty hκ,
end
lemma T6J_a2 {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : κ.card_add (μ.card_add one) = (κ.card_add μ).card_add one :=
card_add_assoc hκ hμ (nat_is_cardinal one_nat)
lemma card_mul_empty {κ : Set} (hκ : κ.is_cardinal) : κ.card_mul ∅ = ∅ :=
begin
rcases hκ with ⟨K, hK⟩,
rw ←card_mul_spec hK (card_nat zero_nat), rw prod_empty_eq_empty, exact card_nat zero_nat,
end
lemma T6J_m2 {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : κ.card_mul (μ.card_add one) = (κ.card_mul μ).card_add κ :=
begin
rw card_mul_add hκ hμ (nat_is_cardinal one_nat), congr,
rcases hκ with ⟨K, hK⟩, rw ←card_mul_spec hK (card_nat one_nat), rw ←hK,
rw [one, succ, union_empty], exact same_card,
end
lemma card_exp_empty {κ : Set} (hκ : κ.is_cardinal) : κ.card_exp ∅ = one :=
begin
rcases hκ with ⟨K, hK⟩, rw ←card_exp_spec hK (card_nat zero_nat), rw ex2,
have h : {∅} = one, rw [one, succ, union_empty],
rw h, exact card_nat one_nat,
end
--set_option pp.notation false
lemma T6J_e2 {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : κ.card_exp (μ.card_add one) = (κ.card_exp μ).card_mul κ :=
begin
rw card_exp_add hκ hμ (nat_is_cardinal one_nat), congr,
rcases hκ with ⟨K, hK⟩, rw [←card_exp_spec hK (card_nat one_nat), ←hK, card_equiv],
let f : Set := pair_sep_eq (one.into_funs K) K (λ g, g.fun_value ∅),
have hfun : f.is_function := pair_sep_eq_is_fun,
have hdom : f.dom = one.into_funs K, apply pair_sep_eq_dom_eq,
intros g hg, rw mem_into_funs at hg, apply hg.right.right, apply fun_value_def'' hg.left, rw [hg.right.left, one], exact self_mem_succ,
have hran : f.ran = K, apply pair_sep_eq_ran_eq, intros x hx, use {(∅ : Set).pair x}, rw mem_into_funs,
rw [one, succ, union_empty], refine ⟨single_pair_into hx, _⟩,
symmetry, exact single_pair_fun_value,
have hoto : f.one_to_one, apply pair_sep_eq_oto, intros g hg g' hg' he, rw Set.mem_into_funs at hg hg',
apply fun_ext hg.left hg'.left,
rw [hg.right.left, hg'.right.left],
intros x hx, rw [hg.right.left, one, succ, union_empty, mem_singleton] at hx, rw hx, exact he,
exact ⟨_, ⟨hfun, hdom, hran⟩, hoto⟩,
end
lemma card_singleton {x : Set} : card {x} = one :=
begin
rw [←card_nat one_nat, card_equiv, one, succ, union_empty],
exact singleton_equin,
end
lemma card_insert {A x : Set} (xA : x ∉ A) : (insert x A).card = A.card.card_add one :=
begin
have h : insert x A = {x} ∪ A,
simp only [←ext_iff, mem_insert, mem_union, mem_singleton, forall_const, iff_self],
rw [h, union_comm], apply card_add_spec rfl card_singleton, rw eq_empty,
intros z zAx, rw [mem_inter, mem_singleton] at zAx, rcases zAx with ⟨zA, zx⟩, subst zx,
exact xA zA,
end
lemma card_add_one_eq_succ {n : Set} (hn : n.finite_cardinal) : n.card_add one = n.succ :=
begin
rcases hn with ⟨N, hf, hN⟩, have hn := (card_finite hf).left, rw hN at hn,
have h : card {n} = one, rw [←card_nat one_nat, card_equiv, one, succ, union_empty], exact singleton_equin,
rw [←card_add_spec (card_nat hn) h, union_comm, ←succ],
exact card_nat (nat_induct.succ_closed hn),
simp only [eq_empty, mem_inter, mem_singleton],
rintros k ⟨hk, he⟩, rw he at hk, exact nat_not_mem_self hn hk,
end
-- Theorem 6J
theorem card_add_eq_ord_add {m : Set} (hm : m.finite_cardinal) {n : Set} (hn : n.finite_cardinal) : m.card_add n = m + n :=
begin
rw finite_cardinal_iff_nat at hm hn, revert n, apply induction,
rw [card_add_empty (nat_is_cardinal hm), add_base hm],
intros k hk hi,
have hk' : k.finite_cardinal, rw finite_cardinal_iff_nat, exact hk,
nth_rewrite 0 ←card_add_one_eq_succ hk',
rw [T6J_a2 (nat_is_cardinal hm) (nat_is_cardinal hk), hi],
have hmk : (m + k).finite_cardinal, rw finite_cardinal_iff_nat, exact add_into_nat hm hk,
rw [card_add_one_eq_succ hmk, add_ind hm hk],
end
lemma eq_union_of_card_succ {A n : Set} (nω : n ∈ ω) (Acard : A.card = n.succ) : ∃ B x : Set, A = B ∪ {x} ∧ B.card = n ∧ x ∈ A ∧ x ∉ B :=
begin
have Ane : A ≠ ∅, intro Ae, subst Ae,
rw [card_nat zero_nat] at Acard, exact succ_neq_empty Acard.symm,
obtain ⟨x, xA⟩ := inhabited_of_ne_empty Ane,
refine ⟨A \ {x}, x, (diff_singleton_union_eq xA).symm, _, xA, _⟩,
have Afin : A.is_finite, rw finite_iff, exact ⟨_, nat_induct.succ_closed nω, Acard⟩,
have fin : (A \ {x}).is_finite := subset_finite_of_finite Afin subset_diff,
rw finite_iff at fin, rcases fin with ⟨m, mω, Axm⟩, rw Axm,
apply cancel_add_right mω nω one_nat,
have onefin : one.finite_cardinal, rw finite_cardinal_iff_nat, exact one_nat,
have nfin : n.finite_cardinal, rw finite_cardinal_iff_nat, exact nω,
have mfin : m.finite_cardinal, rw finite_cardinal_iff_nat, exact mω,
rw [←card_add_eq_ord_add mfin onefin, ←card_add_eq_ord_add nfin onefin, card_add_one_eq_succ nfin],
rw [←Axm, ←@card_singleton x, card_add_comm ⟨_, rfl⟩ ⟨_, rfl⟩, ←card_add_spec rfl rfl self_inter_diff_empty],
rw [union_comm, diff_singleton_union_eq xA, Acard],
intro xAx, rw [mem_diff, mem_singleton] at xAx, exact xAx.right rfl,
end
theorem card_mul_eq_ord_mul {m : Set} (hm : m.finite_cardinal) {n : Set} (hn : n.finite_cardinal) : m.card_mul n = m * n :=
begin
rw finite_cardinal_iff_nat at hm hn, revert n, apply induction,
rw [card_mul_empty (nat_is_cardinal hm), mul_base hm],
intros k hk hi,
have hm' : m.finite_cardinal, rw finite_cardinal_iff_nat, exact hm,
have hk' : k.finite_cardinal, rw finite_cardinal_iff_nat, exact hk,
nth_rewrite 0 ←card_add_one_eq_succ hk',
rw [T6J_m2 (nat_is_cardinal hm) (nat_is_cardinal hk), hi],
have hmk : (m * k).finite_cardinal, rw finite_cardinal_iff_nat, exact mul_into_nat hm hk,
rw [card_add_eq_ord_add hmk hm', mul_ind hm hk],
end
theorem card_exp_eq_ord_exp {m : Set} (hm : m.finite_cardinal) {n : Set} (hn : n.finite_cardinal) : m.card_exp n = m ^ n :=
begin
rw finite_cardinal_iff_nat at hm hn, revert n, apply induction,
rw [card_exp_empty (nat_is_cardinal hm), exp_base hm],
intros k hk hi,
have hm' : m.finite_cardinal, rw finite_cardinal_iff_nat, exact hm,
have hk' : k.finite_cardinal, rw finite_cardinal_iff_nat, exact hk,
nth_rewrite 0 ←card_add_one_eq_succ hk',
rw [T6J_e2 (nat_is_cardinal hm) (nat_is_cardinal hk), hi],
have hmk : (m ^ k).finite_cardinal, rw finite_cardinal_iff_nat, exact exp_into_nat hm hk,
rw [card_mul_eq_ord_mul hmk hm', exp_ind hm hk],
end
lemma card_mul_fin_of_fin {κ : Set} (κfin : κ.finite_cardinal) {μ : Set} (μfin : μ.finite_cardinal) : (κ.card_mul μ).finite_cardinal :=
begin
rw [finite_cardinal_iff_nat, card_mul_eq_ord_mul κfin μfin],
rw finite_cardinal_iff_nat at κfin μfin, exact mul_into_nat κfin μfin,
end
-- example 8, page 142
theorem card_add_self_eq_two_mul_self {κ : Set} (hκ : κ.is_cardinal) : κ.card_add κ = two.card_mul κ :=
begin
rw [card_mul_comm (nat_is_cardinal two_nat) hκ, two, succ_eq_add_one one_nat],
have one_fin : one.finite_cardinal, rw finite_cardinal_iff_nat, exact one_nat,
rw [←card_add_eq_ord_add one_fin one_fin, card_mul_add hκ (nat_is_cardinal one_nat) (nat_is_cardinal one_nat)],
rw [card_mul_one_eq_self hκ],
end
-- Corollary 6K
theorem union_finite_of_finite {A : Set} (hA : A.is_finite) {B : Set} (hB : B.is_finite) : (A ∪ B).is_finite :=
begin
rw union_eq_union_diff,
have hB' : (B \ A).is_finite := subset_finite_of_finite hB subset_diff,
have hdisj : A ∩ (B \ A) = ∅ := self_inter_diff_empty,
rw finite_iff at *, rcases hA with ⟨n, hn, hA⟩, rcases hB' with ⟨m, hm, hB'⟩, refine ⟨n + m, add_into_nat hn hm, _⟩,
rw card_add_spec hA hB' hdisj, apply card_add_eq_ord_add,
rw finite_cardinal_iff_nat, exact hn,
rw finite_cardinal_iff_nat, exact hm,
end
theorem prod_finite_of_finite {A : Set} (hA : A.is_finite) {B : Set} (hB : B.is_finite) : (A.prod B).is_finite :=
begin
rw finite_iff at *, rcases hA with ⟨n, hn, hA⟩, rcases hB with ⟨m, hm, hB⟩, refine ⟨n * m, mul_into_nat hn hm, _⟩,
rw card_mul_spec hA hB, apply card_mul_eq_ord_mul,
rw finite_cardinal_iff_nat, exact hn,
rw finite_cardinal_iff_nat, exact hm,
end
theorem into_funs_finite_of_finite {A : Set} (hA : A.is_finite) {B : Set} (hB : B.is_finite) : (B.into_funs A).is_finite :=
begin
rw finite_iff at *, rcases hA with ⟨n, hn, hA⟩, rcases hB with ⟨m, hm, hB⟩, refine ⟨n ^ m, exp_into_nat hn hm, _⟩,
rw card_exp_spec hA hB, apply card_exp_eq_ord_exp,
rw finite_cardinal_iff_nat, exact hn,
rw finite_cardinal_iff_nat, exact hm,
end
lemma dominates_self {A : Set} : A ≼ A := ⟨A.id, id_into, id_oto⟩
lemma dominated_sub {A B : Set} (h : A ⊆ B) : A ≼ B := ⟨A.id, into_of_into_ran_sub h id_into, id_oto⟩
lemma dominated_of_equin_of_dominated {K₁ K₂ : Set} (hK : K₂.equinumerous K₁) {L₁ L₂ : Set} (hL : L₁.equinumerous L₂) (h : K₁ ≼ L₁) : (K₂ ≼ L₂) :=
begin
rcases hK with ⟨F, Fonto, Foto⟩, rcases hL with ⟨G, Gonto, Goto⟩, rcases h with ⟨D, Dinto, Doto⟩,
let H : Set := G.comp (D.comp F),
exact ⟨H, comp_into_fun (comp_into_fun (into_of_onto Fonto) Dinto) (into_of_onto Gonto),
comp_one_to_one Goto (comp_one_to_one Doto Foto)⟩,
end
lemma dominated_iff_equin {K₁ K₂ : Set} (hK : K₁.equinumerous K₂) {L₁ L₂ : Set} (hL : L₁.equinumerous L₂) : K₁ ≼ L₁ ↔ K₂ ≼ L₂ :=
⟨λ h, dominated_of_equin_of_dominated (equin_symm hK) hL h, λ h, dominated_of_equin_of_dominated hK (equin_symm hL) h⟩
def card_le (κ μ : Set) : Prop := ∀ ⦃K : Set⦄, K.card = κ → ∀ ⦃M : Set⦄, M.card = μ → K ≼ M
lemma card_le_iff_equin {κ K : Set} (hK : K.card = κ) {μ M : Set} (hM : M.card = μ) : κ.card_le μ ↔ K ≼ M :=
begin
split,
{ intro h, exact h hK hM, },
{ intros h K' hK' M' hM', apply dominated_of_equin_of_dominated _ _ h,
rw [←card_equiv, hK, hK'],
rw [←card_equiv, hM, hM'], },
end
lemma card_le_iff_equin' {K L : Set} : K.card.card_le L.card ↔ K ≼ L :=
⟨λ h, (card_le_iff_equin rfl rfl).mp h, λ h, (card_le_iff_equin rfl rfl).mpr h⟩
def card_lt (κ μ : Set) : Prop := κ.card_le μ ∧ κ ≠ μ
lemma card_lt_iff {K L : Set} : K.card.card_lt L.card ↔ K ≼ L ∧ K ≉ L :=
by simp only [card_lt, card_le_iff_equin', ←card_equiv]
lemma card_le_iff {κ μ : Set} : κ.card_le μ ↔ κ.card_lt μ ∨ κ = μ :=
begin
let P : Prop := κ = μ,
rw [card_lt, and_or_distrib_right, or_comm (¬ P) _, (iff_true (P ∨ ¬P)).mpr (classical.em P), and_true], split,
intro h, exact or.inl h,
rintro (h|h),
exact h,
intros K hK M hM, rw [←hK, ←hM] at h, rw dominated_iff, use M, refine ⟨subset_self, _⟩,
rw ←card_equiv, exact h,
end
lemma card_le_of_subset {A B : Set} (hAB : A ⊆ B) : A.card.card_le B.card :=
begin
rw card_le_iff_equin rfl rfl, exact ⟨A.id, into_of_into_ran_sub hAB id_into, id_oto⟩,
end
lemma exists_sets_of_card_le {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (h : κ.card_le μ) :
∃ K M : Set, K ⊆ M ∧ K.card = κ ∧ M.card = μ :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩,
have hd : K ≼ M, rw [←card_le_iff_equin rfl rfl, hK, hM], exact h,
rcases hd with ⟨f, finto, foto⟩,
refine ⟨f.ran, M, finto.right.right, _, hM⟩,
rw [←hK, card_equiv], apply equin_symm, exact ⟨f, ⟨finto.left, finto.right.left, rfl⟩, foto⟩,
end
lemma exists_equin_subset_of_dominated {A B : Set} (h : A ≼ B) : ∃ K : Set, K ⊆ B ∧ K ≈ A :=
begin
rcases h with ⟨f, finto, foto⟩,
exact ⟨f.ran, finto.right.right, equin_symm ⟨f, ⟨finto.left, finto.right.left, rfl⟩, foto⟩⟩,
end
lemma finite_of_dominated_by_finite {B : Set} (hB : B.is_finite) {A : Set} (hAB : A ≼ B) : A.is_finite :=
begin
obtain ⟨K, hKB, hKA⟩ := exists_equin_subset_of_dominated hAB,
exact finite_of_equin_finite (subset_finite_of_finite hB hKB) hKA,
end
lemma infinite_of_dominates_infinite {A : Set} (hA : ¬ A.is_finite) {B : Set} (hAB : A ≼ B) : ¬ B.is_finite :=
begin
intro hfin, apply hA, exact finite_of_dominated_by_finite hfin hAB,
end
local attribute [instance] classical.prop_decidable
lemma zero_card_le {κ : Set} (hκ : κ.is_cardinal) : card_le ∅ κ :=
begin
rcases hκ with ⟨K, hK⟩, rw [←hK, ←card_nat zero_nat], apply card_le_of_subset,
intros z hz, exfalso, exact mem_empty _ hz,
end
lemma finite_card_lt_aleph_null {n : Set} (hn : n.finite_cardinal) : n.card_lt (card ω) :=
begin
rw finite_cardinal_iff_nat at hn, rw [←card_nat hn, card_lt], split,
apply card_le_of_subset, exact subset_nat_of_mem_nat hn,
intro h, apply nat_infinite, rw card_equiv at h, exact ⟨_, hn, equin_symm h⟩,
end
lemma finite_card_lt_aleph_null' {X : Set} (Xfin : X.is_finite) : X.card.card_lt (card ω) :=
finite_card_lt_aleph_null ⟨_, Xfin, rfl⟩
lemma finite_card_le_iff_le {m : Set} (hm : m.finite_cardinal) {n : Set} (hn : n.finite_cardinal) : m.card_le n ↔ m ≤ n :=
begin
split,
{ intro h,
rw finite_cardinal_iff_nat at hn hm,
rw [←card_nat hm, ←card_nat hn, card_le_iff_equin'] at h,
apply le_of_not_lt hn hm, intro hnm, rw ←nat_ssub_iff_mem hn hm at hnm,
rcases h with ⟨f, finto, foto⟩,
exact pigeonhole'' (ssub_of_sub_of_ssub finto.right.right hnm) ⟨f, onto_ran_of_into finto, foto⟩ (nat_finite hm), },
{ intro h,
rw finite_cardinal_iff_nat at hn hm,
rw ←nat_sub_iff_le hm hn at h,
rw [←card_nat hm, ←card_nat hn],
exact card_le_of_subset h, },
end
lemma finite_card_lt_iff_lt {m : Set} (hm : m.finite_cardinal) {n : Set.{u}} (hn : n.finite_cardinal) : m.card_lt n ↔ m ∈ n :=
begin
have nω : n ∈ nat.{u}, rwa ←finite_cardinal_iff_nat,
simp only [lt_iff' nω, card_lt], exact and_congr_left' (finite_card_le_iff_le hm hn),
end
lemma card_lt_exp {κ : Set} (hκ : κ.is_cardinal) : card_lt κ (card_exp two κ) :=
begin
rcases hκ with ⟨K, hK⟩, rw [←hK, ←card_power, card_lt_iff], split,
let f := pair_sep_eq K K.powerset (λ x, {x}),
have finto : f.into_fun K K.powerset, apply pair_sep_eq_into, intros x hx,
simp only [mem_powerset], intros z hz, rw mem_singleton at hz, rw hz, exact hx,
have foto : f.one_to_one, apply pair_sep_eq_oto, intros x hx x' hx' he,
rw ←ext_iff at he, simp only [mem_singleton] at he, specialize he x, rw ←he,
exact ⟨f, finto, foto⟩,
exact not_equin_powerset,
end
lemma card_le_refl {κ : Set} : κ.card_le κ :=
begin
intros K hK M hM, rw [←hM, card_equiv] at hK, rw dominated_iff, exact ⟨_, subset_self, hK⟩,
end
lemma card_le_trans {κ μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ) {ν : Set} (hμν : μ.card_le ν) : κ.card_le ν :=
begin
rcases hμ with ⟨M, hM⟩, intros K hK N hN, specialize hκμ hK hM, specialize hμν hM hN,
rcases hκμ with ⟨f, finto, foto⟩, rcases hμν with ⟨g, ginto, goto⟩,
exact ⟨g.comp f, comp_into_fun finto ginto, comp_one_to_one goto foto⟩,
end
-- Schröer-Bernstein Theorem part a
lemma equin_of_dom_of_dom {A B : Set} (hAB : A ≼ B) (hBA : B ≼ A) : A ≈ B :=
begin
rcases hAB with ⟨f, finto, foto⟩, rcases hBA with ⟨g, ginto, goto⟩,
let C : ℕ → Set := @nat.rec (λ n, Set) (A \ g.ran) (λ _ C, g.img (f.img C)),
have hnz : ∀ {x}, x ∈ A → ¬ (∃ n, x ∈ C n) → x ∈ g.ran, intros x hx hc,
have hnz : x ∉ A \ g.ran, intro hz, exact hc ⟨0, hz⟩,
rw [mem_diff] at hnz, apply by_contradiction, intro hngr, exact hnz ⟨hx, hngr⟩,
have Csub : ∀ {n}, C n ⊆ A, intro n, induction n with n ih,
{ exact subset_diff, },
{ exact subset_trans img_subset_ran ginto.right.right, },
let h' : Set → Set := (λ x, if ∃ n, x ∈ C n then f.fun_value x else g.inv.fun_value x),
let h := pair_sep_eq A B h',
have hfun := pair_sep_eq_is_fun,
have hdom : h.dom = A, apply pair_sep_eq_dom_eq, intros x hx,
by_cases hc : ∃ n, x ∈ C n,
{ dsimp [h'], simp only [hc, if_true], apply finto.right.right, apply fun_value_def'' finto.left,
rw finto.right.left, exact hx, },
{ dsimp [h'], simp only [hc, if_false, ←ginto.right.left, ←T3E_b],
apply fun_value_def'',
rw T3F_a, exact goto,
rw T3E_a, exact hnz hx hc, },
have hoto : h.one_to_one, apply pair_sep_eq_oto,
have hb : ∀ {x}, x ∈ A → (∃ n, x ∈ C n) → ∀ {x'}, x' ∈ A → (¬ ∃ n, x' ∈ C n) → h' x = h' x' → x = x',
intros x hx hc x' hx' hc' he,
dsimp [h'] at he, simp only [hc, hc', if_true, if_false] at he,
rcases hc with ⟨n, hc⟩,
have hf : f.fun_value x ∈ f.img (C n), refine fun_value_mem_img finto.left _ hc,
rw finto.right.left, exact Csub,
rw he at hf, rw mem_img' finto.left at hf, rcases hf with ⟨x'', hc'', he'⟩,
have he'' : g.fun_value (g.inv.fun_value x') = g.fun_value (f.fun_value x''), rw he',
rw ←T3H_c ginto.left (T3F_a.mpr goto) at he'', rw eq_inv_id ginto.left goto at he'',
rw id_value (hnz hx' hc') at he'', exfalso, apply hc', use n.succ,
have h' : f.img (C n) ⊆ g.dom, rw ginto.right.left, exact subset_trans img_subset_ran finto.right.right,
have h'' : C n ⊆ f.dom, rw finto.right.left, exact Csub,
simp only [mem_img' ginto.left h', mem_img' finto.left h''],
refine ⟨f.fun_value x'', ⟨_, hc'', rfl⟩, he''⟩,
have h''' : g.inv.ran ⊆ g.dom, rw [T3E_b, ginto.right.left], exact subset_self,
rw [dom_comp h''', T3E_a], exact hnz hx' hc',
rw finto.right.left, exact Csub,
intros x hx x' hx' he,
by_cases hc : (∃ n, x ∈ C n);
by_cases hc' : ∃ n, x' ∈ C n,
{ dsimp [h'] at he, simp only [hc, hc', if_true] at he, rw [←finto.right.left] at hx hx',
exact from_one_to_one finto.left foto hx hx' he, },
{ exact hb hx hc hx' hc' he, },
{ symmetry, exact hb hx' hc' hx hc he.symm, },
{ dsimp [h'] at he, simp only [hc, hc', if_false] at he,
apply from_one_to_one (T3F_a.mpr goto) ((T3F_b ginto.left.left).mp ginto.left),
rw T3E_a, exact hnz hx hc,
rw T3E_a, exact hnz hx' hc',
exact he, },
have hran : h.ran = B, apply pair_sep_eq_ran_eq, intros y hy,
by_cases hc : ∃ n, y ∈ f.img (C n),
{ rcases hc with ⟨n, hc⟩,
have Csub' : C n ⊆ f.dom, rw finto.right.left, exact Csub,
simp only [mem_img' finto.left Csub'] at hc,
rcases hc with ⟨x, hx, hc⟩, refine ⟨x, Csub hx, _⟩,
dsimp [h'], simp only [exists.intro n hx, if_true], exact hc, },
{ refine ⟨g.fun_value y, _, _⟩,
apply ginto.right.right, apply fun_value_def'' ginto.left, rw ginto.right.left, exact hy,
have hne : ¬ ∃ n, g.fun_value y ∈ C n, rintro ⟨n, hn⟩,
cases n with n,
rw mem_diff at hn, apply hn.right, apply fun_value_def'' ginto.left, rw ginto.right.left, exact hy,
have hfimg : f.img (C n) ⊆ g.dom, rw ginto.right.left, exact subset_trans img_subset_ran finto.right.right,
rw mem_img' ginto.left hfimg at hn, rcases hn with ⟨y', hy', he⟩, apply hc, use n,
suffices he' : y = y',
rw he', exact hy',
refine from_one_to_one ginto.left goto _ _ he,
rw ginto.right.left, exact hy,
rw ginto.right.left, exact (subset_trans img_subset_ran finto.right.right) hy',
dsimp [h'], simp only [hne, if_false],
rw [←T3H_c (T3F_a.mpr goto) ginto.left, eq_id ginto.left goto, ginto.right.left, id_value hy],
rw [dom_comp, ginto.right.left], exact hy,
rw T3E_a, exact subset_self, },
exact ⟨_, ⟨hfun, hdom, hran⟩, hoto⟩,
end
-- Schröer-Bernstein Theorem part b
lemma card_eq_of_le_of_le {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ) (hμκ : μ.card_le κ) : κ = μ :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩, rw [←hK, ←hM, card_equiv],
apply equin_of_dom_of_dom (hκμ hK hM) (hμκ hM hK),
end
lemma card_lt_trans {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_lt μ) {ν : Set} (hμν : μ.card_lt ν) : κ.card_lt ν :=
begin
rcases hκμ with ⟨κlμ, κeμ⟩, rcases hμν with ⟨μlν, μeν⟩,
refine ⟨card_le_trans hμ κlμ μlν, λ κeν, _⟩,
subst κeν, apply κeμ, exact card_eq_of_le_of_le hκ hμ κlμ μlν,
end
lemma not_card_lt_cycle {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) : ¬ (κ.card_lt μ ∧ μ.card_lt κ) :=
λ h, (card_lt_trans hκ hμ h.left h.right).right rfl
lemma card_lt_of_le_of_lt {κ : Set} (κcard : κ.is_cardinal) {μ : Set} (μcard : μ.is_cardinal) (κμ : κ.card_le μ) {ν : Set} (μν : μ.card_lt ν) : κ.card_lt ν :=
begin
rw card_le_iff at κμ, cases κμ,
exact card_lt_trans κcard μcard κμ μν,
subst κμ, exact μν,
end
-- Too lazy to do all of theorem 6L
-- Theorem 6L part a
theorem card_add_le_of_le_left {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ)
{ν : Set} (hν : ν.is_cardinal) : (κ.card_add ν).card_le (μ.card_add ν) :=
begin
rcases hκ with ⟨K, hK⟩,
rcases hμ with ⟨M, hM⟩,
rcases hν with ⟨N, hN⟩,
let M' := M.prod {∅},
let N' := N.prod {one},
have hM' : M'.card = μ, rw ←hM, exact same_card,
have hN' : N'.card = ν, rw ←hN, exact same_card,
have hdisj : M' ∩ N' = ∅ := disj zero_ne_one,
rw [←hK, ←hM', card_le_iff_equin', dominated_iff] at hκμ,
rcases hκμ with ⟨K', hKM', hK'⟩,
have hdisj' : K' ∩ N' = ∅, rw eq_empty, intros x hx, rw mem_inter at hx,
apply mem_empty x, rw ←hdisj, rw mem_inter, exact ⟨hKM' hx.left, hx.right⟩,
rw [←card_equiv, hK] at hK',
rw [←card_add_spec hK'.symm hN' hdisj', ←card_add_spec hM' hN' hdisj],
apply card_le_of_subset, apply union_subset_of_subset_of_subset,
exact subset_trans hKM' subset_union_left,
exact subset_union_right,
end
theorem card_add_le_of_le_right {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ)
{ν : Set} (hν : ν.is_cardinal) : (ν.card_add κ).card_le (ν.card_add μ) :=
begin
rw [card_add_comm hν hκ, card_add_comm hν hμ], exact card_add_le_of_le_left hκ hμ hκμ hν,
end
-- Theorem 6L part b
theorem card_mul_le_of_le_left {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ)
{ν : Set} (hν : ν.is_cardinal) : (κ.card_mul ν).card_le (μ.card_mul ν) :=
begin
obtain ⟨K, M, hKM, hK, hM⟩ := exists_sets_of_card_le hκ hμ hκμ,
rcases hν with ⟨N, hN⟩,
rw [←card_mul_spec hK hN, ←card_mul_spec hM hN],
exact card_le_of_subset (prod_subset_of_subset_of_subset hKM subset_self),
end
theorem card_mul_le_of_le_right {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ)
{ν : Set} (hν : ν.is_cardinal) : (ν.card_mul κ).card_le (ν.card_mul μ) :=
begin
rw [card_mul_comm hν hκ, card_mul_comm hν hμ], exact card_mul_le_of_le_left hκ hμ hκμ hν,
end
-- Theorem 6L part c
theorem card_exp_le_of_le {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hκμ : κ.card_le μ)
{ν : Set} (hν : ν.is_cardinal) : (κ.card_exp ν).card_le (μ.card_exp ν) :=
begin
obtain ⟨K, M, hKM, hK, hM⟩ := exists_sets_of_card_le hκ hμ hκμ,
rcases hν with ⟨N, hN⟩,
rw [←card_exp_spec hK hN, ←card_exp_spec hM hN],
apply card_le_of_subset, intros f hf, rw mem_into_funs at *,
exact ⟨hf.left, hf.right.left, subset_trans hf.right.right hKM⟩,
end
-- excercise 15
theorem not_exists_dominators : ¬ ∃ K : Set, ∀ A : Set, ∃ B : Set, B ∈ K ∧ A ≼ B :=
begin
rintro ⟨K, h⟩, apply @not_equin_powerset K.Union, apply equin_of_dom_of_dom,
rw dominated_iff_equin equin_refl powerset_equinumerous_into_funs,
rw ←card_le_iff_equin', rw card_exp_spec rfl rfl, rw card_le_iff, left,
rw card_nat two_nat, exact card_lt_exp ⟨_, rfl⟩,
specialize h K.Union.powerset, rcases h with ⟨B, hBK, hB⟩,
rw ←card_le_iff_equin', rw ←card_le_iff_equin' at hB,
refine card_le_trans ⟨_, rfl⟩ hB _,
rw card_le_iff_equin',
exact dominated_sub (subset_Union_of_mem hBK),
end
lemma Union_chain_is_function {𝓑 : Set} (hch : 𝓑.is_chain) (hf : ∀ {f : Set}, f ∈ 𝓑 → f.is_function) : 𝓑.Union.is_function :=
begin
rw is_function_iff, split,
intros b hb, rw mem_Union at hb, rcases hb with ⟨B, hB𝓑, hbB⟩, specialize hf hB𝓑,
replace hf := hf.left, exact hf _ hbB,
intros x y y' hxy hxy', simp only [mem_Union, exists_prop] at hxy hxy',
rcases hxy with ⟨Z, hZ𝓑, hxyZ⟩, rcases hxy' with ⟨Z', hZ𝓑', hxyZ'⟩,
specialize hch hZ𝓑 hZ𝓑', cases hch,
specialize hf hZ𝓑', rw is_function_iff at hf, exact hf.right _ _ _ (hch hxyZ) hxyZ',
specialize hf hZ𝓑, rw is_function_iff at hf, exact hf.right _ _ _ hxyZ (hch hxyZ'),
end
lemma Union_chain_onto {X : Set} (Xch : X.is_chain) (Xf : ∀ ⦃f : Set⦄, f ∈ X → f.is_function) :
X.Union.onto_fun (repl_img dom X).Union (repl_img ran X).Union :=
begin
refine ⟨Union_chain_is_function Xch Xf, _, _⟩,
symmetry, apply dom_Union_eq_Union_dom, intro x,
simp only [mem_Union, exists_prop, mem_repl_img, ←exists_and_distrib_right, and_assoc],
rw exists_comm, simp only [exists_and_distrib_left, exists_eq_left, and_comm],
symmetry, apply ran_Union_eq_Union_ran, intro y,
simp only [mem_Union, exists_prop, mem_repl_img, ←exists_and_distrib_right, and_assoc],
rw exists_comm, simp only [exists_and_distrib_left, exists_eq_left, and_comm],
end
lemma Union_chain_fun_value {X : Set} (Xch : X.is_chain) (Xf : ∀ ⦃f : Set⦄, f ∈ X → f.is_function)
{f : Set} (fX : f ∈ X) {x : Set} (xf : x ∈ f.dom) : X.Union.fun_value x = f.fun_value x :=
begin
symmetry, apply fun_value_def (Union_chain_is_function Xch Xf),
rw mem_Union, exact ⟨_, fX, fun_value_def' (Xf fX) xf⟩,
end
lemma Union_chain_oto {𝓑 : Set} (hch : 𝓑.is_chain) (hf : ∀ {f : Set}, f ∈ 𝓑 → f.one_to_one) : 𝓑.Union.one_to_one :=
begin
rw one_to_one_iff, intros y x x' hxy hxy', rw mem_Union at hxy hxy',
rcases hxy with ⟨B, hB𝓑, hxyB⟩, rcases hxy' with ⟨B', hB𝓑', hxyB'⟩,
specialize hch hB𝓑 hB𝓑', cases hch,
replace hB𝓑' := hf hB𝓑', rw one_to_one_iff at hB𝓑',
exact hB𝓑' (hch hxyB) hxyB',
replace hB𝓑 := hf hB𝓑, rw one_to_one_iff at hB𝓑,
exact hB𝓑 hxyB (hch hxyB'),
end
theorem choice_equiv_6_1 : Axiom_of_choice_VI.{u} → Axiom_of_choice_I.{u} :=
begin
dsimp [Axiom_of_choice_VI, Axiom_of_choice_I], intros ax6 R hR,
let 𝓐 : Set := {f ∈ R.powerset | f.is_function},
have huncl : ∀ 𝓑 : Set, 𝓑.is_chain → 𝓑 ⊆ 𝓐 → 𝓑.Union ∈ 𝓐,
intros 𝓑 hch h𝓑𝓐, simp only [mem_sep, mem_powerset], split,
apply Union_subset_of_subset_powerset, intros B hB,
have h : B ∈ 𝓐 := h𝓑𝓐 hB,
rw Set.mem_sep at h, exact h.left,
apply Union_chain_is_function hch, intros f hf, specialize h𝓑𝓐 hf, rw mem_sep at h𝓑𝓐, exact h𝓑𝓐.right,
specialize ax6 _ huncl, rcases ax6 with ⟨F, hf𝓐, hmax⟩, rw [mem_sep, mem_powerset] at hf𝓐,
refine ⟨_, hf𝓐.right, hf𝓐.left, _⟩, apply ext, intros x, split,
intro hx, rw mem_dom at *, rcases hx with ⟨y, hxy⟩, exact ⟨_, hf𝓐.left hxy⟩,
intro hx, apply classical.by_contradiction, intro hnx, rw mem_dom at hx, rcases hx with ⟨y, hxy⟩,
let F' := F ∪ {x.pair y},
apply hmax F',
rw [mem_sep, mem_powerset], split,
apply union_subset_of_subset_of_subset hf𝓐.left,
intros z hz, rw mem_singleton at hz, subst hz, exact hxy,
apply union_singleton_is_fun hf𝓐.right hnx,
intros he,
have hxyF' : x.pair y ∈ F', rw [mem_union, mem_singleton], right, refl,
rw he at hxyF', apply hnx, rw mem_dom, exact ⟨_, hxyF'⟩,
exact subset_union_left,
end
theorem choice_equiv_6_5 : Axiom_of_choice_VI.{u} → Axiom_of_choice_V.{u} :=
begin
dsimp [Axiom_of_choice_VI, Axiom_of_choice_V], intros ax6 C D,
let 𝓐 : Set := {f ∈ (C.prod D).powerset | f.is_function ∧ f.one_to_one},
have h𝓐 : ∀ {f}, f ∈ 𝓐 ↔ f ⊆ C.prod D ∧ f.is_function ∧ f.one_to_one,
simp only [mem_sep, mem_powerset, iff_self, implies_true_iff],
have h𝓐' : ∀ {f : Set}, f ∈ 𝓐 → f.dom ⊆ C ∧ f.ran ⊆ D, intros f hf, rw h𝓐 at hf, split,
intros x hx, rw mem_dom at hx, rcases hx with ⟨y, hxy⟩,
have hxy' : x.pair y ∈ C.prod D := hf.left hxy,
rw pair_mem_prod at hxy', exact hxy'.left,
intros y hy, rw mem_ran at hy, rcases hy with ⟨x, hxy⟩,
have hxy' : x.pair y ∈ C.prod D := hf.left hxy,
rw pair_mem_prod at hxy', exact hxy'.right,
have huncl : ∀ 𝓑 : Set, 𝓑.is_chain → 𝓑 ⊆ 𝓐 → 𝓑.Union ∈ 𝓐,
intros 𝓑 hch 𝓑𝓐, rw h𝓐, split,
intros z hz, rw mem_Union at hz, rcases hz with ⟨B, hB𝓑, hzB⟩, specialize 𝓑𝓐 hB𝓑, rw h𝓐 at 𝓑𝓐,
exact 𝓑𝓐.left hzB,
split,
apply Union_chain_is_function hch, intros f hf, specialize 𝓑𝓐 hf, rw h𝓐 at 𝓑𝓐, exact 𝓑𝓐.right.left,
apply Union_chain_oto hch, intros f hf, specialize 𝓑𝓐 hf, rw h𝓐 at 𝓑𝓐, exact 𝓑𝓐.right.right,
specialize ax6 _ huncl, rcases ax6 with ⟨F, hF𝓐, hmax⟩,
specialize h𝓐' hF𝓐, rw h𝓐 at hF𝓐,
suffices h : C ⊆ F.dom ∨ D ⊆ F.ran, cases h,
left, refine ⟨_, ⟨hF𝓐.right.left, _, h𝓐'.right⟩, hF𝓐.right.right⟩,
rw eq_iff_subset_and_subset, exact ⟨h𝓐'.left, h⟩,
right, refine ⟨F.inv, ⟨_, _, _⟩, _⟩,
rw T3F_a, exact hF𝓐.right.right,
rw [T3E_a, eq_iff_subset_and_subset], exact ⟨h𝓐'.right, h⟩,
rw T3E_b, exact h𝓐'.left,
rw ←(T3F_b hF𝓐.right.left.left), exact hF𝓐.right.left,
apply classical.by_contradiction, intro hns,
simp only [not_or_distrib, subset_def, not_forall] at hns,
rcases hns with ⟨⟨c, hcC, hnc⟩, d, hdD, hnd⟩,
let F' : Set := F ∪ {c.pair d},
apply hmax F',
rw h𝓐, split,
apply union_subset_of_subset_of_subset hF𝓐.left, simp only [subset_def, mem_singleton],
intros z hz, subst hz, rw pair_mem_prod, exact ⟨hcC, hdD⟩,
split,
exact union_singleton_is_fun hF𝓐.right.left hnc,
exact union_singleton_one_to_one hF𝓐.right.right hnd,
intros he,
have hcdF' : c.pair d ∈ F', rw [mem_union, mem_singleton], right, refl,
rw he at hcdF', apply hnc, rw mem_dom, exact ⟨_, hcdF'⟩,
exact subset_union_left,
end
-- Theorem 6M completed
theorem choice_equiv_all : list.tfae [
Axiom_of_choice_I.{u},
Axiom_of_choice_II.{u},
Axiom_of_choice_III.{u},
Axiom_of_choice_IV.{u},
Axiom_of_choice_V.{u},
Axiom_of_choice_VI.{u},
WO.{u}] :=
begin
tfae_have : 1 → 2, refine list.tfae_prf choice_equiv _ _, finish, finish,
tfae_have : 2 → 4, refine list.tfae_prf choice_equiv _ _, finish, finish,
tfae_have : 4 → 3, refine list.tfae_prf choice_equiv _ _, finish, finish,
tfae_have : 3 → 1, refine list.tfae_prf choice_equiv _ _, finish, finish,
tfae_have : 6 → 1, exact choice_equiv_6_1,
tfae_have : 6 → 5, exact choice_equiv_6_5,
tfae_have : 3 → 7, exact choice_equiv_3_WO,
tfae_have : 5 → 7, exact choice_equiv_5_WO,
tfae_have : 7 → 6, exact choice_equiv_WO_6,
tfae_finish,
end
lemma ax_ch_6 : Axiom_of_choice_VI :=
begin
refine list.tfae_prf choice_equiv_all _ _ @ax_ch_3, finish, finish,
end
lemma ax_ch_5 : Axiom_of_choice_V :=
begin
refine list.tfae_prf choice_equiv_all _ _ @ax_ch_3, finish, finish,
end
lemma dominates_of_onto_fun {A B : Set} (he : ∃ f : Set, f.onto_fun A B) : B.dominated A :=
begin
rcases he with ⟨f, fonto⟩,
obtain ⟨g, ginto, hc⟩ := (T3J_b (into_of_onto fonto)).mpr fonto,
exact ⟨g, ginto, one_to_one_of_has_left_inv ginto ⟨_, into_of_onto fonto, hc⟩⟩,
end
lemma exists_onto_of_dominated {A B : Set} (hbne : B.inhab) (hd : B ≼ A) : ∃ g : Set, g.onto_fun A B :=
begin
rcases hd with ⟨f, finto, foto⟩, rw ←T3J_a finto hbne at foto,
rcases foto with ⟨g, ginto, gc⟩, use g, rw ←T3J_b ginto, exact ⟨_, finto, gc⟩,
end
lemma dominated_iff_exists_onto_fun {A B : Set} (hbne : B.inhab) : B ≼ A ↔ ∃ f : Set, f.onto_fun A B :=
⟨λ h, exists_onto_of_dominated hbne h, λ h, dominates_of_onto_fun h⟩
lemma nonempty_diff_of_finite_subset_of_inf {A : Set} (hA : ¬ A.is_finite) {B : Set} (hB : B.is_finite) (hBA : B ⊆ A) : A \ B ≠ ∅ :=
begin
intro he, simp only [eq_empty, mem_diff, not_and_distrib, ←imp_iff_not_or, not_not, ←subset_def] at he,
have he' : A = B, rw eq_iff_subset_and_subset, exact ⟨he, hBA⟩,
subst he', exact hA hB,
end
lemma singleton_finite {x : Set} : is_finite {x} :=
begin
refine ⟨one, one_nat, _⟩,
dsimp [one, succ], rw [union_empty],
exact singleton_equin,
end
-- Theorem 6N part a
theorem omega_least_infinite_set {A : Set.{u}} (hA : ¬ A.is_finite) : ω ≼ A :=
begin
let P : Set := {x ∈ A.powerset | x.is_finite},
have hP : P ⊆ A.powerset, intros x hx, rw [mem_sep] at hx, exact hx.left,
obtain ⟨F, Ffun, Fdom, hF⟩ := @ax_ch_3 A,
have Fran : F.ran ⊆ A, intros y hy, rw mem_ran at hy, rcases hy with ⟨x, hxy⟩,
have hd : x ∈ F.dom, rw mem_dom, exact ⟨_, hxy⟩,
specialize hF _ hd, rw [Fdom, mem_sep, mem_powerset] at hd, apply hd.left,
rw fun_value_def Ffun hxy, exact hF,
let hrec : Set := pair_sep_eq P P (λ a, a ∪ {F.fun_value (A \ a)}),
let h : Set := P.rec_fun ∅ hrec,
have hesA : ∅ ∈ P, rw [mem_sep, mem_powerset], refine ⟨_, _, zero_nat, equin_refl⟩, intros x hx, exfalso, exact mem_empty _ hx,
have hrecinto : hrec.into_fun P P, apply pair_sep_eq_into,
intros a ha, rw [mem_sep, mem_powerset] at *, refine ⟨union_subset_of_subset_of_subset ha.left _, _⟩,
intros x hx, rw mem_singleton at hx, subst hx,
have hd : A \ a ∈ F.dom, rw [Fdom, mem_sep, mem_powerset], refine ⟨subset_diff, _⟩,
apply nonempty_diff_of_finite_subset_of_inf hA ha.right ha.left,
specialize hF _ hd, rw mem_diff at hF, exact hF.left,
apply union_finite_of_finite ha.right singleton_finite,
have hh : ∀ {n : Set.{u}}, n ∈ (ω : Set.{u}) → (h.fun_value n) ⊆ A ∧ (h.fun_value n).is_finite, refine @induction _ _ _,
rw (recursion_thm hesA hrecinto).left, rw [mem_sep, mem_powerset] at hesA, exact hesA,
intros n hn hi, rw (recursion_thm hesA hrecinto).right _ hn,
have hd : h.fun_value n ∈ hrec.dom, rw [hrecinto.right.left, mem_sep, mem_powerset], exact hi,
rw pair_sep_eq_fun_value hd, refine ⟨union_subset_of_subset_of_subset hi.left _, union_finite_of_finite hi.right singleton_finite⟩,
intros x hx, rw mem_singleton at hx, subst hx, apply Fran, apply fun_value_def'' Ffun,
rw [Fdom, mem_sep, mem_powerset], refine ⟨subset_diff, nonempty_diff_of_finite_subset_of_inf hA hi.right hi.left⟩,
let g : Set := pair_sep_eq ω A (λ n, F.fun_value (A \ h.fun_value n)),
refine ⟨g, pair_sep_eq_into _, pair_sep_eq_oto _⟩,
intros n hn, apply Fran, apply fun_value_def'' Ffun, rw [Fdom, mem_sep, mem_powerset],
refine ⟨subset_diff, nonempty_diff_of_finite_subset_of_inf hA (hh hn).right (hh hn).left⟩,
have hs : ∀ {n : Set.{u}}, n ∈ (ω : Set.{u}) → ∀ {k : Set.{u}}, k ∈ (ω : Set.{u}) → h.fun_value n ⊆ h.fun_value (n + k),
intros n hn, apply @induction (λ k, h.fun_value n ⊆ h.fun_value (n + k)),
rw [add_base hn], exact subset_self,
intros k hk ih,
have hnknat : (n + k) ∈ (ω : Set.{u}) := add_into_nat hn hk,
rw [add_ind hn hk, (recursion_thm hesA hrecinto).right _ hnknat],
have hd : h.fun_value (n + k) ∈ hrec.dom, rw [hrecinto.right.left, mem_sep, mem_powerset], exact hh hnknat,
rw pair_sep_eq_fun_value hd, exact subset_union_of_subset ih,
have hlt : ∀ {n : Set.{u}}, n ∈ (ω : Set.{u}) → ∀ {m : Set.{u}}, m ∈ (ω : Set.{u}) → n ∈ m → F.fun_value (A \ h.fun_value n) ≠ F.fun_value (A \ h.fun_value m),
intros n hn m hm hnm he,
rw [mem_iff_succ_le hn hm, le_iff_exists (nat_induct.succ_closed hn) hm] at hnm,
rcases hnm with ⟨p, hp, hnpm⟩,
specialize hs (nat_induct.succ_closed hn) hp, rw hnpm at hs,
have hf : F.fun_value (A \ h.fun_value n) ∈ h.fun_value m, apply hs,
rw (recursion_thm hesA hrecinto).right _ hn,
have hd : h.fun_value n ∈ hrec.dom, rw [hrecinto.right.left, mem_sep, mem_powerset], exact hh hn,
rw [pair_sep_eq_fun_value hd, mem_union, mem_singleton], right, refl,
have hf' : F.fun_value (A \ h.fun_value m) ∉ h.fun_value m,
have hd : A \ h.fun_value m ∈ F.dom, rw [Fdom, mem_sep, mem_powerset],
refine ⟨subset_diff, nonempty_diff_of_finite_subset_of_inf hA (hh hm).right (hh hm).left⟩,
specialize hF _ hd, rw [mem_diff] at hF, exact hF.right,
change F.fun_value (A \ h.fun_value n) = F.fun_value (A \ h.fun_value m) at he,
rw he at hf, exact hf' hf,
intros n hn m hm he, apply classical.by_contradiction, intro hne,
cases nat_order_conn hn hm hne with hnm hmn,
exact hlt hn hm hnm he,
exact hlt hm hn hmn he.symm,
end
-- Theorem 6N part b
theorem aleph_null_least_infinite_cardinal {κ : Set} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : card_le (card ω) κ :=
begin
rcases hκ with ⟨K, hK⟩, rw ←hK, rw card_le_iff_equin',
apply omega_least_infinite_set, intro hf, exact hinf ⟨_, hf, hK⟩,
end
lemma equin_omega_of_inf_subset {A : Set} (hA : ¬ A.is_finite) (hA' : A ⊆ ω) : A ≈ ω :=
equin_of_dom_of_dom (dominated_sub hA') (omega_least_infinite_set hA)
lemma exists_sub_card_alpeh_null_of_inf {κ : Set} (hκ : ¬ κ.finite_cardinal) {B : Set} (hB : B.card = κ) : ∃ A : Set, A ⊆ B ∧ A.card = card ω :=
begin
have Binf : ¬ B.is_finite, intro fin, apply hκ, exact ⟨_, fin, hB⟩,
have h := omega_least_infinite_set Binf,
obtain ⟨A, hAB, hA⟩ := exists_equin_subset_of_dominated h,
rw ←card_equiv at hA,
exact ⟨_, hAB, hA⟩,
end
lemma card_lt_aleph_null_iff_finite {κ : Set} (hκ : κ.is_cardinal) : κ.card_lt (card ω) ↔ κ.finite_cardinal :=
begin
split,
intros hlt, apply classical.by_contradiction, intro hnf, apply hlt.right,
apply card_eq_of_le_of_le hκ ⟨_, rfl⟩,
exact hlt.left,
exact aleph_null_least_infinite_cardinal hκ hnf,
intro hf, exact finite_card_lt_aleph_null hf,
end
lemma card_inf_of_ge_inf {κ : Set} (κcard : κ.is_cardinal) (κfin : ¬ κ.finite_cardinal)
{μ : Set} (μcard : μ.is_cardinal) (κμ : κ.card_le μ) : ¬ μ.finite_cardinal :=
begin
intro μfin, apply κfin,
rw ←card_lt_aleph_null_iff_finite κcard,
rw ←card_lt_aleph_null_iff_finite μcard at μfin,
exact card_lt_of_le_of_lt κcard μcard κμ μfin,
end
-- Corollary 6G, different proof
theorem subset_finite_of_finite' {A : Set.{u}} (hA : A.is_finite) {B : Set} (hBA : B ⊆ A) : B.is_finite :=
begin
rcases hA with ⟨n, hn, hAn⟩,
have hBn : B.card.card_le n.card, rw ←card_equiv at hAn, rw ←hAn, rw card_le_iff_equin', exact dominated_sub hBA,
have hnal : n.card.card_lt (card ω), apply finite_card_lt_aleph_null, exact ⟨_, nat_finite hn, rfl⟩,
refine one_finite_all_finite _ rfl, rw ←card_lt_aleph_null_iff_finite ⟨_, rfl⟩, split,
exact card_le_trans ⟨n, rfl⟩ hBn hnal.left,
intro he, apply hnal.right, apply card_eq_of_le_of_le ⟨_, rfl⟩ ⟨_, rfl⟩ hnal.left,
rw ←he, exact hBn,
end
-- Corollary 6P
theorem infinite_iff_equin_proper_subset_self {A : Set} : ¬ A.is_finite ↔ ∃ B : Set, B ⊂ A ∧ A ≈ B :=
begin
split,
intro hinf,
obtain ⟨f, finto, foto⟩ := omega_least_infinite_set hinf,
let L := (f.comp succ_fun).comp f.inv,
let R := (A \ f.ran).id,
let g := L ∪ R,
let B : Set := A \ {f.fun_value ∅},
refine ⟨B, _, _⟩,
rw ssubset_iff, refine ⟨subset_diff, _⟩,
intro he, rw ←ext_iff at he, simp only [and_iff_left_iff_imp, mem_diff, not_forall, mem_singleton] at he,
refine he (f.fun_value ∅) _ rfl,
apply finto.right.right, apply fun_value_def'' finto.left, rw finto.right.left, exact zero_nat,
have ranL : L.ran = f.ran \ {f.fun_value ∅},
have h : (f.comp succ_fun).dom ⊆ f.inv.ran,
have h' : succ_fun.ran ⊆ f.dom, rw [succ_fun_ran, finto.right.left], exact subset_diff,
rw [dom_comp h', T3E_b, finto.right.left, succ_fun_into_fun.right.left], exact subset_self,
rw [ran_comp h, ran_comp_complex foto, finto.right.left, succ_fun_ran],
have h' : {∅} ⊆ ω, intros x hx, rw [mem_singleton] at hx, subst hx, exact zero_nat,
rw [diff_diff_eq_self_of_subset h'],
have h'' : ∅ ∈ f.dom, rw finto.right.left, exact zero_nat,
rw img_singleton_eq finto.left h'',
refine ⟨g, _, _⟩,
have compfun : (f.comp succ_fun).is_function := T3H_a finto.left succ_fun_into_fun.left,
have finvfun : f.inv.is_function := T3F_a.mpr foto,
have domL : L.dom = f.ran,
have h : f.inv.ran ⊆ (f.comp succ_fun).dom,
have h' : succ_fun.ran ⊆ f.dom, rw [succ_fun_ran, finto.right.left], exact subset_diff,
rw [dom_comp h', T3E_b, finto.right.left, succ_fun_into_fun.right.left], exact subset_self,
rw [dom_comp h, T3E_a],
have gonto : g.onto_fun (L.dom ∪ R.dom) (L.ran ∪ R.ran),
apply union_fun (T3H_a compfun finvfun) id_is_function,
rw [eq_empty, domL, id_into.right.left], intros y hy, rw [mem_inter, mem_diff] at hy,
exact hy.right.right hy.left,
rw [domL, id_into.right.left] at gonto,
have h : f.ran ∪ A \ f.ran = A, rw eq_iff_subset_and_subset,
refine ⟨union_subset_of_subset_of_subset finto.right.right subset_diff, _⟩,
intros x hx, rw [mem_union, mem_diff],
by_cases hc : x ∈ f.ran,
left, exact hc,
right, exact ⟨hx, hc⟩,
rw h at gonto,
have ranL : L.ran = f.ran \ {f.fun_value ∅},
have h : (f.comp succ_fun).dom ⊆ f.inv.ran,
have h' : succ_fun.ran ⊆ f.dom, rw [succ_fun_ran, finto.right.left], exact subset_diff,
rw [dom_comp h', T3E_b, finto.right.left, succ_fun_into_fun.right.left], exact subset_self,
rw [ran_comp h, ran_comp_complex foto, finto.right.left, succ_fun_ran],
have h' : {∅} ⊆ ω, intros x hx, rw [mem_singleton] at hx, subst hx, exact zero_nat,
rw [diff_diff_eq_self_of_subset h'],
have h'' : ∅ ∈ f.dom, rw finto.right.left, exact zero_nat,
rw img_singleton_eq finto.left h'',
rw [ranL, id_onto.right.right] at gonto,
have h' : f.ran \ {f.fun_value ∅} ∪ A \ f.ran = B, apply ext,
simp only [mem_diff, mem_singleton, mem_union], intro y, split,
rintro (⟨hy, hny⟩|⟨hy, hny⟩),
exact ⟨finto.right.right hy, hny⟩,
refine ⟨hy, _⟩, intro hy', apply hny, subst hy', apply fun_value_def'' finto.left, rw finto.right.left, exact zero_nat,
rintro ⟨hy, hny⟩, by_cases hc : y ∈ f.ran,
left, exact ⟨hc, hny⟩,
right, exact ⟨hy, hc⟩,
rw h' at gonto, exact gonto,
refine union_one_to_one _ id_oto _,
rw [←T3F_a, T3I, T3E_c finto.left.left, T3I], apply T3H_a finto.left, apply T3H_a,
rw T3F_a, exact succ_one_to_one,
rw T3F_a, exact foto,
rw [ranL, id_onto.right.right, eq_empty], simp only [mem_inter, mem_diff, mem_singleton],
rintros y ⟨⟨hy, hny⟩, hA, hnf⟩, exact hnf hy,
rintro ⟨B, hBA, heq⟩, exact pigeonhole'' hBA heq,
end
-- I skipped some of the section on countable sets
def countable (A : Set) : Prop := A ≼ ω
lemma countable_card {A : Set} : A.card.card_le (card ω) ↔ A.countable :=
begin
rw [card_le_iff_equin', countable],
end
lemma countable_iff {A : Set} : A.countable ↔ A.is_finite ∨ A.card = card ω :=
by rw [←countable_card, card_le_iff, card_lt_aleph_null_iff_finite ⟨_, rfl⟩, card_finite_iff_finite]
lemma card_lt_of_not_le {K M : Set} (h : ¬ K.card.card_le M.card) : M.card.card_lt K.card :=
begin
rw card_lt_iff, split,
cases ax_ch_5 K M with hKM hMK,
exfalso, apply h, rw card_le_iff_equin', exact hKM,
exact hMK,
intro he, apply h, rw ←card_equiv at he, rw card_le_iff, right, exact he.symm,
end
lemma nat_le_inf {n : Set} (hn : n ∈ ω) {K : Set} (hK : ¬ K.is_finite) : n.card_le K.card :=
begin
apply card_le_trans ⟨ω, rfl⟩,
have h : n.card_lt (card ω), rw card_lt_aleph_null_iff_finite ⟨_, card_nat hn⟩,
rw finite_cardinal_iff_nat, exact hn,
exact h.left,
apply aleph_null_least_infinite_cardinal ⟨_, rfl⟩, rw card_finite_iff_finite, exact hK,
end
lemma nat_le_inf' {n : Set} (hn : n ∈ ω) {κ : Set} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : n.card_le κ :=
begin
rcases hκ with ⟨K, hK⟩, rw ←hK, apply nat_le_inf hn, rw ←card_finite_iff_finite, rw hK, exact hinf,
end
lemma finite_le_infinite {K : Set} (hK : K.is_finite) {M : Set} (hM : ¬ M.is_finite) : K.card.card_le M.card :=
begin
rw finite_iff at hK, rcases hK with ⟨n, hn, he⟩, rw he, exact nat_le_inf hn hM,
end
lemma finite_le_infinite' {κ : Set} (hκ : κ.is_cardinal) (hfin : κ.finite_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hinf : ¬ μ.finite_cardinal) : κ.card_le μ :=
begin
rcases hκ with ⟨K, hK⟩, rcases hμ with ⟨M, hM⟩, rw [←hK] at *,
rw ←hM at hinf, rw ←hM, rw card_finite_iff_finite at *, exact finite_le_infinite hfin hinf,
end
lemma mul_infinite_card_eq_self {κ : Set.{u}} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : κ.card_mul κ = κ :=
begin
rcases hκ with ⟨B, hB⟩,
let H : Set := {f ∈ ((B.prod B).prod B).powerset | f = ∅ ∨ ∃ A : Set, ¬ A.is_finite ∧ A ⊆ B ∧ (A.prod A).correspondence A f},
have hH : ∀ {f : Set}, f ∈ H ↔ f = ∅ ∨ ∃ A : Set, ¬ A.is_finite ∧ A ⊆ B ∧ (A.prod A).correspondence A f,
simp only [mem_powerset, and_imp, forall_eq_or_imp, mem_sep, and_iff_right_iff_imp, exists_imp_distrib],
refine ⟨empty_subset, _⟩, rintros f A hAinf hAB ⟨fonto, foto⟩, refine subset_trans _ (prod_subset_of_subset_of_subset (prod_subset_of_subset_of_subset hAB hAB) hAB),
rw [←fonto.right.left, ←fonto.right.right, ←rel_sub_dom_ran], exact fonto.left.left,
have hch : ∀ C : Set, C.is_chain → C ⊆ H → C.Union ∈ H, intros C hch hCH,
by_cases case : ∃ h, h ∈ C ∧ h ≠ ∅,
rcases case with ⟨h, hh, hhne⟩, rw hH, right,
let A := {R ∈ B.powerset | ∃ f : Set, f ∈ C ∧ R = f.ran}.Union,
have hA : ∀ ⦃y⦄, y ∈ A ↔ ∃ f : Set, y ∈ f.ran ∧ f ∈ C,
simp only [mem_powerset, exists_prop, mem_Union, mem_sep, mem_ran], intro y, split,
rintro ⟨A, ⟨hA, f, hf, he⟩, hy⟩, subst he, rw mem_ran at hy, exact ⟨_, hy, hf⟩,
rintro ⟨f, hy, hf⟩, rw ←mem_ran at hy,
have h : f ∈ H := hCH hf,
rw hH at h, rcases h with (hf|⟨A, -, hAB, fonto, -⟩),
subst hf, rw [ran_empty_eq_empty] at hy, exfalso, exact mem_empty _ hy,
refine ⟨_, ⟨_, _, hf, rfl⟩, hy⟩, rw fonto.right.right, exact hAB,
have hAeq : A = C.Union.ran := ran_Union_eq_Union_ran hA,
let D := {D ∈ (B.prod B).powerset | ∃ f : Set, f ∈ C ∧ D = f.dom}.Union,
have hD : ∀ ⦃x⦄, x ∈ D ↔ ∃ f : Set, x ∈ f.dom ∧ f ∈ C,
simp only [mem_Union, mem_sep, mem_powerset, exists_prop, mem_dom], intro x, split,
rintro ⟨X, ⟨hX, f, hf, he⟩, hx⟩, subst he, rw mem_dom at hx, exact ⟨_, hx, hf⟩,
rintro ⟨f, hx, hf⟩, rw ←mem_dom at hx,
have h : f ∈ H := hCH hf,
rw hH at h, rcases h with (hf|⟨A, -, hAB, fonto, -⟩),
subst hf, rw [dom_empty_eq_empty] at hx, exfalso, exact mem_empty _ hx,
refine ⟨_, ⟨_, _, hf, rfl⟩, hx⟩, rw fonto.right.left, exact prod_subset_of_subset_of_subset hAB hAB,
have hDeq : D = C.Union.dom := dom_Union_eq_Union_dom hD,
refine ⟨A, _, _, ⟨_, _, hAeq.symm⟩, _⟩,
{ have hhC := hCH hh,
rw hH at hhC, rcases hhC with (hemp|⟨A', hA'inf, hA'B, honto, hoto⟩),
exfalso, exact hhne hemp,
intro hAfin, apply hA'inf,
have hA'subA : A' ⊆ A, rw ←honto.right.right, intros y hy, rw hA, exact ⟨_, hy, hh⟩,
exact subset_finite_of_finite hAfin hA'subA, },
{ intros y hy, rw hA at hy, rcases hy with ⟨f, hy, hf⟩,
replace hf := hCH hf, rw hH at hf, rcases hf with (hf|⟨A, -, hAB, fonto, -⟩),
subst hf, rw [ran_empty_eq_empty] at hy, exfalso, exact mem_empty _ hy,
rw fonto.right.right at hy, exact hAB hy, },
{ apply Union_chain_is_function hch, intros f hf,
replace hf := hCH hf, rw hH at hf, rcases hf with (hf|⟨A, -, -, fonto, -⟩),
subst hf, exact empty_fun,
exact fonto.left, },
{ apply ext, intro z, split,
rw [←hDeq, hD], rintro ⟨f, hz, hf⟩,
have hf' := hCH hf, rw hH at hf', rcases hf' with (hf'|⟨X, Xinf, hXB, fonto, foto⟩),
subst hf', rw dom_empty_eq_empty at hz, exfalso, exact mem_empty _ hz,
simp only [fonto.right.left, mem_prod, exists_prop] at hz, rcases hz with ⟨a₁, ha₁, a₂, ha₂, he⟩, subst he,
simp only [pair_mem_prod, hA], rw ←fonto.right.right at ha₁ ha₂,
exact ⟨⟨_, ha₁, hf⟩, _, ha₂, hf⟩,
simp only [mem_prod, exists_prop, hA],
have hpart : ∀ {f₁ : Set.{u}}, f₁ ∈ C → ∀ {f₂}, f₂ ∈ C → f₁ ⊆ f₂ → ∀ {a₁ : Set}, a₁ ∈ f₁.ran ∪ f₂.ran → ∀ {a₂}, a₂ ∈ f₁.ran ∪ f₂.ran → a₁.pair a₂ ∈ C.Union.dom,
intros f₁ hf₁ f₂ hf₂ hf a₁ ha₁ a₂ ha₂,
have hf₂' := hCH hf₂, rw hH at hf₂', rcases hf₂' with (hf₂'|⟨X, Xinf, hXB, fonto, foto⟩),
subst hf₂', rw [ran_empty_eq_empty, union_empty, mem_ran] at ha₂, rcases ha₂ with ⟨x, ha₂⟩, exfalso, exact mem_empty _ (hf ha₂),
rw [←hDeq, hD], refine ⟨f₂, _, hf₂⟩, rw [fonto.right.left, pair_mem_prod],
replace ha₁ := union_subset_of_subset_of_subset (ran_subset_of_subset hf) subset_self ha₁,
replace ha₂ := union_subset_of_subset_of_subset (ran_subset_of_subset hf) subset_self ha₂,
rw fonto.right.right at ha₁ ha₂, exact ⟨ha₁, ha₂⟩,
rintro ⟨a₁, ⟨f₁, ha₁, hf₁⟩, a₂, ⟨f₂, ha₂, hf₂⟩, he⟩, subst he,
replace ha₁ : a₁ ∈ f₁.ran ∪ f₂.ran, rw mem_union, left, exact ha₁,
replace ha₂ : a₂ ∈ f₁.ran ∪ f₂.ran, rw mem_union, right, exact ha₂,
cases hch hf₁ hf₂ with hf hf,
exact hpart hf₁ hf₂ hf ha₁ ha₂,
rw union_comm at ha₁ ha₂,
exact hpart hf₂ hf₁ hf ha₁ ha₂, },
{ apply Union_chain_oto hch, intros f hf,
replace hf := hCH hf, rw hH at hf, rcases hf with (hf|⟨-, -, -, -, foto⟩),
subst hf, exact empty_oto,
exact foto, },
rw hH, left, rw eq_empty, intros z hz, apply case, rw mem_Union at hz,
rcases hz with ⟨f, hf, hz⟩, refine ⟨_, hf, _⟩, exact ne_empty_of_inhabited _ ⟨_, hz⟩,
obtain ⟨f₀, hf₀, hmax⟩ := ax_ch_6 _ hch,
rw hH at hf₀, cases hf₀,
obtain ⟨A, hAB, hA⟩ := exists_sub_card_alpeh_null_of_inf hinf hB,
have hAprodA := aleph_mul_aleph_eq_aleph,
rw [←hA, ←card_mul_spec rfl rfl, card_equiv] at hAprodA, rcases hAprodA with ⟨g, gcorr⟩,
have gH : g ∈ H, rw hH, right, refine ⟨_, _, hAB, gcorr⟩, rw [←card_finite_iff_finite, hA], exact aleph_null_infinite_cardinal,
have Ainhab : A.inhab, rw card_equiv at hA, replace hA := equin_symm hA,
rcases hA with ⟨f, fonto, foto⟩, use f.fun_value ∅, rw ←fonto.right.right,
apply fun_value_def'' fonto.left, rw fonto.right.left, exact zero_nat,
rcases Ainhab with ⟨a, ha⟩,
exfalso, subst hf₀, refine hmax _ gH _ empty_subset,
apply ne_empty_of_inhabited, use (pair a a).pair (g.fun_value (a.pair a)),
apply fun_value_def' gcorr.onto.left, rw [gcorr.onto.right.left, pair_mem_prod], exact ⟨ha, ha⟩,
rcases hf₀ with ⟨A₀, hAinf, hAB, fcorr⟩,
let μ := A₀.card,
have μpμ : μ.card_mul μ = μ, rw [←card_mul_spec rfl rfl, card_equiv], exact ⟨_, fcorr⟩,
have hlt : (B \ A₀).card.card_lt μ, apply card_lt_of_not_le, intro hle,
rw card_le_iff_equin' at hle,
obtain ⟨D, hDBA, hDA⟩ := exists_equin_subset_of_dominated hle,
rw ←card_equiv at hDA,
have hdisj : A₀ ∩ D = ∅, rw eq_empty, intros x hx, rw mem_inter at hx,
specialize hDBA hx.right, rw mem_diff at hDBA, exact hDBA.right hx.left,
have hmpm : μ.card_add μ = μ,
rw [card_add_self_eq_two_mul_self ⟨_, rfl⟩],
apply card_eq_of_le_of_le (mul_cardinal (nat_is_cardinal two_nat) ⟨_, rfl⟩) ⟨_, rfl⟩,
change (two.card_mul μ).card_le μ,
nth_rewrite 1 ←μpμ, refine card_mul_le_of_le_left (nat_is_cardinal two_nat) ⟨_, rfl⟩ _ ⟨_, rfl⟩,
have two_le_a : two.card_le (card ω), rw card_le_iff, left, apply finite_card_lt_aleph_null,
rw finite_cardinal_iff_nat, exact two_nat,
refine card_le_trans ⟨_, rfl⟩ two_le_a _, apply aleph_null_least_infinite_cardinal ⟨_, rfl⟩,
rw card_finite_iff_finite, exact hAinf,
nth_rewrite 0 ←card_mul_one_eq_self ⟨_, rfl⟩,
rw card_mul_comm ⟨_, rfl⟩ (nat_is_cardinal one_nat),
refine card_mul_le_of_le_left (nat_is_cardinal one_nat) (nat_is_cardinal two_nat) _ ⟨_, rfl⟩,
have one_fin : one.finite_cardinal, rw finite_cardinal_iff_nat, exact one_nat,
have two_fin : two.finite_cardinal, rw finite_cardinal_iff_nat, exact two_nat,
rw [finite_card_le_iff_le one_fin two_fin, le_iff, two],
left, exact self_mem_succ,
have cardAD : (A₀ ∪ D).card = μ, rw card_add_spec rfl hDA hdisj, exact hmpm,
have hext : ((D.prod A₀) ∪ ((A₀.prod D) ∪ (D.prod D))).card = D.card,
have hdisj' : A₀.prod D ∩ D.prod D = ∅, rw rel_eq_empty (inter_rel_is_rel prod_is_rel),
simp only [eq_empty, mem_inter] at hdisj,
simp only [pair_mem_prod, mem_inter], rintros x y ⟨⟨hx, hy⟩, hx', hy'⟩, exact hdisj _ ⟨hx, hx'⟩,
have hdisj'' : D.prod A₀ ∩ (A₀.prod D ∪ D.prod D) = ∅, rw rel_eq_empty (inter_rel_is_rel prod_is_rel),
simp only [eq_empty, mem_inter] at hdisj,
simp only [pair_mem_prod, mem_inter, mem_union], rintros x y ⟨⟨hx, hy⟩, (⟨hx', hy'⟩|⟨hx', hy'⟩)⟩,
exact hdisj _ ⟨hy, hy'⟩,
exact hdisj _ ⟨hy, hy'⟩,
rw [card_add_spec rfl rfl hdisj'', card_add_spec rfl rfl hdisj'],
simp only [card_mul_spec rfl rfl, hDA],
change (μ.card_mul μ).card_add ((μ.card_mul μ).card_add (μ.card_mul μ)) = μ,
simp only [μpμ, hmpm],
rw card_equiv at hext, rcases hext with ⟨g, gcorr⟩,
have fgonto : (f₀ ∪ g).onto_fun ((A₀ ∪ D).prod (A₀ ∪ D)) (A₀ ∪ D),
simp only [union_prod, prod_union],
simp only [←@union_assoc (A₀.prod A₀) (D.prod A₀) ((A₀.prod D) ∪ (D.prod D))],
rw [←fcorr.onto.right.left, ←gcorr.onto.right.left, ←fcorr.onto.right.right, ←gcorr.onto.right.right],
apply union_fun fcorr.onto.left gcorr.onto.left,
rw [fcorr.onto.right.left, gcorr.onto.right.left],
rw rel_eq_empty (inter_rel_is_rel prod_is_rel),
intros x y hxy, simp only [mem_inter, mem_union, pair_mem_prod] at hxy,
rw eq_empty at hdisj, simp only [mem_inter] at hdisj,
rcases hxy with ⟨⟨hx', hy'⟩,(⟨hx, hy⟩|⟨hx, hy⟩|⟨hx, hy⟩)⟩,
exact hdisj _ ⟨hx', hx⟩,
exact hdisj _ ⟨hy', hy⟩,
exact hdisj _ ⟨hx', hx⟩,
have fgH : f₀ ∪ g ∈ H, rw hH, right, refine ⟨A₀ ∪ D, _, _, _⟩,
rw [←card_finite_iff_finite, cardAD, card_finite_iff_finite], exact hAinf,
apply union_subset_of_subset_of_subset hAB,
intros x hx, specialize hDBA hx, rw mem_diff at hDBA, exact hDBA.left,
split,
exact fgonto,
apply union_one_to_one fcorr.oto gcorr.oto, rw [fcorr.onto.right.right, gcorr.onto.right.right],
exact hdisj,
have Dinhab : D.inhab,
have a_le_D : card_le (card ω) D.card, apply aleph_null_least_infinite_cardinal ⟨_, rfl⟩,
rw [hDA, card_finite_iff_finite], exact hAinf,
rw card_le_iff_equin' at a_le_D, rcases a_le_D with ⟨f, finto, foto⟩,
use f.fun_value ∅, apply finto.right.right, apply fun_value_def'' finto.left,
rw finto.right.left, exact zero_nat,
rcases Dinhab with ⟨d, hd⟩,
have fgnef : f₀ ∪ g ≠ f₀, intro he,
have hd' : d ∈ (f₀ ∪ g).ran, rw [fgonto.right.right, mem_union], right, exact hd,
rw [he, fcorr.onto.right.right] at hd', simp only [eq_empty, mem_inter] at hdisj,
exact hdisj _ ⟨hd', hd⟩,
exact hmax _ fgH fgnef subset_union_left,
have kem : κ = μ, symmetry, apply card_eq_of_le_of_le ⟨_, rfl⟩ ⟨_, hB⟩,
rw ←hB, exact card_le_of_subset hAB,
rw [←hB, ←union_diff_eq_self_of_subset hAB, card_add_spec rfl rfl self_inter_diff_empty],
change (A₀.card.card_add (B \ A₀).card).card_le μ, rw ←μpμ, apply card_le_trans (mul_cardinal (nat_is_cardinal two_nat) ⟨A₀, rfl⟩),
rw ←card_add_self_eq_two_mul_self ⟨_, rfl⟩, exact card_add_le_of_le_right ⟨_, rfl⟩ ⟨_, rfl⟩ hlt.left ⟨_, rfl⟩,
exact card_mul_le_of_le_left ⟨_, card_nat two_nat⟩ ⟨_, rfl⟩ (nat_le_inf two_nat hAinf) ⟨_, rfl⟩,
rw kem, exact μpμ,
end
lemma add_infinite_card_eq_self {κ : Set.{u}} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : κ.card_add κ = κ :=
begin
rw [card_add_self_eq_two_mul_self hκ],
apply card_eq_of_le_of_le (mul_cardinal (nat_is_cardinal two_nat) hκ) hκ,
nth_rewrite 1 ←mul_infinite_card_eq_self hκ hinf,
refine card_mul_le_of_le_left (nat_is_cardinal two_nat) hκ _ hκ,
have two_le_a : two.card_le (card ω), rw card_le_iff, left, apply finite_card_lt_aleph_null,
rw finite_cardinal_iff_nat, exact two_nat,
refine card_le_trans ⟨_, rfl⟩ two_le_a (aleph_null_least_infinite_cardinal hκ hinf),
nth_rewrite 0 ←card_mul_one_eq_self hκ,
rw card_mul_comm hκ (nat_is_cardinal one_nat),
refine card_mul_le_of_le_left (nat_is_cardinal one_nat) (nat_is_cardinal two_nat) _ hκ,
have one_fin : one.finite_cardinal, rw finite_cardinal_iff_nat, exact one_nat,
have two_fin : two.finite_cardinal, rw finite_cardinal_iff_nat, exact two_nat,
rw [finite_card_le_iff_le one_fin two_fin, le_iff, two],
left, exact self_mem_succ,
end
lemma card_add_eq_right_of_le {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hinf : ¬ μ.finite_cardinal) (hκμ : κ.card_le μ) : κ.card_add μ = μ :=
begin
apply card_eq_of_le_of_le (add_cardinal hκ hμ) hμ,
nth_rewrite 1 ←add_infinite_card_eq_self hμ hinf,
exact card_add_le_of_le_left hκ hμ hκμ hμ,
nth_rewrite 0 ←card_empty_add hμ, refine card_add_le_of_le_left (nat_is_cardinal zero_nat) hκ _ hμ,
exact zero_card_le hκ,
end
lemma card_add_eq_left_of_le {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (hinf : ¬ μ.finite_cardinal) (hκμ : κ.card_le μ) : μ.card_add κ = μ :=
begin
rw card_add_comm hμ hκ, exact card_add_eq_right_of_le hκ hμ hinf hκμ,
end
lemma card_diff_from_inf {K : Set} (hinf : ¬ K.is_finite) {M : Set} (hMK : M ⊆ K) (hMK' : M.card.card_lt K.card) : (K \ M).card = K.card :=
begin
have he : K.card = (M ∪ K \ M).card, rw union_diff_eq_self_of_subset hMK,
rw card_add_spec rfl rfl self_inter_diff_empty at he,
by_cases hcase : M.is_finite,
have hKM : ¬ (K \ M).is_finite, intro hfin, rw finite_iff at *,
rcases hcase with ⟨n, hn, hM⟩, rcases hfin with ⟨m, hm, hKM⟩, rw [hM, hKM] at he,
apply hinf, rw he, refine ⟨n + m, add_into_nat hn hm, _⟩,
apply card_add_eq_ord_add,
rw finite_cardinal_iff_nat, exact hn,
rw finite_cardinal_iff_nat, exact hm,
have hKM' : ¬ (K \ M).card.finite_cardinal, intro hfin, rw card_finite_iff_finite at hfin,
exact hKM hfin,
have he' : M.card.card_add (K \ M).card = (K \ M).card,
apply card_add_eq_right_of_le ⟨_, rfl⟩ ⟨_, rfl⟩ hKM', exact finite_le_infinite hcase hKM,
rw he' at he, exact he.symm,
cases ax_ch_5 M (K \ M),
have hKMfin : ¬ (K \ M).is_finite := infinite_of_dominates_infinite hcase h,
have he' : M.card.card_add (K \ M).card = (K \ M).card,
apply card_add_eq_right_of_le ⟨_, rfl⟩ ⟨_, rfl⟩,
rw card_finite_iff_finite, exact hKMfin,
rw ←card_le_iff_equin' at h, exact h,
rw he' at he, exact he.symm,
have he' : M.card.card_add (K \ M).card = M.card,
apply card_add_eq_left_of_le ⟨_, rfl⟩ ⟨_, rfl⟩,
rw card_finite_iff_finite, exact hcase,
rw ←card_le_iff_equin' at h, exact h,
rw he' at he, exfalso, exact hMK'.right he.symm,
end
lemma card_exp_self_eq_pow_self {κ : Set} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : κ.card_exp κ = two.card_exp κ :=
begin
have two_card : two.is_cardinal := nat_is_cardinal two_nat,
apply card_eq_of_le_of_le (exp_cardinal hκ hκ) (exp_cardinal two_card hκ),
nth_rewrite 2 ←mul_infinite_card_eq_self hκ hinf, rw ←card_exp_exp two_card hκ hκ,
exact card_exp_le_of_le hκ (exp_cardinal two_card hκ) (card_le_iff.mpr (or.inl (card_lt_exp hκ))) hκ,
refine card_exp_le_of_le two_card hκ (finite_le_infinite' two_card _ hκ hinf) hκ,
rw finite_cardinal_iff_nat, exact two_nat,
end
lemma card_fin_of_le_fin {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (μfin : μ.finite_cardinal) (κμ : κ.card_le μ) : κ.finite_cardinal :=
classical.by_contradiction (λ κinf, card_inf_of_ge_inf hκ κinf (fin_card_is_card μfin) κμ μfin)
lemma inf_card_not_empty {κ : Set} (hκ : κ.is_cardinal) (hinf : ¬ κ.finite_cardinal) : κ ≠ ∅ :=
begin
intro κz, subst κz, rw [←card_nat zero_nat, card_finite_iff_finite] at hinf,
exact hinf (nat_finite zero_nat),
end
lemma card_not_empty_iff_ge_one {κ : Set} (hκ : κ.is_cardinal) : κ ≠ ∅ ↔ one.card_le κ :=
begin
split,
intro κz, rcases hκ with ⟨K, hK⟩, subst hK,
have Kz : K ≠ ∅, intro Kz, subst Kz, exact κz (card_nat zero_nat),
obtain ⟨x, xK⟩ := inhabited_of_ne_empty Kz,
rw ←@card_singleton x, apply card_le_of_subset, intro z, rw mem_singleton, intro zx, subst zx, exact xK,
intros h κz, subst κz,
have o : one ∈ ω := one_nat,
have z : ∅ ∈ ω := zero_nat,
rw ←finite_cardinal_iff_nat at o z,
rw finite_card_le_iff_le o z at h, cases h,
exact mem_empty _ h,
apply mem_empty ∅, nth_rewrite 1 ←h, exact zero_lt_one,
end
lemma card_mul_lt_mul {κ : Set} (hκ : κ.is_cardinal) {μ : Set} (hμ : μ.is_cardinal) (κμ : κ.card_lt μ) :
(κ.card_mul κ).card_lt (μ.card_mul μ) :=
begin
by_cases μfin : μ.finite_cardinal,
have κfin := card_fin_of_le_fin hκ μfin κμ.left,
rw [finite_card_lt_iff_lt (card_mul_fin_of_fin κfin κfin) (card_mul_fin_of_fin μfin μfin),
card_mul_eq_ord_mul κfin κfin, card_mul_eq_ord_mul μfin μfin],
rw finite_card_lt_iff_lt κfin μfin at κμ,
rw finite_cardinal_iff_nat at μfin,
apply mul_lt_mul_of_lt' μfin κμ,
by_cases κz : κ = ∅,
subst κz, rwa [card_mul_empty (nat_is_cardinal zero_nat), mul_infinite_card_eq_self hμ μfin],
refine ⟨card_le_trans (mul_cardinal hμ hκ) (card_mul_le_of_le_left hκ hμ κμ.left hκ) (card_mul_le_of_le_right hκ hμ κμ.left hμ), λ h, _⟩,
have κκ : κ.card_le (κ.card_mul κ),
nth_rewrite 0 ←card_mul_one_eq_self hκ,
change κ ≠ ∅ at κz, rw card_not_empty_iff_ge_one hκ at κz,
exact card_mul_le_of_le_right (nat_is_cardinal one_nat) hκ κz hκ,
rw card_le_iff at κκ, cases κκ, rotate,
rw [κκ, h, mul_infinite_card_eq_self hμ μfin] at κμ, exact κμ.right rfl,
have κfin : κ.finite_cardinal, apply classical.by_contradiction, intro κinf,
rw mul_infinite_card_eq_self hκ κinf at κκ, exact κκ.right rfl,
apply μfin, rw [←mul_infinite_card_eq_self hμ μfin, ←h], exact card_mul_fin_of_fin κfin κfin,
end
end Set
|
How to choose an interesting and creative wedding cake topper?
Nowadays, there is such a vast range of beautiful miniaturized figurines and replicas of romancing couples available in the market that you would be mesmerized. These collectibles also include wedding cake toppers for bride and groom. These cake toppers are so beautiful and cute that you would love to make it a part of your guestbook table, or keep it in your drawing room. You can also gift these to your loved ones.
These silent figurines, which showcase romancing couples, interlocking hearts, birds, wedding rings, girls in bridal dresses, dancing couples, and couples performing love on the hood of a car, are simply amazing. These cake toppers not only have a great aesthetic appeal, but also provide a perfect finish to the wedding cakes. They come in all sizes, colors and varieties, so as to fit on all types of wedding cakes.
If you want to buy cake toppers, make sure that these are of top quality. These porcelain wonders should have a lead free paint to begin with. They should be perfectly crafted to give it a real-life look. Furthermore, make sure attention to details is provided, as these are collectibles and people love to keep it. Some of the wedding accessory suppliers do not pay attention to details. Refer to the website of the store, and choose from a wide variety of cake toppers. A high priority return policy is also an indication that the supplier is committed towards customer service and quality.
For those, who think that most of the wedding toppers are similar, here are a few tips to anniversary cake toppers that are sure to excite you. Don't go for the traditional "arm in arm" or "bride and groom exchanging kisses" positions. Imagine a real-life situation, which would excite you. It might be related to your past events, a memorable journey, your ambition, your favorite outfit, or your favorite activity. You can also get the bride and groom dressed like Indians or Australian aborigines. Adding the element of fun to your cake topper would make it more interesting and original.
A professional cake designer can create an endless variety of wedding cake toppers. You can use different materials such as glass, crystal or porcelain to make them. Most of the people love to keep them as wedding day souvenirs in their drawing rooms. |
open import Agda.Builtin.Bool
open import Agda.Builtin.Char
open import Agda.Builtin.Nat
open import Agda.Builtin.Equality
char : Char → Set
char 'A' with 'O'
char _ | _ = Char
char _ = Char
lit : Nat → Set
lit 5 with 0
lit _ | _ = Nat
lit _ = Nat
con : Nat → Set
con zero with zero
con _ | _ = Nat
con (suc x) with zero
con _ | _ = Nat
record R : Set where
coinductive -- disallow matching
field f : Bool
n : Nat
data P (r : R) : Nat → Set where
fTrue : R.f r ≡ true → P r zero
nSuc : P r (suc (R.n r))
data Q : (b : Bool) (n : Nat) → Set where
true! : Q true zero
suc! : ∀{b n} → Q b (suc n)
test : (r : R) {n : Nat} (p : P r n) → Q (R.f r) n
test r nSuc = suc!
test r (fTrue p) with R.f r
test _ (fTrue ()) | false
test _ _ | true = true! -- underscore instead of (isTrue _)
-- -- Note that `with` first and then splitting on p does not work:
--
-- foo : (r : R) {n : Nat} (p : P r n) → Q (R.f r) n
-- foo r p with R.f r
-- foo r (fTrue x) | false = {!x!} -- cannot split on x
-- foo r (fTrue _) | true = true!
-- foo r nSuc | _ = suc!
|
------------------------------------------------------------------------
-- An implementation of the Thue-Morse sequence
------------------------------------------------------------------------
-- The paper "Productivity of stream definitions" by Endrullis et al.
-- (TCS 2010) uses a certain definition of the Thue-Morse sequence as
-- a running example.
-- Note that the code below makes use of the fact that Agda's
-- termination checker allows "swapping of arguments", which was not
-- mentioned when the termination checker was described in the paper
-- "Beating the Productivity Checker Using Embedded Languages".
-- However, it is easy to rewrite the code into a form which does not
-- make use of swapping, at the cost of some code duplication.
module ThueMorse where
open import Codata.Musical.Notation
open import Codata.Musical.Stream as S using (Stream; _≈_)
open S.Stream; open S._≈_
open import Data.Bool using (Bool; not); open Data.Bool.Bool
open import Function
open import Relation.Binary
import Relation.Binary.PropositionalEquality as P
import Relation.Binary.Reasoning.Setoid as EqReasoning
private
module SS {A : Set} = Setoid (S.setoid A)
open module SR {A : Set} = EqReasoning (S.setoid A)
using (begin_; _∎)
------------------------------------------------------------------------
-- Chunks
-- A value of type Chunks describes how a stream is generated. Note
-- that an infinite sequence of empty chunks is not allowed.
data Chunks : Set where
-- Start the next chunk.
next : (m : Chunks) → Chunks
-- Cons an element to the current chunk.
cons : (m : ∞ Chunks) → Chunks
-- Equality of chunks.
infix 4 _≈C_
data _≈C_ : Chunks → Chunks → Set where
next : ∀ {m m′} (m≈m′ : m ≈C m′ ) → next m ≈C next m′
cons : ∀ {m m′} (m≈m′ : ∞ (♭ m ≈C ♭ m′)) → cons m ≈C cons m′
------------------------------------------------------------------------
-- Chunk transformers
tailC : Chunks → Chunks
tailC (next m) = next (tailC m)
tailC (cons m) = ♭ m
mutual
evensC : Chunks → Chunks
evensC (next m) = next (evensC m)
evensC (cons m) = cons (♯ oddsC (♭ m))
oddsC : Chunks → Chunks
oddsC (next m) = next (oddsC m)
oddsC (cons m) = evensC (♭ m)
infixr 5 _⋎C_
-- Note that care is taken to create as few and large chunks as
-- possible (see also _⋎W_).
_⋎C_ : Chunks → Chunks → Chunks
next m ⋎C next m′ = next (m ⋎C m′) -- Two chunks in, one out.
next m ⋎C cons m′ = next (m ⋎C cons m′)
cons m ⋎C m′ = cons (♯ (m′ ⋎C ♭ m))
------------------------------------------------------------------------
-- Stream programs
-- StreamP m A encodes programs which generate streams with chunk
-- sizes given by m.
infixr 5 _∷_ _⋎_
data StreamP : Chunks → Set → Set₁ where
[_] : ∀ {m A} (xs : ∞ (StreamP m A)) → StreamP (next m) A
_∷_ : ∀ {m A} (x : A) (xs : StreamP (♭ m) A) → StreamP (cons m) A
tail : ∀ {m A} (xs : StreamP m A) → StreamP (tailC m) A
evens : ∀ {m A} (xs : StreamP m A) → StreamP (evensC m) A
odds : ∀ {m A} (xs : StreamP m A) → StreamP (oddsC m) A
_⋎_ : ∀ {m m′ A} (xs : StreamP m A) (ys : StreamP m′ A) →
StreamP (m ⋎C m′) A
map : ∀ {m A B} (f : A → B) (xs : StreamP m A) → StreamP m B
cast : ∀ {m m′ A} (ok : m ≈C m′) (xs : StreamP m A) → StreamP m′ A
data StreamW : Chunks → Set → Set₁ where
[_] : ∀ {m A} (xs : StreamP m A) → StreamW (next m) A
_∷_ : ∀ {m A} (x : A) (xs : StreamW (♭ m) A) → StreamW (cons m) A
program : ∀ {m A} → StreamW m A → StreamP m A
program [ xs ] = [ ♯ xs ]
program (x ∷ xs) = x ∷ program xs
tailW : ∀ {m A} → StreamW m A → StreamW (tailC m) A
tailW [ xs ] = [ tail xs ]
tailW (x ∷ xs) = xs
mutual
evensW : ∀ {m A} → StreamW m A → StreamW (evensC m) A
evensW [ xs ] = [ evens xs ]
evensW (x ∷ xs) = x ∷ oddsW xs
oddsW : ∀ {m A} → StreamW m A → StreamW (oddsC m) A
oddsW [ xs ] = [ odds xs ]
oddsW (x ∷ xs) = evensW xs
infixr 5 _⋎W_
-- Note: Uses swapping of arguments.
_⋎W_ : ∀ {m m′ A} → StreamW m A → StreamW m′ A → StreamW (m ⋎C m′) A
[ xs ] ⋎W [ ys ] = [ xs ⋎ ys ]
[ xs ] ⋎W (y ∷ ys) = [ xs ⋎ program (y ∷ ys) ]
(x ∷ xs) ⋎W ys = x ∷ ys ⋎W xs
mapW : ∀ {m A B} → (A → B) → StreamW m A → StreamW m B
mapW f [ xs ] = [ map f xs ]
mapW f (x ∷ xs) = f x ∷ mapW f xs
castW : ∀ {m m′ A} → m ≈C m′ → StreamW m A → StreamW m′ A
castW (next m≈m′) [ xs ] = [ cast m≈m′ xs ]
castW (cons m≈m′) (x ∷ xs) = x ∷ castW (♭ m≈m′) xs
whnf : ∀ {m A} → StreamP m A → StreamW m A
whnf [ xs ] = [ ♭ xs ]
whnf (x ∷ xs) = x ∷ whnf xs
whnf (tail xs) = tailW (whnf xs)
whnf (evens xs) = evensW (whnf xs)
whnf (odds xs) = oddsW (whnf xs)
whnf (xs ⋎ ys) = whnf xs ⋎W whnf ys
whnf (map f xs) = mapW f (whnf xs)
whnf (cast m≈m′ xs) = castW m≈m′ (whnf xs)
mutual
⟦_⟧W : ∀ {m A} → StreamW m A → Stream A
⟦ [ xs ] ⟧W = ⟦ xs ⟧P
⟦ x ∷ xs ⟧W = x ∷ ♯ ⟦ xs ⟧W
⟦_⟧P : ∀ {m A} → StreamP m A → Stream A
⟦ xs ⟧P = ⟦ whnf xs ⟧W
------------------------------------------------------------------------
-- The Thue-Morse sequence
[ccn]ω : Chunks
[ccn]ω = cons (♯ cons (♯ next [ccn]ω))
[cn]²[ccn]ω : Chunks
[cn]²[ccn]ω = cons (♯ next (cons (♯ next [ccn]ω)))
[cn]³[ccn]ω : Chunks
[cn]³[ccn]ω = cons (♯ next [cn]²[ccn]ω)
-- Explanation of the proof of lemma₁:
--
-- odds [ccn]ω ≈ [cn]ω
--
-- [cn]ω ⋎ [ccn]ω ≈
-- c ([ccn]ω ⋎ n[cn]ω) ≈
-- c c (n[cn]ω ⋎ cn[ccn]ω) ≈
-- c c n ([cn]ω ⋎ cn[ccn]ω) ≈
-- c c n c (cn[ccn]ω ⋎ n[cn]ω) ≈
-- c c n c c (n[cn]ω ⋎ n[ccn]ω) ≈
-- c c n c c n ([cn]ω ⋎ [ccn]ω)
lemma₁ : oddsC [ccn]ω ⋎C [ccn]ω ≈C [ccn]ω
lemma₁ = cons (♯ cons (♯ next (cons (♯ cons (♯ next lemma₁)))))
-- Explanation of the proof of lemma:
--
-- evens [cn]³[ccn]ω ≈ cnn[cn]ω
-- tail [cn]³[ccn]ω ≈ n[cn]²[ccn]ω
--
-- cnn[cn]ω ⋎ n[cn]²[ccn]ω ≈
-- c (n[cn]²[ccn]ω ⋎ nn[cn]ω) ≈
-- c n ([cn]²[ccn]ω ⋎ n[cn]ω) ≈
-- c n c (n[cn]ω ⋎ ncn[ccn]ω) ≈
-- c n c n ([cn]ω ⋎ cn[ccn]ω) ≈
-- c n c n c (cn[ccn]ω ⋎ n[cn]ω) ≈
-- c n c n c c (n[cn]ω ⋎ n[ccn]ω) ≈
-- c n c n c c n ([cn]ω ⋎ [ccn]ω)
lemma : evensC [cn]³[ccn]ω ⋎C tailC [cn]³[ccn]ω ≈C [cn]²[ccn]ω
lemma = cons (♯ next (cons (♯ next (cons (♯ cons (♯ next lemma₁))))))
thueMorse : StreamP [cn]³[ccn]ω Bool
thueMorse =
false ∷ [ ♯ cast lemma (map not (evens thueMorse) ⋎ tail thueMorse) ]
------------------------------------------------------------------------
-- Equality programs
infix 4 _≈[_]P_ _≈[_]W_
infixr 2 _≈⟨_⟩P_ _≈⟨_⟩_
data _≈[_]P_ : {A : Set} → Stream A → Chunks → Stream A → Set₁ where
[_] : ∀ {m A} {xs ys : Stream A}
(xs≈ys : ∞ (xs ≈[ m ]P ys)) → xs ≈[ next m ]P ys
_∷_ : ∀ {m A} (x : A) {xs ys}
(xs≈ys : ♭ xs ≈[ ♭ m ]P ♭ ys) → x ∷ xs ≈[ cons m ]P x ∷ ys
tail : ∀ {m A} {xs ys : Stream A} (xs≈ys : xs ≈[ m ]P ys) →
S.tail xs ≈[ tailC m ]P S.tail ys
evens : ∀ {m A} {xs ys : Stream A} (xs≈ys : xs ≈[ m ]P ys) →
S.evens xs ≈[ evensC m ]P S.evens ys
odds : ∀ {m A} {xs ys : Stream A} (xs≈ys : xs ≈[ m ]P ys) →
S.odds xs ≈[ oddsC m ]P S.odds ys
_⋎_ : ∀ {m m′ A} {xs xs′ ys ys′ : Stream A}
(xs≈ys : xs ≈[ m ]P ys) (xs′≈ys′ : xs′ ≈[ m′ ]P ys′) →
(xs ⟨ S._⋎_ ⟩ xs′) ≈[ m ⋎C m′ ]P (ys ⟨ S._⋎_ ⟩ ys′)
map : ∀ {m A B} (f : A → B) {xs ys : Stream A}
(xs≈ys : xs ≈[ m ]P ys) → S.map f xs ≈[ m ]P S.map f ys
cast : ∀ {m m′ A} (ok : m ≈C m′) {xs ys : Stream A}
(xs≈ys : xs ≈[ m ]P ys) → xs ≈[ m′ ]P ys
_≈⟨_⟩P_ : ∀ {m A} xs {ys zs : Stream A}
(xs≈ys : xs ≈[ m ]P ys) (ys≈zs : ys ≈ zs) → xs ≈[ m ]P zs
_≈⟨_⟩_ : ∀ {m A} xs {ys zs : Stream A}
(xs≈ys : xs ≈ ys) (ys≈zs : ys ≈[ m ]P zs) → xs ≈[ m ]P zs
data _≈[_]W_ : {A : Set} → Stream A → Chunks → Stream A → Set₁ where
[_] : ∀ {m A} {xs ys : Stream A}
(xs≈ys : xs ≈[ m ]P ys) → xs ≈[ next m ]W ys
_∷_ : ∀ {m A} (x : A) {xs ys}
(xs≈ys : ♭ xs ≈[ ♭ m ]W ♭ ys) → x ∷ xs ≈[ cons m ]W x ∷ ys
program≈ : ∀ {m A} {xs ys : Stream A} → xs ≈[ m ]W ys → xs ≈[ m ]P ys
program≈ [ xs≈ys ] = [ ♯ xs≈ys ]
program≈ (x ∷ xs≈ys) = x ∷ program≈ xs≈ys
tail-congW : ∀ {m A} {xs ys : Stream A} → xs ≈[ m ]W ys →
S.tail xs ≈[ tailC m ]W S.tail ys
tail-congW [ xs≈ys ] = [ tail xs≈ys ]
tail-congW (x ∷ xs≈ys) = xs≈ys
mutual
evens-congW : ∀ {m A} {xs ys : Stream A} →
xs ≈[ m ]W ys → S.evens xs ≈[ evensC m ]W S.evens ys
evens-congW [ xs≈ys ] = [ evens xs≈ys ]
evens-congW (x ∷ xs≈ys) = x ∷ odds-congW xs≈ys
odds-congW : ∀ {m A} {xs ys : Stream A} →
xs ≈[ m ]W ys → S.odds xs ≈[ oddsC m ]W S.odds ys
odds-congW [ xs≈ys ] = [ odds xs≈ys ]
odds-congW (x ∷ xs≈ys) = evens-congW xs≈ys
infixr 5 _⋎-congW_
-- Note: Uses swapping of arguments.
_⋎-congW_ : ∀ {m m′ A} {xs xs′ ys ys′ : Stream A} →
xs ≈[ m ]W ys → xs′ ≈[ m′ ]W ys′ →
(xs ⟨ S._⋎_ ⟩ xs′) ≈[ m ⋎C m′ ]W (ys ⟨ S._⋎_ ⟩ ys′)
[ xs≈ys ] ⋎-congW [ xs′≈ys′ ] = [ xs≈ys ⋎ xs′≈ys′ ]
[ xs≈ys ] ⋎-congW (y ∷ xs′≈ys′) = [ xs≈ys ⋎ program≈ (y ∷ xs′≈ys′) ]
(x ∷ xs≈ys) ⋎-congW xs′≈ys′ = x ∷ xs′≈ys′ ⋎-congW xs≈ys
map-congW : ∀ {m A B} (f : A → B) {xs ys : Stream A} →
xs ≈[ m ]W ys → S.map f xs ≈[ m ]W S.map f ys
map-congW f [ xs≈ys ] = [ map f xs≈ys ]
map-congW f (x ∷ xs≈ys) = f x ∷ map-congW f xs≈ys
cast-congW : ∀ {m m′ A} (ok : m ≈C m′) {xs ys : Stream A} →
xs ≈[ m ]W ys → xs ≈[ m′ ]W ys
cast-congW (next m≈m′) [ xs≈ys ] = [ cast m≈m′ xs≈ys ]
cast-congW (cons m≈m′) (x ∷ xs≈ys) = x ∷ cast-congW (♭ m≈m′) xs≈ys
transPW : ∀ {m A} {xs ys zs : Stream A} →
xs ≈[ m ]W ys → ys ≈ zs → xs ≈[ m ]W zs
transPW [ xs≈ys ] ys≈zs = [ _ ≈⟨ xs≈ys ⟩P ys≈zs ]
transPW (x ∷ xs≈ys) (P.refl ∷ ys≈zs) = x ∷ transPW xs≈ys (♭ ys≈zs)
transW : ∀ {m A} {xs ys zs : Stream A} →
xs ≈ ys → ys ≈[ m ]W zs → xs ≈[ m ]W zs
transW (x ∷ xs≈ys) [ ys≈zs ] = [ _ ≈⟨ x ∷ xs≈ys ⟩ ys≈zs ]
transW (P.refl ∷ xs≈ys) (x ∷ ys≈zs) = x ∷ transW (♭ xs≈ys) ys≈zs
whnf≈ : ∀ {m A} {xs ys : Stream A} → xs ≈[ m ]P ys → xs ≈[ m ]W ys
whnf≈ [ xs ] = [ ♭ xs ]
whnf≈ (x ∷ xs) = x ∷ whnf≈ xs
whnf≈ (tail xs) = tail-congW (whnf≈ xs)
whnf≈ (evens xs) = evens-congW (whnf≈ xs)
whnf≈ (odds xs) = odds-congW (whnf≈ xs)
whnf≈ (xs ⋎ ys) = whnf≈ xs ⋎-congW whnf≈ ys
whnf≈ (map f xs) = map-congW f (whnf≈ xs)
whnf≈ (cast m≈m′ xs) = cast-congW m≈m′ (whnf≈ xs)
whnf≈ (xs ≈⟨ xs≈ys ⟩P ys≈zs) = transPW (whnf≈ xs≈ys) ys≈zs
whnf≈ (xs ≈⟨ xs≈ys ⟩ ys≈zs) = transW xs≈ys (whnf≈ ys≈zs)
mutual
soundW : ∀ {m A} {xs ys : Stream A} → xs ≈[ m ]W ys → xs ≈ ys
soundW [ xs≈ys ] = soundP xs≈ys
soundW (x ∷ xs≈ys) = P.refl ∷ ♯ soundW xs≈ys
soundP : ∀ {m A} {xs ys : Stream A} → xs ≈[ m ]P ys → xs ≈ ys
soundP xs≈ys = soundW (whnf≈ xs≈ys)
------------------------------------------------------------------------
-- The definition is correct
-- The proof consists mostly of boiler-plate code.
program-hom : ∀ {m A} (xs : StreamW m A) → ⟦ program xs ⟧P ≈ ⟦ xs ⟧W
program-hom [ xs ] = SS.refl
program-hom (x ∷ xs) = P.refl ∷ ♯ program-hom xs
mutual
tailW-hom : ∀ {A : Set} {m} (xs : StreamW m A) →
⟦ tailW xs ⟧W ≈ S.tail ⟦ xs ⟧W
tailW-hom [ xs ] = tail-hom xs
tailW-hom (x ∷ xs) = SS.refl
tail-hom : ∀ {A : Set} {m} (xs : StreamP m A) →
⟦ tail xs ⟧P ≈ S.tail ⟦ xs ⟧P
tail-hom xs = tailW-hom (whnf xs)
mutual
infixr 5 _⋎W-hom_ _⋎-hom_
-- Note: Uses swapping of arguments.
_⋎W-hom_ : ∀ {A : Set} {m m′} (xs : StreamW m A) (ys : StreamW m′ A) →
⟦ xs ⋎W ys ⟧W ≈[ m ⋎C m′ ]P (⟦ xs ⟧W ⟨ S._⋎_ ⟩ ⟦ ys ⟧W)
(x ∷ xs) ⋎W-hom ys = x ∷ ys ⋎W-hom xs
[ xs ] ⋎W-hom [ ys ] = [ ♯ (xs ⋎-hom ys) ]
[ xs ] ⋎W-hom (y ∷ ys′) =
[ ♯ (⟦ xs ⋎ program ys ⟧P ≈⟨ xs ⋎-hom program ys ⟩P (begin
(⟦ xs ⟧P ⟨ S._⋎_ ⟩ ⟦ program ys ⟧P) SR.≈⟨ SS.refl ⟨ S._⋎-cong_ ⟩ program-hom ys ⟩
(⟦ xs ⟧P ⟨ S._⋎_ ⟩ ⟦ ys ⟧W) ∎)) ]
where ys = y ∷ ys′
_⋎-hom_ : ∀ {A : Set} {m m′} (xs : StreamP m A) (ys : StreamP m′ A) →
⟦ xs ⋎ ys ⟧P ≈[ m ⋎C m′ ]P (⟦ xs ⟧P ⟨ S._⋎_ ⟩ ⟦ ys ⟧P)
xs ⋎-hom ys = whnf xs ⋎W-hom whnf ys
mutual
evensW-hom : ∀ {A : Set} {m} (xs : StreamW m A) →
⟦ evensW xs ⟧W ≈ S.evens ⟦ xs ⟧W
evensW-hom [ xs ] = evens-hom xs
evensW-hom (x ∷ xs) = P.refl ∷ ♯ oddsW-hom xs
evens-hom : ∀ {A : Set} {m} (xs : StreamP m A) →
⟦ evens xs ⟧P ≈ S.evens ⟦ xs ⟧P
evens-hom xs = evensW-hom (whnf xs)
oddsW-hom : ∀ {A : Set} {m} (xs : StreamW m A) →
⟦ oddsW xs ⟧W ≈ S.odds ⟦ xs ⟧W
oddsW-hom [ xs ] = odds-hom xs
oddsW-hom (x ∷ xs) = evensW-hom xs
odds-hom : ∀ {A : Set} {m} (xs : StreamP m A) →
⟦ odds xs ⟧P ≈ S.odds ⟦ xs ⟧P
odds-hom xs = oddsW-hom (whnf xs)
mutual
mapW-hom : ∀ {A B : Set} {m} (f : A → B) (xs : StreamW m A) →
⟦ mapW f xs ⟧W ≈ S.map f ⟦ xs ⟧W
mapW-hom f [ xs ] = map-hom f xs
mapW-hom f (x ∷ xs) = P.refl ∷ ♯ mapW-hom f xs
map-hom : ∀ {A B : Set} {m} (f : A → B) (xs : StreamP m A) →
⟦ map f xs ⟧P ≈ S.map f ⟦ xs ⟧P
map-hom f xs = mapW-hom f (whnf xs)
mutual
castW-hom : ∀ {m m′ A} (m≈m′ : m ≈C m′) (xs : StreamW m A) →
⟦ castW m≈m′ xs ⟧W ≈ ⟦ xs ⟧W
castW-hom (next m≈m′) [ xs ] = cast-hom m≈m′ xs
castW-hom (cons m≈m′) (x ∷ xs) = P.refl ∷ ♯ castW-hom (♭ m≈m′) xs
cast-hom : ∀ {m m′ A} (m≈m′ : m ≈C m′) (xs : StreamP m A) →
⟦ cast m≈m′ xs ⟧P ≈ ⟦ xs ⟧P
cast-hom m≈m′ xs = castW-hom m≈m′ (whnf xs)
-- The intended definition of the Thue-Morse sequence is bs = rhs bs.
rhs : Stream Bool → Stream Bool
rhs bs = false ∷ ♯ (S.map not (S.evens bs) ⟨ S._⋎_ ⟩ S.tail bs)
-- The definition above satisfies the intended defining equation.
correct : ⟦ thueMorse ⟧P ≈[ [cn]³[ccn]ω ]P rhs ⟦ thueMorse ⟧P
correct = false ∷ [ ♯ cast lemma (
⟦ cast lemma (map not (evens thueMorse) ⋎ tail thueMorse) ⟧P ≈⟨ cast-hom lemma (map not (evens thueMorse) ⋎ tail thueMorse) ⟩
⟦ map not (evens thueMorse) ⋎ tail thueMorse ⟧P ≈⟨ map not (evens thueMorse) ⋎-hom tail thueMorse ⟩P (begin
(⟦ map not (evens thueMorse) ⟧P ⟨ S._⋎_ ⟩ ⟦ tail thueMorse ⟧P) SR.≈⟨ SS.trans (map-hom not (evens thueMorse))
(S.map-cong not (evens-hom thueMorse))
⟨ S._⋎-cong_ ⟩
tail-hom thueMorse ⟩
(S.map not (S.evens ⟦ thueMorse ⟧P) ⟨ S._⋎_ ⟩ S.tail ⟦ thueMorse ⟧P) ∎ )) ]
-- The defining equation has at most one solution.
unique : ∀ bs bs′ → bs ≈ rhs bs → bs′ ≈ rhs bs′ → bs ≈[ [cn]³[ccn]ω ]P bs′
unique bs bs′ bs≈ bs′≈ =
bs ≈⟨ bs≈ ⟩
rhs bs ≈⟨ false ∷ [ ♯ cast lemma
(map not (evens (unique bs bs′ bs≈ bs′≈))
⋎
tail (unique bs bs′ bs≈ bs′≈)) ] ⟩P (begin
rhs bs′ SR.≈⟨ SS.sym bs′≈ ⟩
bs′ ∎)
|
#' Create marts for b36-38
#'
#' Slow to create these so just make once and save
#'
#' @export
#' @return Saves data to data/marts.rdata
create_marts <- function()
{
mart38 <- useDataset(mart=useMart("ENSEMBL_MART_SNP"), dataset="hsapiens_snp")
mart37 <- useMart(biomart="ENSEMBL_MART_SNP", host="grch37.ensembl.org", path="/biomart/martservice", dataset="hsapiens_snp")
mart36 <- useDataset(mart=useMart("ENSEMBL_MART_SNP", host="http://may2009.archive.ensembl.org"), dataset="hsapiens_snp")
save(mart36, mart37, mart38, file="data/marts.rdata")
}
#' Create dataset of some hm3 SNPs and their build positions
#'
#' @export
#' @return saves build_ref object
create_build_reference <- function()
{
set.seed(314159)
hm3 <- scan("inst/extdata/hapmap3_autosome.snplist", character()) %>% sample(., 300000)
gwasvcf::set_bcftools()
vcf <- gwasvcf::query_gwas("~/data/gwas/ieu-a-2/ieu-a-2.vcf.gz", rsid=hm3)
b37 <- SummarizedExperiment::rowRanges(vcf)
b37$rsid <- names(b37)
GenomeInfoDb::seqlevels(b37) <- paste0("chr", GenomeInfoDb::seqlevels(b37))
ch36 <- rtracklayer::import.chain(system.file(package="GwasDataImport", "extdata", "hg19ToHg18.over.chain"))
b36 <- rtracklayer::liftOver(x=b37, chain=ch36) %>% unlist()
ch38 <- rtracklayer::import.chain(system.file(package="GwasDataImport", "extdata", "hg19ToHg38.over.chain"))
b38 <- rtracklayer::liftOver(x=b37, chain=ch38) %>% unlist()
b36 <- dplyr::tibble(rsid=b36$rsid, b36=GenomicRanges::start(b36))
b37 <- dplyr::tibble(rsid=b37$rsid, b37=GenomicRanges::start(b37))
b38 <- dplyr::tibble(rsid=b38$rsid, b38=GenomicRanges::start(b38))
build_ref <- merge(b36, b37, by="rsid")
build_ref <- merge(build_ref, b38, by="rsid")
save(build_ref, file="data/build_ref.rdata")
}
#' Lookup positions for given rsids in particular build
#'
#' @param rsid rsid
#' @param build build (36, 37 default or 38)
#' @param method "opengwas" (fastest) or "biomart"
#' @param splitsize Default 50000
#'
#' @export
#' @return data frame
get_positions <- function(rsid, build=37, method=c("opengwas", "biomart")[1], splitsize=50000)
{
if(length(rsid) > 100000)
{
message("This could take quite some time")
}
n <- length(rsid)
chunks <- ceiling(n/splitsize)
message("Splitting into ", chunks, " chunks of size ", splitsize, " each")
rsidl <- split(rsid, 1:chunks)
if(method == "opengwas")
{
if(build != 37)
{
stop("Only build 37 available on opengwas")
}
l <- list()
for(i in 1:length(rsidl))
{
message("Chunk ", i, " of ", chunks)
l[[i]] <- ieugwasr::afl2_rsid(rsidl[[i]])
}
b <- dplyr::bind_rows(l) %>%
dplyr::select(rsid, chr, pos=start)
missing <- rsid[! rsid %in% b$rsid]
if(length(missing) > 0)
{
message("Missing ", length(missing), " from first pass, continuing again")
chunks <- ceiling(length(missing)/splitsize)
missing <- split(missing, 1:chunks)
l <- list()
for(i in 1:length(missing))
{
message("Chunk ", i, " of ", chunks)
l[[i]] <- ieugwasr::variants_rsid(missing[[i]])
}
b1 <- dplyr::bind_rows(l) %>%
dplyr::select(rsid=query, chr, pos)
b <- dplyr::bind_rows(b, b1)
}
} else if(method == "biomart"){
data(marts)
message("looking up build ", build)
refsnp <- ifelse(build == 36, "refsnp", "snp_filter")
l <- list()
for(i in 1:length(rsidl))
{
message("Chunk ", i, " of ", chunks)
l[[i]] <- biomaRt::getBM(attributes = c('refsnp_id','chr_name', 'chrom_start'), filters = c(refsnp), values = rsidl[[i]], mart = get(paste0("mart", build))) %>%
dplyr::select(rsid=refsnp_id, chr=chr_name, pos=chrom_start)
}
} else {
stop("Method must be 'opengwas' or 'biomart'")
}
m <- match(rsid, b$rsid)
b <- b[m, ]
message("Found ", nrow(b), " of ", length(rsid), " rsids")
return(b)
}
#' Determines which build a set of SNPs are on
#'
#' @param rsid rsid
#' @param chr chr
#' @param pos pos
#' @param build Builds to try e.g. c(37,38,36)
#'
#' @export
#' @return build if detected, or dataframe of matches if not
determine_build_biomart <- function(rsid, chr, pos, build=c(37,38,36))
{
index <- sample(1:length(rsid), min(length(rsid), 500))
dat <- dplyr::tibble(rsid=rsid[index], chr=chr[index], pos=pos[index])
l <- list()
for(i in 1:length(build))
{
a <- get_positions(dat$rsid, build[i])
b <- dplyr::inner_join(a, dat, by=rsid)
n <- sum(b$chr.x == b$chr.y & b$pos.x == b$pos.y)
l[[i]] <- dplyr::tibble(
build=build[i],
prop_pos = n / nrow(b),
prop_found = nrow(b) / nrow(dat)
)
if(l[[i]]$prop_pos > 0.9 & l[[i]]$prop_found > 0.3)
{
return(build[i])
}
}
l %>% dplyr::bind_rows() %>% return()
}
#' Determine build based on reference dataset
#'
#' @param rsid rsid
#' @param chr chr
#' @param pos pos
#' @param build Builds to try e.g. c(37,38,36)
#' @param fallback Whether to try "position" (fast) or "biomart" (more accurate if you have rsids) based approaches instead
#'
#' @export
#' @return build if detected, or dataframe of matches if not
determine_build <- function(rsid, chr, pos, build=c(37,38,36), fallback="position")
{
index <- sample(1:length(rsid), min(length(rsid), 1000000))
dat <- dplyr::tibble(rsid=rsid[index], chr=chr[index], pos=pos[index])
data(build_ref)
dat2 <- merge(dat, build_ref, by="rsid")
if(nrow(dat) > 100000)
{
if(nrow(dat2) < 20)
{
message("Not enough variants in reference dataset")
if(fallback == "position")
{
message("Matching by position")
return(determine_build_position(pos, build))
}
if(fallback == "biomart")
{
message("Trying biomaRt")
return(determine_build_biomart(rsid, chr, pos, build))
} else {
return(data.frame())
}
}
} else {
if(nrow(dat2) < 20)
{
message("Failed to match in reference dataset")
if(biomart_fallback)
{
message("Trying biomaRt")
return(determine_build_biomart(rsid, chr, pos, build))
} else {
return(data.frame())
}
}
}
l <- list()
for(i in 1:length(build))
{
n <- sum(dat2$pos == dat2[[paste0("b", build[i])]])
l[[i]] <- dplyr::tibble(
build=build[i],
prop_pos = n / nrow(dat2),
n_found = nrow(dat2)
)
if(l[[i]]$prop_pos > 0.9 & l[[i]]$n_found > 20)
{
return(build[i])
}
}
l %>% dplyr::bind_rows() %>% return()
}
#' Determine build just from positions
#'
#' A bit sketchy but computationally fast - just assumes that there will be at least 50x more position matches in the true build than either of the others.
#'
#' @param pos Vector of positions
#' @param build c(37,38,36)
#' @param threshold how many times more in the true build than the others. default = 50
#'
#' @export
#' @return build or if not determined then dataframe
determine_build_position <- function(pos, build=c(37,38,36))
{
stopifnot(length(build) == 3)
data(build_ref)
l <- list()
for(i in 1:length(build))
{
n <- sum(pos %in% build_ref[[paste0("b", build[i])]])
l[[i]] <- dplyr::tibble(
build=build[i],
prop_pos = n / length(pos),
n_found = n
)
}
l <- dplyr::bind_rows(l)
print(l)
m <- which.max(l$n_found)
return(l$build[m])
}
#' Liftover GWAS positions
#'
#' Determine GWAS build and liftover to required build
#'
#' @param dat Data frame with chr, pos, snp name, effect allele, non-effect allele columns
#' @param build The possible builds to check data against Default = c(37,38,26)
#' @param to Which build to lift over to. Default=37
#' @param chr_col Name of chromosome column name. Required
#' @param pos_col Name of position column name. Required
#' @param snp_col Name of SNP column name. Optional. Uses less certain method of matching if not available
#' @param ea_col Name of effect allele column name. Optional. Might lead to duplicated rows if not presented
#' @param oa_col Name of other allele column name. Optional. Might lead to duplicated rows if not presented
#'
#' @export
#' @return Data frame
liftover_gwas <- function(dat, build=c(37,38,36), to=37, chr_col="chr", pos_col="pos", snp_col="snp", ea_col="ea", oa_col="oa", build_fallback="position")
{
if(is.null(snp_col))
{
message("Only using position")
from <- determine_build_position(dat[[pos_col]], build=build)
} else {
message("Using rsid")
from <- determine_build(dat[[snp_col]], dat[[chr_col]], dat[[pos_col]], build=build, fallback="position")
}
if(is.data.frame(from))
{
print(from)
stop("Cannot determine build")
} else {
if(from == to)
{
message("Already build ", to)
return(dat)
}
}
message("Lifting build: ", from, " to ", to)
tab <- dplyr::tibble(build=c(36,37,38), name=c("Hg18", "Hg19", "Hg38"))
path <- system.file(package="GwasDataImport", "extdata", paste0(
tolower(tab$name[tab$build==from]),
"To",
tab$name[tab$build==to],
".over.chain"
))
stopifnot(file.exists(path))
message("Loading chainfile")
ch <- rtracklayer::import.chain(path)
message("Converting chromosome codings")
if(!grepl("chr", dat[[chr_col]][1]))
{
dat[[chr_col]] <- paste0("chr", dat[[chr_col]])
}
dat[[chr_col]][dat[[chr_col]] == "chr23"] <- "chrX"
dat[[chr_col]][dat[[chr_col]] == "chr24"] <- "chrY"
dat[[chr_col]][dat[[chr_col]] == "chr25"] <- "chrXY"
dat[[chr_col]][dat[[chr_col]] == "chr26"] <- "chrM"
dat[[chr_col]][dat[[chr_col]] == "chrMT"] <- "chrM"
message("Organising")
datg <- GenomicRanges::GRanges(
seqnames=dat[[chr_col]],
ranges=IRanges::IRanges(start=dat[[pos_col]], end=dat[[pos_col]]),
ind=1:nrow(dat)
)
message("Lifting")
d19 <- rtracklayer::liftOver(datg, ch) %>% unlist()
message("Organising again")
dat <- dat[d19$ind,]
dat[[chr_col]] <- d19@seqnames
dat[[pos_col]] <- d19@ranges@start
dat[[chr_col]] <- gsub("chr", "", dat[[chr_col]])
message("Reordering")
dat <- dat[order(dat[[chr_col]], dat[[pos_col]]), ]
if(!is.null(ea_col) & !is.na(oa_col))
{
message("Removing duplicates")
nom <- names(dat)
if(is.numeric(chr_col)) chr_col <- nom[chr_col]
if(is.numeric(pos_col)) pos_col <- nom[pos_col]
if(is.numeric(ea_col)) ea_col <- nom[ea_col]
if(is.numeric(oa_col)) oa_col <- nom[oa_col]
dat <- distinct(dat, .data[[chr_col]], .data[[pos_col]], .data[[ea_col]], .data[[oa_col]], .keep_all=TRUE)
}
message("Done")
return(dat)
}
liftover_gwas_old <- function(dat, build=c(37,38,36), to=37, chr_col="chr", pos_col="pos", snp_col="snp", ea_col="ea", oa_col="oa", build_fallback="position")
{
if(is.null(snp_col))
{
message("Only using position")
from <- determine_build_position(dat[[pos_col]], build=build)
} else {
message("Using rsid")
from <- determine_build(dat[[snp_col]], dat[[chr_col]], dat[[pos_col]], build=build, fallback="position")
}
if(is.data.frame(from))
{
print(from)
stop("Cannot determine build")
} else {
if(from == to)
{
message("Already build ", to)
return(dat)
}
}
message("Lifting build: ", from, " to ", to)
tab <- dplyr::tibble(build=c(36,37,38), name=c("Hg18", "Hg19", "Hg38"))
path <- system.file(package="GwasDataImport", "extdata", paste0(
tolower(tab$name[tab$build==from]),
"To",
tab$name[tab$build==to],
".over.chain"
))
stopifnot(file.exists(path))
message("Loading chainfile")
ch <- rtracklayer::import.chain(path)
message("Converting chromosome codings")
if(!grepl("chr", dat[[chr_col]][1]))
{
dat[[chr_col]] <- paste0("chr", dat[[chr_col]])
}
dat[[chr_col]][dat[[chr_col]] == "chr23"] <- "chrX"
dat[[chr_col]][dat[[chr_col]] == "chr24"] <- "chrY"
dat[[chr_col]][dat[[chr_col]] == "chr25"] <- "chrXY"
dat[[chr_col]][dat[[chr_col]] == "chr26"] <- "chrM"
dat[[chr_col]][dat[[chr_col]] == "chrMT"] <- "chrM"
message("Organising")
datg <- GenomicRanges::GRanges(seqnames=dat[[chr_col]], ranges=IRanges::IRanges(start=dat[[pos_col]], end=dat[[pos_col]]), LIFTOVERCHRPOS=paste0(dat[[chr_col]], ":", dat[[pos_col]]))
message("Lifting")
d19 <- rtracklayer::liftOver(datg, ch) %>% unlist()
message("Organising again")
d19 <- d19 %>% dplyr::as_tibble() %>% dplyr::select(LIFTOVERCHRPOS=LIFTOVERCHRPOS, LIFTOVERCHR=seqnames, LIFTOVERPOS=start)
dat$LIFTOVERCHRPOS <- paste0(dat[[chr_col]], ":", dat[[pos_col]])
dat <- merge(dat, d19, by="LIFTOVERCHRPOS")
dat[[chr_col]] <- dat$LIFTOVERCHR
dat[[pos_col]] <- dat$LIFTOVERPOS
dat <- subset(dat, select=-c(LIFTOVERCHRPOS, LIFTOVERCHR, LIFTOVERPOS))
dat[[chr_col]] <- gsub("chr", "", dat[[chr_col]])
dat <- dat[order(dat[[chr_col]], dat[[pos_col]]), ] %>% dplyr::as_tibble()
if(!is.null(ea_col) & !is.na(oa_col))
{
dat$code <- paste(dat[[chr_col]], dat[[pos_col]], dat[[ea_col]], dat[[oa_col]])
dat <- subset(dat, !duplicated(code))
dat <- subset(dat, select=-c(code))
}
message("Done")
return(dat)
}
|
C Copyright(C) 1999-2020 National Technology & Engineering Solutions
C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C See packages/seacas/LICENSE for details
C=======================================================================
LOGICAL FUNCTION GRABRT ()
C=======================================================================
C --*** GRABRT *** (GRPLIB) Check cancel function (PLT)
C -- Written by Amy Gilkey - revised 04/28/87
C --
C --GRABRT checks the cancel flag. If it is set, it aborts pending
C --graphics and returns the terminal to alphanumeric mode.
C --In any case, the value of the cancel flag is returned as the
C --function value.
C --Routines Called:
C -- CPUIFC - (PLTLIB) Check interrupt flag
C -- PLTBEL - (PLTLIB) Ring bell
C -- PLTBGN - (PLTLIB) Erase display surface
C -- PLTFLU - (PLTLIB) Flush graphics buffer and set alphanumeric mode
C -- GRSNAP - (GRPLIB) Handle device frame snapping
LOGICAL CPUIFC
C --Return cancel flag
GRABRT = CPUIFC (.FALSE.)
IF (GRABRT) THEN
C --Abort plot that is being snapped
CALL GRSNAP ('ABORT', 0)
C --Flush buffer (do not erase screen), ring bell, set alphanumeric mode
CALL PLTFLU
CALL PLTBEL
CALL PLTFLU
C --Send abort message
WRITE (*, '(1X, A)') '*** Plot set aborted ***'
END IF
RETURN
END
|
From Coq Require Import ssreflect.
From stdpp Require Import base gmap.
From iris.proofmode Require Import tactics.
From aneris.prelude Require Import gset_map.
From aneris.aneris_lang.lib Require Import list_proof.
From aneris.aneris_lang.lib.serialization Require Import serialization_proof.
From aneris.aneris_lang Require Import aneris_lifting proofmode.
From aneris.examples.crdt.spec Require Import crdt_base crdt_time crdt_events crdt_denot crdt_resources.
From aneris.examples.crdt.oplib Require Import oplib_code.
From aneris.aneris_lang.lib Require Import inject.
From aneris.examples.crdt.oplib.spec Require Import model spec.
From aneris.examples.crdt.oplib.examples.lwwreg Require Import lwwreg_code lwwreg_proof.
From aneris.examples.crdt.oplib.examples.map_comb Require Import map_comb_code map_comb_proof.
From aneris.examples.crdt.oplib.examples.table_of_lwwregs Require Import table_of_lwwregs_code.
Section table_of_lwwregs_proof.
Context `{!EqDecision vl, !Countable vl}.
Context `{!Inject vl val}.
Context `{!∀ p : vl, Serializable vl_serialization $ p}.
Context `{!anerisG M Σ, !CRDT_Params, !OpLib_Res (mapOp (LWWOp vl))}.
Notation map_OpLib_Params' := (@map_OpLib_Params (LWWOp vl) _ _ _ _).
Notation map_init_st_fn_spec' := (@map_init_st_fn_spec (LWWOp vl)).
Notation map_effect_spec' := (@map_effect_spec (LWWOp vl)).
Lemma table_of_lwwregs_init_st_fn_spec :
⊢ @init_st_fn_spec _ _ _ _ _ _ _ map_OpLib_Params' table_of_lwwregs_init_st.
Proof.
iIntros (addr).
iIntros "!#" (Φ) "_ HΦ".
rewrite /table_of_lwwregs_init_st.
wp_pure _.
wp_apply map_init_st_fn_spec'; done.
Qed.
Lemma table_of_lwwregs_effect_spec :
⊢ @effect_spec _ _ _ _ _ _ _ map_OpLib_Params' table_of_lwwregs_effect.
Proof.
iIntros (addr ev st s log_ev log_st).
iIntros "!#" (Φ) "(%Hev & %Hst & %Hs & %Hevs) HΦ".
rewrite /table_of_lwwregs_effect.
wp_pures.
rewrite /map_comb_effect.
do 4 wp_pure _.
wp_apply map_effect_spec';
[iApply lww_register_init_st_fn_spec|iApply lww_register_effect_spec|done|done].
Qed.
Lemma table_of_lwwregs_crdt_fun_spec :
⊢ @crdt_fun_spec _ _ _ _ _ _ _ map_OpLib_Params' table_of_lwwregs_crdt.
Proof.
iIntros (addr).
iIntros "!#" (Φ) "_ HΦ".
rewrite /table_of_lwwregs_crdt.
wp_pures.
iApply "HΦ".
iExists _, _; iSplit; first done.
iSplit.
- iApply table_of_lwwregs_init_st_fn_spec; done.
- iApply table_of_lwwregs_effect_spec; done.
Qed.
Notation oplib_init' :=
(oplib_init
(s_ser (s_serializer (@OpLib_Serialization _ _ _ _ map_OpLib_Params')))
(s_deser (s_serializer (@OpLib_Serialization _ _ _ _ map_OpLib_Params')))).
Lemma table_of_lwwregs_init_spec :
@init_spec _ _ _ _ _ _ _ map_OpLib_Params' _ _ oplib_init' -∗
@init_spec_for_specific_crdt _ _ _ _ _ _ _ map_OpLib_Params' _ _
(table_of_lwwregs_init
(s_ser (s_serializer vl_serialization)) (s_deser (s_serializer vl_serialization))).
Proof.
iIntros "#Hinit" (repId addr addrs_val).
iIntros (Φ) "!# (%Haddrs & %Hrepid & Hprotos & Hskt & Hfr & Htoken) HΦ".
rewrite /table_of_lwwregs_init /table_of_lwwregs_crdt.
wp_pures.
wp_apply ("Hinit" with "[$Hprotos $Htoken $Hskt $Hfr]").
{ do 2 (iSplit; first done). iApply table_of_lwwregs_crdt_fun_spec; done. }
iIntros (get update) "(HLS & #Hget & #Hupdate)".
wp_pures.
iApply "HΦ"; eauto.
Qed.
End table_of_lwwregs_proof.
|
/-
Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Violeta Hernández Palacios
-/
import set_theory.ordinal_arithmetic
import topology.algebra.order.basic
/-!
### Topology of ordinals
We prove some miscellaneous results involving the order topology of ordinals.
### Main results
* `ordinal.is_closed_iff_sup` / `ordinal.is_closed_iff_bsup`: A set of ordinals is closed iff it's
closed under suprema.
* `ordinal.is_normal_iff_strict_mono_and_continuous`: A characterization of normal ordinal
functions.
* `ordinal.enum_ord_is_normal_iff_is_closed`: The function enumerating the ordinals of a set is
normal iff the set is closed.
-/
noncomputable theory
universes u v
open cardinal
namespace ordinal
instance : topological_space ordinal.{u} :=
preorder.topology ordinal.{u}
instance : order_topology ordinal.{u} :=
⟨rfl⟩
theorem is_open_singleton_iff {o : ordinal} : is_open ({o} : set ordinal) ↔ ¬ is_limit o :=
begin
refine ⟨λ h ho, _, λ ho, _⟩,
{ obtain ⟨a, b, hab, hab'⟩ := (mem_nhds_iff_exists_Ioo_subset'
⟨0, ordinal.pos_iff_ne_zero.2 ho.1⟩ ⟨_, lt_succ_self o⟩).1 (h.mem_nhds rfl),
have hao := ho.2 a hab.1,
exact hao.ne (hab' ⟨lt_succ_self a, hao.trans hab.2⟩) },
{ rcases zero_or_succ_or_limit o with rfl | ⟨a, ha⟩ | ho',
{ convert is_open_gt' (1 : ordinal),
ext,
exact ordinal.lt_one_iff_zero.symm },
{ convert @is_open_Ioo _ _ _ _ a (o + 1),
ext b,
refine ⟨λ hb, _, _⟩,
{ rw set.mem_singleton_iff.1 hb,
refine ⟨_, lt_succ_self o⟩,
rw ha,
exact lt_succ_self a },
{ rintro ⟨hb, hb'⟩,
apply le_antisymm (lt_succ.1 hb'),
rw ha,
exact ordinal.succ_le.2 hb } },
{ exact (ho ho').elim } }
end
theorem is_open_iff (s : set ordinal) :
is_open s ↔ (∀ o ∈ s, is_limit o → ∃ a < o, set.Ioo a o ⊆ s) :=
begin
classical,
refine ⟨_, λ h, _⟩,
{ rw is_open_iff_generate_intervals,
intros h o hos ho,
have ho₀ := ordinal.pos_iff_ne_zero.2 ho.1,
induction h with t ht t u ht hu ht' hu' t ht H,
{ rcases ht with ⟨a, rfl | rfl⟩,
{ exact ⟨a, hos, λ b hb, hb.1⟩ },
{ exact ⟨0, ho₀, λ b hb, hb.2.trans hos⟩ } },
{ exact ⟨0, ho₀, λ b _, set.mem_univ b⟩ },
{ rcases ht' hos.1 with ⟨a, ha, ha'⟩,
rcases hu' hos.2 with ⟨b, hb, hb'⟩,
exact ⟨_, max_lt ha hb, λ c hc, ⟨
ha' ⟨(le_max_left a b).trans_lt hc.1, hc.2⟩,
hb' ⟨(le_max_right a b).trans_lt hc.1, hc.2⟩⟩⟩ },
{ rcases hos with ⟨u, hu, hu'⟩,
rcases H u hu hu' with ⟨a, ha, ha'⟩,
exact ⟨a, ha, λ b hb, ⟨u, hu, ha' hb⟩⟩ } },
{ let f : s → set ordinal := λ o,
if ho : is_limit o.val
then set.Ioo (classical.some (h o.val o.prop ho)) (o + 1)
else {o.val},
have : ∀ a, is_open (f a) := λ a, begin
change is_open (dite _ _ _),
split_ifs,
{ exact is_open_Ioo },
{ rwa is_open_singleton_iff }
end,
convert is_open_Union this,
ext o,
refine ⟨λ ho, set.mem_Union.2 ⟨⟨o, ho⟩, _⟩, _⟩,
{ split_ifs with ho',
{ refine ⟨_, lt_succ_self o⟩,
cases classical.some_spec (h o ho ho') with H,
exact H },
{ exact set.mem_singleton o } },
{ rintro ⟨t, ⟨a, ht⟩, hoa⟩,
change dite _ _ _ = t at ht,
split_ifs at ht with ha;
subst ht,
{ cases classical.some_spec (h a.val a.prop ha) with H has,
rcases lt_or_eq_of_le (lt_succ.1 hoa.2) with hoa' | rfl,
{ exact has ⟨hoa.1, hoa'⟩ },
{ exact a.prop } },
{ convert a.prop } } }
end
theorem mem_closure_iff_sup {s : set ordinal.{u}} {a : ordinal.{u}} :
a ∈ closure s ↔ ∃ {ι : Type u} [nonempty ι] (f : ι → ordinal.{u}),
(∀ i, f i ∈ s) ∧ sup.{u u} f = a :=
begin
refine mem_closure_iff.trans ⟨λ h, _, _⟩,
{ by_cases has : a ∈ s,
{ exact ⟨punit, by apply_instance, λ _, a, λ _, has, sup_const a⟩ },
{ have H := λ b (hba : b < a), h _ (@is_open_Ioo _ _ _ _ b (a + 1)) ⟨hba, lt_succ_self a⟩,
let f : a.out.α → ordinal := λ i, classical.some (H (typein (<) i) (typein_lt_self i)),
have hf : ∀ i, f i ∈ set.Ioo (typein (<) i) (a + 1) ∩ s :=
λ i, classical.some_spec (H _ _),
rcases eq_zero_or_pos a with rfl | ha₀,
{ rcases h _ (is_open_singleton_iff.2 not_zero_is_limit) rfl with ⟨b, hb, hb'⟩,
rw set.mem_singleton_iff.1 hb at *,
exact (has hb').elim },
refine ⟨_, out_nonempty_iff_ne_zero.2 (ordinal.pos_iff_ne_zero.1 ha₀), f,
λ i, (hf i).2, le_antisymm (sup_le (λ i, lt_succ.1 (hf i).1.2)) _⟩,
by_contra' h,
cases H _ h with b hb,
rcases eq_or_lt_of_le (lt_succ.1 hb.1.2) with rfl | hba,
{ exact has hb.2 },
{ have : b < f (enum (<) b (by rwa type_lt)) := begin
have := (hf (enum (<) b (by rwa type_lt))).1.1,
rwa typein_enum at this
end,
have : b ≤ sup.{u u} f := this.le.trans (le_sup f _),
exact this.not_lt hb.1.1 } } },
{ rintro ⟨ι, ⟨i⟩, f, hf, rfl⟩ t ht hat,
cases eq_zero_or_pos (sup.{u u} f) with ha₀ ha₀,
{ rw ha₀ at hat,
use [0, hat],
convert hf i,
exact (sup_eq_zero_iff.1 ha₀ i).symm },
rcases (mem_nhds_iff_exists_Ioo_subset' ⟨0, ha₀⟩ ⟨_, lt_succ_self _⟩).1 (ht.mem_nhds hat) with
⟨b, c, ⟨hab, hac⟩, hbct⟩,
cases lt_sup.1 hab with i hi,
exact ⟨_, hbct ⟨hi, (le_sup.{u u} f i).trans_lt hac⟩, hf i⟩ }
end
theorem mem_closed_iff_sup {s : set ordinal.{u}} {a : ordinal.{u}} (hs : is_closed s) :
a ∈ s ↔ ∃ {ι : Type u} (hι : nonempty ι) (f : ι → ordinal.{u}),
(∀ i, f i ∈ s) ∧ sup.{u u} f = a :=
by rw [←mem_closure_iff_sup, hs.closure_eq]
theorem mem_closure_iff_bsup {s : set ordinal.{u}} {a : ordinal.{u}} :
a ∈ closure s ↔ ∃ {o : ordinal} (ho : o ≠ 0) (f : Π a < o, ordinal.{u}),
(∀ i hi, f i hi ∈ s) ∧ bsup.{u u} o f = a :=
mem_closure_iff_sup.trans ⟨
λ ⟨ι, ⟨i⟩, f, hf, ha⟩, ⟨_, λ h, (type_eq_zero_iff_is_empty.1 h).elim i, bfamily_of_family f,
λ i hi, hf _, by rwa bsup_eq_sup⟩,
λ ⟨o, ho, f, hf, ha⟩, ⟨_, out_nonempty_iff_ne_zero.2 ho, family_of_bfamily o f,
λ i, hf _ _, by rwa sup_eq_bsup⟩⟩
theorem mem_closed_iff_bsup {s : set ordinal.{u}} {a : ordinal.{u}} (hs : is_closed s) :
a ∈ s ↔ ∃ {o : ordinal} (ho : o ≠ 0) (f : Π a < o, ordinal.{u}),
(∀ i hi, f i hi ∈ s) ∧ bsup.{u u} o f = a :=
by rw [←mem_closure_iff_bsup, hs.closure_eq]
theorem is_closed_iff_sup {s : set ordinal.{u}} :
is_closed s ↔ ∀ {ι : Type u} (hι : nonempty ι) (f : ι → ordinal.{u}),
(∀ i, f i ∈ s) → sup.{u u} f ∈ s :=
begin
use λ hs ι hι f hf, (mem_closed_iff_sup hs).2 ⟨ι, hι, f, hf, rfl⟩,
rw ←closure_subset_iff_is_closed,
intros h x hx,
rcases mem_closure_iff_sup.1 hx with ⟨ι, hι, f, hf, rfl⟩,
exact h hι f hf
end
theorem is_closed_iff_bsup {s : set ordinal.{u}} :
is_closed s ↔ ∀ {o : ordinal.{u}} (ho : o ≠ 0) (f : Π a < o, ordinal.{u}),
(∀ i hi, f i hi ∈ s) → bsup.{u u} o f ∈ s :=
begin
rw is_closed_iff_sup,
refine ⟨λ H o ho f hf, H (out_nonempty_iff_ne_zero.2 ho) _ _, λ H ι hι f hf, _⟩,
{ exact λ i, hf _ _ },
{ rw ←bsup_eq_sup,
apply H (type_ne_zero_iff_nonempty.2 hι),
exact λ i hi, hf _ }
end
theorem is_limit_of_mem_frontier {s : set ordinal} {o : ordinal} (ho : o ∈ frontier s) :
is_limit o :=
begin
simp only [frontier_eq_closure_inter_closure, set.mem_inter_iff, mem_closure_iff] at ho,
by_contra h,
rw ←is_open_singleton_iff at h,
rcases ho.1 _ h rfl with ⟨a, ha, ha'⟩,
rcases ho.2 _ h rfl with ⟨b, hb, hb'⟩,
rw set.mem_singleton_iff at *,
subst ha, subst hb,
exact hb' ha'
end
theorem is_normal_iff_strict_mono_and_continuous (f : ordinal.{u} → ordinal.{u}) :
is_normal f ↔ (strict_mono f ∧ continuous f) :=
begin
refine ⟨λ h, ⟨h.strict_mono, _⟩, _⟩,
{ rw continuous_def,
intros s hs,
rw is_open_iff at *,
intros o ho ho',
rcases hs _ ho (h.is_limit ho') with ⟨a, ha, has⟩,
rw [←is_normal.bsup_eq.{u u} h ho', lt_bsup] at ha,
rcases ha with ⟨b, hb, hab⟩,
exact ⟨b, hb, λ c hc,
set.mem_preimage.2 (has ⟨hab.trans (h.strict_mono hc.1), h.strict_mono hc.2⟩)⟩ },
{ rw is_normal_iff_strict_mono_limit,
rintro ⟨h, h'⟩,
refine ⟨h, λ o ho a h, _⟩,
suffices : o ∈ (f ⁻¹' set.Iic a), from set.mem_preimage.1 this,
rw mem_closed_iff_sup (is_closed.preimage h' (@is_closed_Iic _ _ _ _ a)),
exact ⟨_, out_nonempty_iff_ne_zero.2 ho.1, typein (<),
λ i, h _ (typein_lt_self i), sup_typein_limit ho.2⟩ }
end
theorem enum_ord_is_normal_iff_is_closed {S : set ordinal.{u}} (hS : S.unbounded (<)) :
is_normal (enum_ord S) ↔ is_closed S :=
begin
have HS := enum_ord_strict_mono hS,
refine ⟨λ h, is_closed_iff_sup.2 (λ ι hι f hf, _),
λ h, (is_normal_iff_strict_mono_limit _).2 ⟨HS, λ a ha o H, _⟩⟩,
{ let g : ι → ordinal.{u} := λ i, (enum_ord_order_iso hS).symm ⟨_, hf i⟩,
suffices : enum_ord S (sup.{u u} g) = sup.{u u} f,
{ rw ←this, exact enum_ord_mem hS _ },
rw is_normal.sup.{u u u} h g hι,
congr, ext,
change ((enum_ord_order_iso hS) _).val = f x,
rw order_iso.apply_symm_apply },
{ rw is_closed_iff_bsup at h,
suffices : enum_ord S a ≤ bsup.{u u} a (λ b < a, enum_ord S b), from this.trans (bsup_le H),
cases enum_ord_surjective hS _ (h ha.1 (λ b hb, enum_ord S b) (λ b hb, enum_ord_mem hS b))
with b hb,
rw ←hb,
apply HS.monotone,
by_contra' hba,
apply (HS (lt_succ_self b)).not_le,
rw hb,
exact le_bsup.{u u} _ _ (ha.2 _ hba) }
end
end ordinal
|
#! /usr/bin/env Rscript
library(muHVT)
library(MASS)
args <- commandArgs(trailing = TRUE)
D <- as.integer(args[1])
n <- as.integer(args[2])
N <- as.integer(args[3])
print(D)
print(n)
print(N)
generate_standard_normal_voronoi <- function(N, d, n_clusters)
{
mu <- c(rep(0, d))
sigma <- diag(d)
samples <- mvrnorm(N, mu = mu, Sigma = sigma )
hvt.results <- list()
hvt.results <- muHVT::HVT(samples,
nclust = n_clusters,
depth = 1,
quant.err = 0.2,
projection.scale = 10,
normalize = T,
distance_metric = "L2_Norm",
error_metric = "mean")
hvt.results[[3]][['summary']]['n'] <- hvt.results[[3]][['summary']]['n']/N
list(hvt.results[[3]][['summary']], samples)
}
set.seed(Sys.time())
result = generate_standard_normal_voronoi(N=N, d=D, n_clusters=n)
rsamples <- result[[2]]
quantized_samples <- result[[1]]
write.csv(quantized_samples, 'grid.dat',row.names = FALSE) |
%% This is an evolving article style
%% steeling ideas from different places
\documentclass[12pt,english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage{babel}
\usepackage[linktocpage,colorlinks,urlcolor=blue,pdfstartview=FitH]{hyperref}
\newcommand{\boldsymbol}[1]{\mbox{\boldmath $#1$}}
\newcommand{\N}{\mbox{$I\!\!N$}}
\newcommand{\Z}{\mbox{$Z\!\!\!Z$}}
\newcommand{\Q}{\mbox{$I\:\!\!\!\!\!Q$}}
\newcommand{\R}{\mbox{$I\!\!R$}}
\makeindex
\makeatletter
\makeatother
\begin{document}
\title{Calculating the Fisher Information Matrix \\
for Parameter Fitting}
\author{Stefan Hoops\\
Virginia Bioinformatics Institute - 0477\\
Virginia Tech\\
Bioinformatics Facility I\\
Blacksburg, VA 24061 \\
USA \\
\href{mailto:Stefan Hoops <[email protected]>}{[email protected]}}
\date{2005-11-11}
\maketitle
\begin{abstract}
The \href{http://planetmath.org/encyclopedia/FisherInformationMatrix.html}
{Fisher Information Matrix} $\boldsymbol{I}$ is a measure for how much
information is known about a parameter set $\boldsymbol{\theta}$. The
\href{http://planetmath.org/encyclopedia/CovarianceMatrix.html}
{covariance matrix} $C$ of the parameter set is bound by the
Cram\'er-Rao inequality $\boldsymbol{C} \ge \boldsymbol{I}^{-1}$ from
below. This allows us to judge the quality of the fitted parameter
set.
\end{abstract}
\section{Calculating the Fisher Information Matrix}
Let $\boldsymbol{X} \in \R^{n}$ be a vector denoting the $n$
measurements we intend to fit with a model depending on $p$ parameters
denoted by $\boldsymbol{\theta} \in \R^{p}$. For our model we assume
that the value $X_k$ is given by a normal distribution
$\boldsymbol{\emph{N}}(\mu_k, \sigma_k^2)$. The mean value $\mu_k$
must obviously depend on the parameter set $\boldsymbol{\theta}$. Whereas
the variance $\sigma_i^2$ is not influenced by the
parameters and we assume that $\sigma_k^2 = 1/2$ for all $n$
measurements. This leads us to the
\href{http://planetmath.org/encyclopedia/Distribution.html}
{probability density function} for
$X_k$
%
\begin{eqnarray}\label{PDF}
p(X_k|\boldsymbol{\theta}) =
\frac{1}{\sqrt{\pi}}
\exp\left(-(X_k - \mu_k(\boldsymbol{\theta}))^2\right)
\end{eqnarray}
%
which gives rise to the
\href{http://planetmath.org/encyclopedia/LikelihoodFunction.html}
{likelihood function}
%
\begin{eqnarray}\label{likelyhood}
L(\boldsymbol{\theta}|\boldsymbol{X}) =
\pi^{-\frac{n}{2}}
\exp\left(- \sum_{k=0}^{n} (X_k - \mu_k(\boldsymbol{\theta}))^2\right)
\end{eqnarray}
%
and the more convenient log likelihood function
%
\begin{eqnarray}\label{loglikelyhood}
l(\boldsymbol{\theta}|\boldsymbol{X}) =
- \frac{n}{2}\ln(\pi)
- \sum_{k=0}^{n}(X_k - \mu_k(\boldsymbol{\theta}))^2
\end{eqnarray}
%
The Fisher Information Matrix $\boldsymbol{I}$ is defined by
\begin{eqnarray}\label{Fisher}
\boldsymbol{I}_{i, j}(\boldsymbol{\theta})) =
\mbox{\bf E}
\left(
-\frac{\partial^2 \, l(\boldsymbol{\theta}|\boldsymbol{X})}
{\partial \theta_i \; \partial \theta_j}
\right)
\end{eqnarray}
where {\bf E} denotes the
\href{http://planetmath.org/encyclopedia/ExpectedValue.html}
{expectation value} and $i$ and $j$ are in
$1, \ldots, p$.
%
\begin{eqnarray}
\boldsymbol{I}_{i, j}(\boldsymbol{\theta}))
& = &
\mbox{\bf E}
\left(
-\frac{\partial}
{\partial \theta_i}
\left(
\frac{\partial \, l(\boldsymbol{\theta}|\boldsymbol{X})}
{\partial \theta_j}
\right)
\right)\\
& = &
\mbox{\bf E}
\left(
-2 \frac{\partial}
{\partial \theta_i}
\sum_{k=0}^{n}(X_k - \mu_k(\boldsymbol{\theta}))
\frac{\mu_k(\boldsymbol{\theta})}{\partial \theta_j}
\right)\\
& = &
\mbox{\bf E}
\left(
2 \sum_{k=0}^{n}
\frac{\mu_k(\boldsymbol{\theta})}{\partial \theta_i}
\frac{\mu_k(\boldsymbol{\theta})}{\partial \theta_j}
- 2
\sum_{k=0}^{n}
(X_k - \mu_k(\boldsymbol{\theta}))
\frac{\partial^2 \, \mu_k(\boldsymbol{\theta})}
{\partial \theta_i \; \partial \theta_j}
\right)\\
& = &
2 \sum_{k=0}^{n}
\frac{\mu_k(\boldsymbol{\theta})}{\partial \theta_i}
\frac{\mu_k(\boldsymbol{\theta})}{\partial \theta_j}
\end{eqnarray}
%
In the last equality we made use of the fact that the expectation
value of $X_k$ is $\mu_k(\boldsymbol{\theta})$.
\end{document}
|
\openepigraph{We have usually no knowledge that any one factor will exert its effects independently of all others that can be varied, or that its effects are particularly simply related to variations in these other factors.} {---Ronald Fisher}
In Chapter 1 we briefly described a study conducted by Simone Schnall and her colleagues, in which they found that washing one's hands leads people to view moral transgressions as less wrong \citep{schnall_clean_2008}. In a different but related study, Schnall and her colleagues investigated whether feeling physically disgusted causes people to make harsher moral judgments \citep{schnall_disgust_2008}. In this experiment, they manipulated participants' feelings of disgust by testing them in either a clean room or a messy room that contained dirty dishes, an overflowing wastebasket, and a chewed-up pen. They also used a self-report questionnaire to measure the amount of attention that people pay to their own bodily sensations. They called this "private body consciousness." They measured their primary dependent variable, the harshness of people's moral judgments, by describing different behaviors (e.g., eating one's dead dog, failing to return a found wallet) and having participants rate the moral acceptability of each one on a scale of 1 to 7. They also measured some other dependent variables, including participants' willingness to eat at a new restaurant. Finally, the researchers asked participants to rate their current level of disgust and other emotions. The primary results of this study were that participants in the messy room were in fact more disgusted and made harsher moral judgments than participants in the clean room---but only if they scored relatively high in private body consciousness.
The research designs we have considered so far have been simple---focusing on a question about one variable or about a statistical relationship between two variables. But in many ways the complex design of this experiment undertaken by Schnall and her colleagues is more typical of research in psychology. Fortunately, we have already covered the basic elements of such designs in previous chapters. In this chapter, we look closely at how and why researchers combine these basic elements into more complex designs. We start with complex experiments---considering first the inclusion of multiple dependent variables and then the inclusion of multiple independent variables. Finally, we look at complex correlational designs.
\section{Multiple Dependent Variables}
\marginnote{\allcaps{Learning Objectives}
\begin{enumerate}
\item Explain why researchers often include multiple dependent variables in their studies.
\item Explain what a manipulation check is and when it would be included in an experiment.
\end{enumerate}
}
Imagine that you have made the effort to find a research topic, review the research literature, formulate a question, design an experiment, obtain research ethics board (REB) approval, recruit research participants, and manipulate an independent variable. It would seem almost wasteful to measure a single dependent variable. Even if you are primarily interested in the relationship between an independent variable and one primary dependent variable, there are usually several more questions that you can answer easily by including multiple dependent variables.
\subsection{Measures of Different Constructs}
Often a researcher wants to know how an independent variable affects several distinct dependent variables. For example, Schnall and her colleagues were interested in how feeling disgusted affects the harshness of people's moral judgments, but they were also curious about how disgust affects other variables, such as people's willingness to eat in a restaurant. As another example, researcher Susan Knasko was interested in how different odors affect people's behavior \citep{knasko_ambient_1992}. She conducted an experiment in which the independent variable was whether participants were tested in a room with no odor or in one scented with lemon, lavender, or dimethyl sulfide (which has a cabbage-like smell). Although she was primarily interested in how the odors affected people's creativity, she was also curious about how they affected people's moods and perceived health---and it was a simple enough matter to measure these dependent variables too. Although she found that creativity was unaffected by the ambient odor, she found that people's moods were lower in the dimethyl sulfide condition, and that their perceived health was greater in the lemon condition.
When an experiment includes multiple dependent variables, there is again a possibility of carryover effects. For example, it is possible that measuring participants' moods before measuring their perceived health could affect their perceived health or that measuring their perceived health before their moods could affect their moods. So the order in which multiple dependent variables are measured becomes an issue. One approach is to measure them in the same order for all participants---usually with the most important one first so that it cannot be affected by measuring the others. Another approach is to counterbalance, or systematically vary, the order in which the dependent variables are measured.
\subsection{Manipulation Checks}
When the independent variable is a construct that can only be manipulated indirectly---such as emotions and other internal states---an additional measure of that independent variable is often included as a manipulation check. This is done to confirm that the independent variable was, in fact, successfully manipulated. For example, Schnall and her colleagues had their participants rate their level of disgust to be sure that those in the messy room actually felt more disgusted than those in the clean room.
Manipulation checks are usually done at the end of the procedure to be sure that the effect of the manipulation lasted throughout the entire procedure and to avoid calling unnecessary attention to the manipulation. Manipulation checks become especially important when the manipulation of the independent variable turns out to have no effect on the dependent variable. Imagine, for example, that you exposed participants to happy or sad movie music---intending to put them in happy or sad moods---but you found that this had no effect on the number of happy or sad childhood events they recalled. This could be because being in a happy or sad mood has no effect on memories for childhood events. But it could also be that the music was ineffective at putting participants in happy or sad moods. A manipulation check---in this case, a measure of participants' moods---would help resolve this uncertainty. If it showed that you had successfully manipulated participants' moods, then it would appear that there is indeed no effect of mood on memory for childhood events. But if it showed that you did not successfully manipulate participants' moods, then it would appear that you need a more effective manipulation to answer your research question.
\subsection{Measures of the Same Construct}
Another common approach to including multiple dependent variables is to operationally define and measure the same construct, or closely related ones, in different ways. Imagine, for example, that a researcher conducts an experiment on the effect of daily exercise on stress. The dependent variable, stress, is a construct that can be operationally defined in different ways. For this reason, the researcher might have participants complete the paper- and-pencil Perceived Stress Scale and measure their levels of the stress hormone cortisol. This is an example of the use of converging operations. If the researcher finds that the different measures are affected by exercise in the same way, then he or she can be confident in the conclusion that exercise affects the more general construct of stress.
When multiple dependent variables are different measures of the same construct---especially if they are measured on the same scale---researchers have the option of combining them into a single measure of that construct. Recall that Schnall and her colleagues were interested in the harshness of people's moral judgments. To measure this construct, they presented their participants with seven different scenarios describing morally questionable behaviors and asked them to rate the moral acceptability of each one. Although they could have treated each of the seven ratings as a separate dependent variable, these researchers combined them into a single dependent variable by computing their mean.
When researchers combine dependent variables in this way, they are treating them collectively as a multiple- response measure of a single construct. The advantage of this is that multiple-response measures are generally more reliable than single-response measures. However, it is important to make sure the individual dependent variables are correlated with each other by computing an internal consistency measure such as Cronbach's $\alpha$. If they are not correlated with each other, then it does not make sense to combine them into a measure of a single construct. If they have poor internal consistency, then they should be treated as separate dependent variables.
\subsection{\allcaps{Key Takeaways}}
\begin{fullwidth}
\begin{itemize}
\item Researchers in psychology often include multiple dependent variables in their studies. The primary reason is that this easily allows them to answer more research questions with minimal additional effort.
\item When an independent variable is a construct that is manipulated indirectly, it is a good idea to include a manipulation check. This is a measure of the independent variable typically given at the end of the procedure to confirm that it was successfully manipulated.
\item Multiple measures of the same construct can be analyzed separately or combined to produce a single multiple-item measure of that construct. The latter approach requires that the measures taken together have good internal consistency.
\end{itemize}
\end{fullwidth}
\subsection{\allcaps{Exercises}}
\begin{fullwidth}
\begin{enumerate}
\item Practice: List three independent variables for which it would be good to include a manipulation check. List three others for which a manipulation check would be unnecessary. Hint: Consider whether there is any ambiguity concerning whether the manipulation will have its intended effect.
\item Practice: Imagine a study in which the independent variable is whether the room where participants are tested is warm (30°) or cool (12°). List three dependent variables that you might treat as measures of separate variables. List three more that you might combine and treat as measures of the same underlying construct.
\end{enumerate}
\end{fullwidth}
\newpage
\section{Multiple Independent Variables}
\marginnote{\allcaps{Learning Objectives}
\begin{enumerate}
\item Explain why researchers often include multiple independent variables in their studies.
\item Define factorial design, and use a factorial design table to represent and interpret simple factorial designs.
\item Distinguish between main effects and interactions, and recognize and give examples of each.
\item Sketch and interpret bar graphs and line graphs showing the results of studies with simple factorial designs.
\end{enumerate}
}
Just as it is common for studies in psychology to include multiple dependent variables, it is also common for them to include multiple independent variables. Schnall and her colleagues studied the effect of both disgust and private body consciousness in the same study. Researchers' inclusion of multiple independent variables in one experiment is further illustrated by the following actual titles from various professional journals:
\begin{itemize}
\item The Effects of Temporal Delay and Orientation on Haptic Object Recognition
\item Opening Closed Minds: The Combined Effects of Intergroup Contact and Need for Closure on Prejudice
\item Effects of Expectancies and Coping on Pain-Induced Intentions to Smoke
\item The Effect of Age and Divided Attention on Spontaneous Recognition
\item The Effects of Reduced Food Size and Package Size on the Consumption Behavior of Restrained and
Unrestrained Eaters
\end{itemize}
Just as including multiple dependent variables in the same experiment allows one to answer more research questions, so too does including multiple independent variables in the same experiment. For example, instead of conducting one study on the effect of disgust on moral judgment and another on the effect of private body consciousness on moral judgment, Schnall and colleagues were able to conduct one study that addressed both questions. But including multiple independent variables also allows the researcher to answer questions about whether the effect of one independent variable depends on the level of another. This is referred to as an interaction between the independent variables. Schnall and her colleagues, for example, observed an interaction between disgust and private body consciousness because the effect of disgust depended on whether participants were high or low in private body consciousness. As we will see, interactions are often among the most interesting results in psychological research.
\subsection{Factorial Designs }
By far the most common approach to including multiple independent variables in an experiment is the factorial design. In a factorial design, each level of one independent variable (which can also be called a factor) is combined with each level of the others to produce all possible combinations. Each combination, then, becomes a condition in the experiment. Imagine, for example, an experiment on the effect of cell phone use (yes vs. no) and time of day (day vs. night) on driving ability. This is shown in the factorial design table in Figure 8.1. The columns of the table represent cell phone use, and the rows represent time of day. The four cells of the table represent the four possible combinations or conditions: using a cell phone during the day, not using a cell phone during the day, using a cell phone at night, and not using a cell phone at night. This particular design is referred to as a 2 x 2 (read "two-by- two") factorial design because it combines two variables, each of which has two levels. If one of the independent variables had a third level (e.g., using a hand-held cell phone, using a hands-free cell phone, and not using a cell phone), then it would be a 3 x 2 factorial design, and there would be six distinct conditions. Notice that the number of possible conditions is the product of the numbers of levels. A 2 x 2 factorial design has four conditions, a 3 x 2 factorial design has six conditions, a 4 x 5 factorial design would have 20 conditions, and so on.
\begin{figure}
\includegraphics[width=.7\linewidth]{figures/C8factorial.pdf}
\caption{Factorial Design Table Representing a 2 x 2 Factorial Design
}
\label{fig:factorial}
\end{figure}
In principle, factorial designs can include any number of independent variables with any number of levels. For example, an experiment could include the type of psychotherapy (cognitive vs. behavioral), the length of the psychotherapy (2 weeks vs. 2 months), and the sex of the psychotherapist (female vs. male). This would be a 2 x 2 x 2 factorial design and would have eight conditions. Figure 8.2 shows one way to represent this design. In practice, it is unusual for there to be more than three independent variables with more than two or three levels each.
This is for at least two reasons: For one, the number of conditions can quickly become unmanageable. For example, adding a fourth independent variable with three levels (e.g., therapist experience: low vs. medium vs. high) to the current example would make it a 2 x 2 x 2 x 3 factorial design with 24 distinct conditions. Second, the number of participants required to populate all of these conditions (while maintaining a reasonable ability to detect a real underlying effect) can render the design unfeasible (for more information, see the discussion about the importance of adequate statistical power in Chapter 13). As a result, in the remainder of this section we will focus on designs with two independent variables. The general principles discussed here extend in a straightforward way to more complex factorial designs.
\begin{figure}
\includegraphics[width=.7\linewidth]{figures/C83way.pdf}
\caption{Factorial Design Table Representing a 2 x 2 x 2 Factorial Design}
\label{fig:3way}
\end{figure}
\subsection{Assigning Participants to Conditions}
Recall that in a simple between-subjects design, each participant is tested in only one condition. In a simple within- subjects design, each participant is tested in all conditions. In a factorial experiment, the decision to take the between-subjects or within-subjects approach must be made separately for each independent variable. In a between- subjects factorial design, all of the independent variables are manipulated between subjects. For example, all participants could be tested either while using a cell phone or while not using a cell phone and either during the day or during the night. This would mean that each participant was tested in one and only one condition. In a within- subjects factorial design, all of the independent variables are manipulated within subjects. All participants could be tested both while using a cell phone and while not using a cell phone and both during the day and during the night. This would mean that each participant was tested in all conditions. The advantages and disadvantages of these two approaches are the same as those discussed in Chapter 6. The between-subjects design is conceptually simpler, avoids carryover effects, and minimizes the time and effort of each participant. The within-subjects design is more efficient for the researcher and controls extraneous participant variables.
It is also possible to manipulate one independent variable between subjects and another within subjects. This is called a mixed factorial design. For example, a researcher might choose to treat cell phone use as a within- subjects factor by testing the same participants both while using a cell phone and while not using a cell phone (while counterbalancing the order of these two conditions). But he or she might choose to treat time of day as a between-subjects factor by testing each participant either during the day or during the night (perhaps because this only requires them to come in for testing once). Thus each participant in this mixed design would be tested in two of the four conditions.
Regardless of whether the design is between subjects, within subjects, or mixed, the actual assignment of participants to conditions or orders of conditions is typically done randomly.
\subsection{Non-manipulated Independent Variables}
In many factorial designs, one of the independent variables is a non-manipulated independent variable. The researcher measures it but does not manipulate it. The study by Schnall and colleagues is a good example. One independent variable was disgust, which the researchers manipulated by testing participants in a clean room or a messy room. The other was private body consciousness, a participant variable which the researchers simply measured. Another example is a study by Halle Brown and colleagues in which participants were exposed to several words that they were later asked to recall \citep{brown_perceptual_1999}. The manipulated independent variable was the type of word. Some were negative health-related words (e.g., tumor, coronary), and others were not health related (e.g., election, geometry). The non-manipulated independent variable was whether participants were high or low in hypochondriasis (excessive concern with ordinary bodily symptoms). The result of this study was that the participants high in hypochondriasis were better than those low in hypochondriasis at recalling the health-related words, but they were no better at recalling the non-health-related words.
Such studies are extremely common, and there are several points worth making about them. First, non- manipulated independent variables are usually participant variables (private body consciousness, hypochondriasis, self-esteem, and so on), and as such they are by definition between-subjects factors. For example, people are either low in hypochondriasis or high in hypochondriasis; they cannot be tested in both of these conditions. Second, such studies are generally considered to be experiments as long as at least one independent variable is manipulated, regardless of how many non-manipulated independent variables are included. Third, it is important to remember that causal conclusions can only be drawn about the manipulated independent variable. For example, Schnall and her colleagues were justified in concluding that disgust affected the harshness of their participants' moral judgments because they manipulated that variable and randomly assigned participants to the clean or messy room. But they would not have been justified in concluding that participants' private body consciousness affected the harshness of their participants' moral judgments because they did not manipulate that variable. It could be, for example, that having a strict moral code and a heightened awareness of one's body are both caused by some third variable (e.g., neuroticism). Thus it is important to be aware of which variables in a study are manipulated and which are not.
\subsection{Graphing the Results of Factorial Experiments}
The results of factorial experiments with two independent variables can be graphed by representing one independent variable on the x-axis and representing the other by using different kinds of bars or lines. (The y-axis is always reserved for the dependent variable.)
\begin{figure}
\includegraphics[width=.7\linewidth]{figures/C8graphing.pdf}
\caption{Two Ways to Plot the Results of a Factorial Experiment With Two Independent Variables}
\label{fig:graphing}
\end{figure}
Figure 8.3 shows results for two hypothetical factorial experiments. The top panel shows the results of a 2 x 2 design. Time of day (day vs. night) is represented by different locations on the x-axis, and cell phone use (no vs. yes) is represented by different-colored bars. (It would also be possible to represent cell phone use on the x-axis and time of day as different-colored bars. The choice comes down to which way seems to communicate the results most clearly.) The bottom panel of Figure 8.3 shows the results of a 4 x 2 design in which one of the variables is quantitative. This variable, psychotherapy length, is represented along the x-axis, and the other variable (psychotherapy type) is represented by differently formatted lines. This is a line graph rather than a bar graph because the variable on the x-axis is quantitative with a small number of distinct levels. Line graphs are also appropriate when representing measurements made over a time interval (also referred to as time series information) on the x-axis.
\subsection{Main Effects and Interactions}
\begin{marginfigure}[0in]
\includegraphics[width=\linewidth]{figures/C8interactionbars.pdf}
\caption{Bar Graphs Showing Three Types of Interactions. In the top panel, one independent variable has an effect at one level of the second independent variable but not at the other. In the middle panel, one independent variable has a stronger effect at one level of the second independent variable than at the other. In the bottom panel, one independent variable has the opposite effect at one level of the second independent variable than at the other.}
\label{fig:interactionbars}
\end{marginfigure}
In factorial designs, there are two kinds of results that are of interest: main effects and interaction effects (which are also just called "interactions"). A main effect is the statistical relationship between one independent variable and a dependent variable---averaging across the levels of the other independent variable. Thus there is one main effect to consider for each independent variable in the study. The top panel of Figure 8.3 shows a main effect of cell phone use because driving performance was better, on average, when participants were not using cell phones than when they were. The blue bars are, on average, higher than the red bars. It also shows a main effect of time of day because driving performance was better during the day than during the night---both when participants were using cell phones and when they were not. Main effects are independent of each other in the sense that whether or not there is a main effect of one independent variable says nothing about whether or not there is a main effect of the other. The bottom panel of Figure 8.3 , for example, shows a clear main effect of psychotherapy length. The longer the psychotherapy, the better it worked.
There is an interaction effect (or just "interaction") when the effect of one independent variable depends on the level of another. Although this might seem complicated, you already have an intuitive understanding of interactions. It probably would not surprise you, for example, to hear that the effect of receiving psychotherapy is stronger among people who are highly motivated to change than among people who are not motivated to change. This is an interaction because the effect of one independent variable (whether or not one receives psychotherapy) depends on the level of another (motivation to change). Schnall and her colleagues also demonstrated an interaction because the effect of whether the room was clean or messy on participants' moral judgments depended on whether the participants were low or high in private body consciousness. If they were high in private body consciousness, then those in the messy room made harsher judgments. If they were low in private body consciousness, then whether the room was clean or messy did not matter.
The effect of one independent variable can depend on the level of the other in several different ways. This is shown in Figure 8.4 .
\begin{marginfigure}[0in]
\includegraphics[width=\linewidth]{figures/C8interactionlines.pdf}
\caption{Line Graphs Showing Three Types of Interactions. In the top panel, one independent variable has an effect at one level of the second independent variable but not at the other. In the middle panel, one independent variable has a stronger effect at one level of the second independent variable than at the other. In the bottom panel, one independent variable has the opposite effect at one level of the second independent variable than at the other.}
\label{fig:interactionlines}
\end{marginfigure}
In the top panel, independent variable "B" has an effect at level 1 of independent variable "A" but no effect at level 2 of independent variable "A." (This is much like the study of Schnall and her colleagues where there was an effect of disgust for those high in private body consciousness but not for those low in private body consciousness.) In the middle panel, independent variable "B" has a stronger effect at level 1 of independent variable "A" than at level 2. This is like the hypothetical driving example where there was a stronger effect of using a cell phone at night than during the day. In the bottom panel, independent variable "B" again has an effect at both levels of independent variable "A," but the effects are in opposite directions. Figure 8.4 shows the strongest form of this kind of interaction, called a crossover interaction. One example of a crossover interaction comes from a study by Kathy Gilliland on the effect of caffeine on the verbal test scores of introverts and extraverts \citep{gilliland_interactive_1980}. Introverts perform better than extraverts when they have not ingested any caffeine. But extraverts perform better than introverts when they have ingested 4 mg of caffeine per kilogram of body weight. Figure 8.5 shows examples of these same kinds of interactions when one of the independent variables is quantitative and the results are plotted in a line graph.
Note that in a crossover interaction, the two lines literally "cross over" each other. In many studies, the primary research question is about an interaction. The study by Brown and her colleagues was inspired by the idea that people with hypochondriasis are especially attentive to any negative health-related information. This led to the hypothesis that people high in hypochondriasis would recall negative health-related words more accurately than people low in hypochondriasis but recall non-health-related words about the same as people low in hypochondriasis. And of course this is exactly what happened in this study.
\subsection{\allcaps{Key Takeaways}}
\begin{itemize}
\item Researchers often include multiple independent variables in their experiments. The most common approach is the factorial design, in which each level of one independent variable is combined with each level of the others to create all possible conditions.
\item In a factorial design, the main effect of an independent variable is its overall effect averaged across all other independent variables. There is one main effect for each independent variable.
\item There is an interaction between two independent variables when the effect of one depends on the level of the other. Some of the most interesting research questions and results in psychology are specifically about interactions.
\end{itemize}
\subsection{\allcaps{Exercises}}
\begin{fullwidth}
\begin{enumerate}
\item Practice: Return to the five article titles presented at the beginning of this section. For each one, identify the independent variables and the dependent variable.
\item Practice: Create a factorial design table for an experiment on the effects of room temperature and noise level on performance on the MCAT. Be sure to indicate whether each independent variable will be manipulated between-subjects or within-subjects and explain why.
\item Practice: Sketch 8 different bar graphs to depict each of the following possible results in a 2 x 2 factorial experiment:
\begin{itemize}
\item No main effect of A; no main effect of B; no interaction
\item Main effect of A; no main effect of B; no interaction
\item No main effect of A; main effect of B; no interaction
\item Main effect of A; main effect of B; no interaction
\item Main effect of A; main effect of B; interaction
\item Main effect of A; no main effect of B; interaction
\item No main effect of A; main effect of B; interaction
\item No main effect of A; no main effect of B; interaction
\end{itemize}
\end{enumerate}
\end{fullwidth}
\newpage
\input{Factorial.tex}
\section{Complex Correlational Designs}
\marginnote{\allcaps{Learning Objectives}
\begin{enumerate}
\item Explain some reasons that researchers use complex correlational designs.
\item Create and interpret a correlation matrix.
\item Describe how researchers can use correlational research to explore causal relationships among variables---including the limits of this approach.
\end{enumerate}
}
As we have already seen, researchers conduct correlational studies rather than experiments when they are interested in noncausal relationships or when they are interested in causal relationships where the independent variable cannot be manipulated for practical or ethical reasons. In this section, we look at some approaches to complex correlational research that involve measuring several variables and assessing the relationships among them.
\subsection{Correlational Studies With Factorial Designs}
We have already seen that factorial experiments can include manipulated independent variables or a combination of manipulated and non-manipulated independent variables. But factorial designs can also include only non- manipulated independent variables, in which case they are no longer experiments but correlational studies. Consider a hypothetical study in which a researcher measures both the moods and the self-esteem of several participants---categorizing them as having either a positive or negative mood and as being either high or low in self-esteem---along with their willingness to have unprotected sexual intercourse. This can be conceptualized as a 2 x 2 factorial design with mood (positive vs. negative) and self-esteem (high vs. low) as between-subjects factors. Willingness to have unprotected sex is the dependent variable. This design can be represented in a factorial design table and the results in a bar graph of the sort we have already seen. The researcher would consider the main effect of sex, the main effect of self-esteem, and the interaction between these two independent variables.
Again, because neither independent variable in this example was manipulated, it is a correlational study rather than an experiment. (The similar study by MacDonald and Martineau \citeyear{macdonald_self-esteem_2002} was an experiment because they manipulated their participants' moods.) This is important because, as always, one must be cautious about inferring causality from correlational studies because of the directionality and third-variable problems. For example, a main effect of participants' moods on their willingness to have unprotected sex might be caused by any other variable that happens to be correlated with their moods.
\subsection{Assessing Relationships Among Multiple Variables}
Most complex correlational research, however, does not fit neatly into a factorial design. Instead, it involves measuring several variables---often both categorical and quantitative---and then assessing the statistical relationships among them. For example, researchers Nathan Radcliffe and William Klein studied a sample of middle-aged adults to see how their level of optimism (measured by using a short questionnaire called the Life Orientation Test) relates to several other variables related to having a heart attack \citep{radcliffe_dispositional_2002}. These included their health, their knowledge of heart attack risk factors, and their beliefs about their own risk of having a heart attack. They found that more optimistic participants were healthier (e.g., they exercised more and had lower blood pressure), knew about heart attack risk factors, and correctly believed their own risk to be lower than that of their peers.
This approach is often used to assess the validity of new psychological measures. For example, when John Cacioppo and Richard Petty created their Need for Cognition Scale---a measure of the extent to which people like to think and value thinking---they used it to measure the need for cognition for a large sample of college students, along with three other variables: intelligence, socially desirable responding (the tendency to give what one thinks is the "appropriate" response), and dogmatism \citep{cacioppo_need_1982}. The results of this study are summarized in Table 8.1, which is a correlation matrix showing the correlation (Pearson's r) between every possible pair of variables in the study.
\begin{figure}
\includegraphics[width=.7\linewidth]{figures/C8need.pdf}
\caption{Correlation Matrix Showing Correlations Among the Need for Cognition and Three Other Variables Based on Research by Cacioppo and Petty (1982)}
\label{fig:need}
\end{figure}
For example, the correlation between the need for cognition and intelligence was +.39, the correlation between intelligence and socially desirable responding was +.02, and so on. (Only half the matrix is filled in because the other half would contain exactly the same information. Also, because the correlation between a variable and itself is always +1.00, these values are replaced with dashes throughout the matrix.) In this case, the overall pattern of correlations was consistent with the researchers' ideas about how scores on the need for cognition should be related to these other constructs.
When researchers study relationships among a large number of conceptually similar variables, they often use a complex statistical technique called factor analysis. In essence, factor analysis organizes the variables into a smaller number of clusters, such that they are strongly correlated within each cluster but weakly correlated between clusters. Each cluster is then interpreted as multiple measures of the same underlying construct. These underlying constructs are also called "factors." For example, when people perform a wide variety of mental tasks, factor analysis typically organizes them into two main factors---one that researchers interpret as mathematical intelligence (arithmetic, quantitative estimation, spatial reasoning, and so on) and another that they interpret as verbal intelligence (grammar, reading comprehension, vocabulary, and so on). The Big Five personality factors have been identified through factor analyses of people's scores on a large number of more specific traits. For example, measures of warmth, gregariousness, activity level, and positive emotions tend to be highly correlated with each other and are interpreted as representing the construct of extraversion. As a final example, researchers Peter Rentfrow and Samuel Gosling asked more than 1,700 university students to rate how much they liked 14 different popular genres of music \citep{rentfrow_re_2003}. They then submitted these 14 variables to a factor analysis, which identified four distinct factors. The researchers called them Reflective and Complex (blues, jazz, classical, and folk), Intense and Rebellious (rock, alternative, and heavy metal), Upbeat and Conventional (country, soundtrack, religious, pop), and Energetic and Rhythmic (rap/hip-hop, soul/funk, and electronica).
Two additional points about factor analysis are worth making here. One is that factors are not categories. Factor analysis does not tell us that people are either extraverted or conscientious or that they like either "reflective and complex" music or "intense and rebellious" music. Instead, factors are constructs that operate independently of each other. So people who are high in extraversion might be high or low in conscientiousness, and people who like reflective and complex music might or might not also like intense and rebellious music. The second point is that factor analysis reveals only the underlying structure of the variables. It is up to researchers to interpret and label the factors and to explain the origin of that particular factor structure. For example, one reason that extraversion and the other Big Five operate as separate factors is that they appear to be controlled by different genes \citep{plomin_behavioral_2008}.
\subsection{Exploring Causal Relationships}
Another important use of complex correlational research is to explore possible causal relationships among variables. This might seem surprising given that "correlation does not imply causation." It is true that correlational research cannot unambiguously establish that one variable causes another. Complex correlational research, however, can often be used to rule out other plausible interpretations.
The primary way of doing this is through the statistical control of potential third variables. Instead of controlling these variables by random assignment or by holding them constant as in an experiment, the researcher measures them and includes them in the statistical analysis. Consider some research by Paul Piff and his colleagues, who hypothesized that being lower in socioeconomic status (SES) causes people to be more generous \citep{piff_having_2010}. They measured their participants' SES and had them play the "dictator game." They told participants that each would be paired with another participant in a different room. (In reality, there was no other participant.) Then they gave each participant 10 points (which could later be converted to money) to split with the "partner" in whatever way he or she decided. Because the participants were the "dictators," they could even keep all 10 points for themselves if they wanted to.
As these researchers expected, participants who were lower in SES tended to give away more of their points than participants who were higher in SES. This is consistent with the idea that being lower in SES causes people to be more generous. But there are also plausible third variables that could explain this relationship. It could be, for example, that people who are lower in SES tend to be more religious and that it is their greater religiosity that causes them to be more generous. Or it could be that people who are lower in SES tend to come from certain ethnic groups that emphasize generosity more than other ethnic groups. The researchers dealt with these potential third variables, however, by measuring them and including them in their statistical analyses. They found that neither religiosity nor ethnicity was correlated with generosity and were therefore able to rule them out as third variables. This does not prove that SES causes greater generosity because there could still be other third variables that the researchers did not measure. But by ruling out some of the most plausible third variables, the researchers made a stronger case for SES as the cause of the greater generosity.
Many studies of this type use a statistical technique called multiple regression. This involves measuring several independent variables (X1, X2, X3,...Xi), all of which are possible causes of a single dependent variable (Y). The result of a multiple regression analysis is an equation that expresses the dependent variable as an additive combination of the independent variables. This regression equation has the following general form:
$b1X1+ b2X2+ b3X3+ ... + biXi = Y$
The quantities b1, b2, and so on are regression weights that indicate how large a contribution an independent variable makes, on average, to the dependent variable. Specifically, they indicate how much the dependent variable changes for each one-unit change in the independent variable.
The advantage of multiple regression is that it can show whether an independent variable makes a contribution to a dependent variable over and above the contributions made by other independent variables. As a hypothetical example, imagine that a researcher wants to know how the independent variables of income and health relate to the dependent variable of happiness. This is tricky because income and health are themselves related to each other. Thus if people with greater incomes tend to be happier, then perhaps this is only because they tend to be healthier. Likewise, if people who are healthier tend to be happier, perhaps this is only because they tend to make more money. But a multiple regression analysis including both income and happiness as independent variables would show whether each one makes a contribution to happiness when the other is taken into account. Research like this, by the way, has shown both income and health make extremely small contributions to happiness except in the case of severe poverty or illness \cite{diener_subjective_2000}.
The examples discussed in this section only scratch the surface of how researchers use complex correlational research to explore possible causal relationships among variables. It is important to keep in mind, however, that purely correlational approaches cannot unambiguously establish that one variable causes another. The best they can do is show patterns of relationships that are consistent with some causal interpretations and inconsistent with others.
\subsection{\allcaps{Key Takeaways}}
\begin{fullwidth}
\begin{itemize}
\item Researchers often use complex correlational research to explore relationships among several variables in the same study.
\item Complex correlational research can be used to explore possible causal relationships among variables using techniques such as multiple regression. Such designs can show patterns of relationships that are consistent with some causal interpretations and inconsistent with others, but they cannot unambiguously establish that one variable causes another.
\end{itemize}
\end{fullwidth}
\subsection{\allcaps{Exercises}}
\begin{fullwidth}
\begin{enumerate}
\item Practice: Construct a correlation matrix for a hypothetical study including the variables of depression, anxiety, self-esteem, and happiness. Include the Pearson's r values that you would expect.
\item Discussion: Imagine a correlational study that looks at intelligence, the need for cognition, and high school students' performance in a critical-thinking course. A multiple regression analysis shows that intelligence is not related to performance in the class but that the need for cognition is. Explain what this study has shown in terms of what causes good performance in the critical- thinking course.
\end{enumerate}
\end{fullwidth}
|
import Control.ST
import Data.Bits
record DecoderState where
constructor MkDecoderState
byteIndex : Int
buffer : String
indexB64 : String -> Int -> Bits 64
indexB64 s i = intToBits $ fromInteger $ cast $ ord $ strIndex s i
startDecode : String -> STrans m Var res (\lbl => (lbl ::: State DecoderState) :: res)
startDecode buf = new $ MkDecoderState 0 buf
decDropNone : Var -> Resources -> Maybe (Bits 64) -> Resources
decDropNone _dec res Nothing = res
decDropNone dec res (Just _) = (dec ::: State DecoderState) :: res
getByte : (dec : Var) -> STrans m (Maybe (Bits 64))
((dec ::: State DecoderState) :: res)
(decDropNone dec res)
getByte dec = do
state <- read dec
if length (buffer state) <= toNat (byteIndex state)
then do
delete dec
pure Nothing
else do
write dec (record { byteIndex $= (+1) } state)
let byte = buffer state `indexB64` byteIndex state
pure (Just byte)
getVInt' : Nat -> (dec : Var) -> STrans m (Maybe (Bits 64))
((dec ::: State DecoderState) :: res)
(decDropNone dec res)
getVInt' Z _ = pure (Just (intToBits 0))
getVInt' (S k) dec = case !(getByte dec) of
Nothing => pure Nothing
Just byte =>
if byte < intToBits 128
then pure (Just byte)
else do case !(getVInt' k dec) of
Nothing => pure Nothing
Just rest => pure $ Just $
(byte `and` intToBits 127) `or` (rest `shiftLeft` intToBits 7)
getVInt : (dec : Var) -> STrans m (Maybe (Bits 64))
((dec ::: State DecoderState) :: res)
(decDropNone dec res)
getVInt = getVInt' 8
|
%% simple example of use of renorm_sibling_layer
%% compute scattering
clear; close all;
Wop = wavelet_factory_2d_pyramid();
x = uiuc_sample;
Sx = scat(x, Wop);
%% extract the second layer
layer = Sx{3};
op = @(x)(sum(x,3));
%% to renormalized order 2, the sibling is all the node with same ancestor
sibling = @(p)(find(Sx{3}.meta.j(1,:) == Sx{3}.meta.j(1,p) & ...
Sx{3}.meta.theta(1,:) == Sx{3}.meta.theta(1,p)));
%% renormalize
layer_renorm = renorm_sibling_layer(layer, op, sibling);
%% more sophistated example of use of renorm_sibling_layer
%% smooth a bit + L1 norm instead of just L1 norm
options.sigma_phi = 1;
options.P = 4;
filters = morlet_filter_bank_2d_pyramid(options);
h = filters.h.filter;
smooth = @(x)(conv_sub_2d(x, h, 0));
op = @(x)(smooth(sum(x,3)));
%% renormalize
layer_renorm = renorm_sibling_layer(layer, op, sibling);
%% display
figure(1);
image_scat_layer(layer, 0, 0);
title('second order of scattering')
figure(2);
image_scat_layer(layer_renorm, 0, 0);
title('normalized second order of scattering')
|
function fx1 = p07_fx1 ( x )
%*****************************************************************************80
%
%% P07_FX1 evaluates the derivative of the function for problem 7.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 07 May 2011
%
% Author:
%
% John Burkardt
%
% Parameters:
%
% Input, real X, the abscissa.
%
% Output, real FX1, the first derivative of the function at X.
%
fx1 = 3.0 * x.^2;
return
end
|
/*! @copyright (c) 2017 King Abdullah University of Science and
* Technology (KAUST). All rights reserved.
*
* STARS-H is a software package, provided by King Abdullah
* University of Science and Technology (KAUST)
*
* @file testing/mpi_cauchy.c
* @version 1.3.0
* @author Aleksandr Mikhalev
* @date 2017-11-07
* */
#ifdef MKL
#include <mkl.h>
#else
#include <cblas.h>
#include <lapacke.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <starsh.h>
#include <starsh-cauchy.h>
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
int mpi_size, mpi_rank;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
if(argc < 5)
{
if(mpi_rank == 0)
{
printf("%d arguments provided, but 4 are needed\n", argc-1);
printf("mpi_cauchy N block_size maxrank tol\n");
}
MPI_Finalize();
return 1;
}
int N = atoi(argv[1]), block_size = atoi(argv[2]);
int maxrank = atoi(argv[3]);
double tol = atof(argv[4]);
int onfly = 0;
char dtype = 'd', symm = 'N';
int ndim = 2;
STARSH_int shape[2] = {N, N};
int info;
srand(0);
// Init STARS-H
info = starsh_init();
if(info != 0)
{
MPI_Finalize();
return 1;
}
// Generate data for spatial statistics problem
STARSH_cauchy *data;
STARSH_kernel *kernel;
info = starsh_application((void **)&data, &kernel, N, dtype, STARSH_CAUCHY,
STARSH_CAUCHY_KERNEL1, 0);
if(info != 0)
{
MPI_Finalize();
return 1;
}
// Init problem with given data and kernel and print short info
STARSH_problem *P;
info = starsh_problem_new(&P, ndim, shape, symm, dtype, data, data,
kernel, "Cauchy example");
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_problem_info(P);
// Init plain clusterization and print info
STARSH_cluster *C;
info = starsh_cluster_new_plain(&C, data, N, block_size);
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_cluster_info(C);
// Init tlr division into admissible blocks and print short info
STARSH_blrf *F;
STARSH_blrm *M;
info = starsh_blrf_new_tlr_mpi(&F, P, symm, C, C);
if(info != 0)
{
MPI_Finalize();
return 1;
}
if(mpi_rank == 0)
starsh_blrf_info(F);
// Approximate each admissible block
MPI_Barrier(MPI_COMM_WORLD);
double time1 = MPI_Wtime();
info = starsh_blrm_approximate(&M, F, maxrank, tol, onfly);
if(info != 0)
{
MPI_Finalize();
return 1;
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
starsh_blrf_info(F);
starsh_blrm_info(M);
}
if(mpi_rank == 0)
printf("TIME TO APPROXIMATE: %e secs\n", time1);
// Measure approximation error
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
double rel_err = starsh_blrm__dfe_mpi(M);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
printf("TIME TO MEASURE ERROR: %e secs\nRELATIVE ERROR: %e\n",
time1, rel_err);
if(rel_err/tol > 10.)
{
printf("Resulting relative error is too big\n");
MPI_Finalize();
return 1;
}
}
if(rel_err/tol > 10.)
{
MPI_Finalize();
return 1;
}
// Measure time for 10 BLRM matvecs and for 10 BLRM TLR matvecs
double *x, *y, *y_tlr;
int nrhs = 1;
x = malloc(N*nrhs*sizeof(*x));
y = malloc(N*nrhs*sizeof(*y));
y_tlr = malloc(N*nrhs*sizeof(*y_tlr));
if(mpi_rank == 0)
{
int iseed[4] = {0, 0, 0, 1};
LAPACKE_dlarnv_work(3, iseed, N*nrhs, x);
cblas_dscal(N*nrhs, 0.0, y, 1);
cblas_dscal(N*nrhs, 0.0, y_tlr, 1);
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
for(int i = 0; i < 10; i++)
starsh_blrm__dmml_mpi(M, nrhs, 1.0, x, N, 0.0, y, N);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
printf("TIME FOR 10 BLRM MATVECS: %e secs\n", time1);
}
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime();
for(int i = 0; i < 10; i++)
starsh_blrm__dmml_mpi_tlr(M, nrhs, 1.0, x, N, 0.0, y_tlr, N);
MPI_Barrier(MPI_COMM_WORLD);
time1 = MPI_Wtime()-time1;
if(mpi_rank == 0)
{
cblas_daxpy(N, -1.0, y, 1, y_tlr, 1);
printf("TIME FOR 10 TLR MATVECS: %e secs\n", time1);
printf("MATVEC DIFF: %e\n", cblas_dnrm2(N, y_tlr, 1)
/cblas_dnrm2(N, y, 1));
}
MPI_Finalize();
return 0;
}
|
(* ***************************************************************** *)
(* *)
(* Released: 2021/02/24. *)
(* Due: 2021/02/28, 23:59:59, CST. *)
(* *)
(* 0. Read instructions carefully before start writing your answer. *)
(* *)
(* 1. You should not add any hypotheses in this assignment. *)
(* Necessary ones have been provided for you. *)
(* *)
(* 2. In order to check whether you have finished all tasks or not, *)
(* just see whether all "Admitted" has been replaced. *)
(* *)
(* 3. You should submit this file (Assignment1.v) on CANVAS. *)
(* *)
(* 4. Only valid Coq files are accepted. In other words, please *)
(* make sure that your file does not generate a Coq error. A *)
(* way to check that is: click "compile buffer" for this file *)
(* and see whether an "Assignment1.vo" file is generated. *)
(* *)
(* 5. Do not copy and paste others' answer. *)
(* *)
(* 6. Using any theorems and/or tactics provided by Coq's standard *)
(* library is allowed in this assignment, if not specified. *)
(* *)
(* 7. When you finish, answer the following question: *)
(* *)
(* Who did you discuss with when finishing this *)
(* assignment? Your answer to this question will *)
(* NOT affect your grade. *)
(* (* FILL IN YOUR ANSWER HERE AS COMMENT *) *)
(* *)
(* ***************************************************************** *)
Require Import PL.Imp.
(** The command [Admitted] can be used as a placeholder for an
incomplete proof or an in complete definition. We'll use it in
exercises, to indicate the parts that we're leaving for you --
i.e., your job is to replace [Admitted]s with real proofs and/or
definitions. *)
(* ################################################################# *)
(** * Task 1 *)
(** Equalities are symmetric and transive. Prove it in Coq. You should
fill in your proof scripts and replace "Admitted" with "Qed". *)
(** **** Exercise: 1 star, standard *)
Theorem eq_sym: forall (A: Type) (x y: A), x = y -> y = x.
Proof.
intros.
rewrite <- H.
reflexivity.
Qed.
(** [] *)
(** **** Exercise: 1 star, standard *)
Theorem eq_trans: forall (A: Type) (x y z: A), x = y -> y = z -> x = z.
Proof.
intros.
rewrite H.
rewrite H0.
reflexivity.
Qed.
(** [] *)
(** The following example is an special instance of congruence properties.
That is, equalities between integers are preserved by addition. *)
(** **** Exercise: 1 star, standard *)
Theorem Zplus_add: forall x1 x2 y1 y2: Z,
x1 = y1 -> x2 = y2 -> x1 + x2 = y1 + y2.
Proof.
intros.
rewrite H.
rewrite H0.
reflexivity.
Qed.
(** [] *)
(* ################################################################# *)
(** * Task 2 *)
(** Read the following pairs of English descriptions and Hoare triples.
Determine whether they express equivalent meaning. *)
Module Task2_Example.
(**
Hoare triple: {{ True }} c {{ {[X]} <= 3 AND 3 <= {[X]} }}.
Informal description: the program [c] will turn the value of [X] into [3].
Do they express equivalent meaning? 1: Yes. 2: No.
*)
Definition my_choice: Z := 1.
End Task2_Example.
(** **** Exercise: 1 star, standard *)
Module Task2_1.
(**
Hoare triple: {{ {[X]} <= {[Y]} }} c {{ {[Y]} <= {[X]} }}.
Informal description: the program [c] will swap the values of [X] and [Y].
Do they express equivalent meaning? 1: Yes. 2: No.
Remove "[Admitted.]" and write down your choice.
*)
Definition my_choice: Z := 2.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
End Task2_1.
(** [] *)
(** **** Exercise: 1 star, standard *)
Module Task2_2.
(**
Hoare triple: {{ EXISTS k. {[X]} = 2 * k }} c {{ {[Y]} = 0 }}.
Informal description: the program [c] will test whether [X] is an even
number (偶数); if yes, [0] will be assigned into [Y].
Do they express equivalent meaning? 1: Yes. 2: No.
*)
Definition my_choice: Z := 2.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
(* Note that the program [c] doesn't necessarily test [X]. *)
End Task2_2.
(** [] *)
(** **** Exercise: 1 star, standard *)
Module Task2_3.
(**
Hoare triple: {{ True }} c {{ False }}.
Informal description: the program [c] will never terminate.
Do they express equivalent meaning? 1: Yes. 2: No.
*)
Definition my_choice: Z := 1.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
End Task2_3.
(** [] *)
(** **** Exercise: 1 star, standard *)
Module Task2_4.
(**
Hoare triple: {{ True }} c {{ True }}.
Informal description: any program [c].
Do they express equivalent meaning? 1: Yes. 2: No.
*)
Definition my_choice: Z := 1.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
End Task2_4.
(** [] *)
(** **** Exercise: 1 star, standard *)
Module Task2_5.
(**
Hoare triple: for any m, {{ {[X]} + {[Y]} = m }} c {{ {[X]} + {[Y]} = m }}.
Informal description: the program [c] will not change the sum of [X] and [Y].
Do they express equivalent meaning? 1: Yes. 2: No.
*)
Definition my_choice: Z := 1.
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *)
End Task2_5.
(** [] *)
(* ################################################################# *)
(** * Task 3 *)
(** **** Exercise: 3 stars, standard (swapping_by_arith) *)
Module swapping_by_arith.
Import Concrete_Pretty_Printing.
Import Axiomatic_semantics.
(** Prove the following swapping programs correct. Hoare triples about single
assignment commands are provided as hypothese.
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
*)
Local Instance X: var := new_var().
Local Instance Y: var := new_var().
(** Here are three hypothese. *)
Hypothesis triple1: forall x y: Z,
{{ {[X]} = x AND {[Y]} = y }}
X ::= X + Y
{{ {[X]} = x + y AND {[Y]} = y }}.
Hypothesis triple2: forall x y: Z,
{{ {[X]} = x + y AND {[Y]} = y }}
Y ::= X - Y
{{ {[X]} = x + y AND {[Y]} = x }}.
Hypothesis triple3: forall x y: Z,
{{ {[X]} = x + y AND {[Y]} = x }}
X ::= X - Y
{{ {[X]} = y AND {[Y]} = x }}.
(** Now, prove the following Hoare triple by Hoare logic axioms. *)
Fact swapping_by_arith_correct:
forall x y: Z,
{{ {[X]} = x AND {[Y]} = y }}
X ::= X + Y;;
Y ::= X - Y;;
X ::= X - Y
{{ {[X]} = y AND {[Y]} = x }}.
Proof.
intros.
apply hoare_seq with ({[X]} = x + y AND {[Y]} = y)%assert.
apply triple1.
apply hoare_seq with ({[X]} = x + y AND {[Y]} = x)%assert.
apply triple2.
apply triple3.
Qed.
(** [] *)
End swapping_by_arith.
(* ################################################################# *)
(** * Task 4: Using [apply] in more Coq proofs *)
(** A binary relation [R] is called a pre-order if it is reflexive and
transitive. Here is a very simple property about pre-orders. Try to prove
it in Coq. *)
Section PreOrder.
Variable A: Type.
Variable R: A -> A -> Prop.
Hypothesis R_refl: forall a, R a a.
Hypothesis R_trans: forall a b c, R a b -> R b c -> R a c.
(** **** Exercise: 1 star, standard *)
Fact R_trans5: forall a b c d e, R a b -> R b c -> R c d -> R d e -> R a e.
Proof.
intros.
apply R_trans with (b := b).
apply H.
apply R_trans with (b := c).
apply H0.
apply R_trans with (b := d).
apply H1.
apply H2.
Qed.
(** [] *)
End PreOrder.
(* 2021-02-23 23:55 *)
|
(*
Copyright 2014 Cornell University
Copyright 2015 Cornell University
Copyright 2016 Cornell University
Copyright 2017 Cornell University
This file is part of VPrl (the Verified Nuprl project).
VPrl 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.
VPrl 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 VPrl. If not, see <http://www.gnu.org/licenses/>.
Websites: http://nuprl.org/html/verification/
http://nuprl.org/html/Nuprl2Coq
https://github.com/vrahli/NuprlInCoq
Authors: Abhishek Anand & Vincent Rahli
*)
Require Export cequiv_seq_util.
Require Export sequents_tacs2.
(*Require Export per_props4.*)
Require Export per_can.
Require Export per_props_atom.
Require Export per_props_ffatom.
Require Export per_props_squash.
Require Export per_props_nat2.
(* !!MOVE *)
Lemma member_mkc_squash {p} :
forall lib (T : @CTerm p),
member lib mkc_axiom (mkc_squash T)
<=> inhabited_type lib T.
Proof.
intros.
rw @equality_in_mkc_squash.
split; intro h; repnd; dands; auto; spcast;
apply computes_to_valc_refl; eauto 3 with slow.
Qed.
Lemma tequality_natk2nat_nat {o} :
forall lib n,
@tequality o lib (natk2nat (mkc_nat n)) (natk2nat (mkc_nat n)).
Proof.
introv.
apply tequality_natk2nat.
exists (Z.of_nat n) (Z.of_nat n).
dands; spcast; try (apply computes_to_valc_refl; eauto 3 with slow).
introv ltk.
destruct (Z_lt_le_dec k (Z.of_nat n)); sp.
Qed.
Hint Resolve tequality_natk2nat_nat : slow.
Lemma equality_in_nout {o} :
forall lib (a b : @CTerm o),
equality lib a b mkc_nout
<=> {u : CTerm
, noutokensc u
# ccequivc lib a u
# ccequivc lib b u}.
Proof.
introv.
unfold mkc_nout.
rw @equality_in_set.
split; intro h; repnd.
- allrw @mkcv_ffatoms_substc.
allrw @mkc_var_substc.
apply inhabited_free_from_atoms in h; exrepnd.
allrw @equality_in_base_iff; spcast.
exists u; dands; spcast; auto.
eapply cequivc_trans;[|eauto].
apply cequivc_sym; auto.
- exrepnd.
dands.
+ introv equ.
allrw @equality_in_base_iff; spcast.
allrw @mkcv_ffatoms_substc.
allrw @mkc_var_substc.
unfold mkc_ffatoms.
apply tequality_free_from_atoms; dands; eauto 3 with slow.
apply equality_in_base_iff; spcast; auto.
+ spcast.
apply equality_in_base_iff; spcast; auto.
eapply cequivc_trans;[eauto|].
apply cequivc_sym; auto.
+ spcast.
allrw @mkcv_ffatoms_substc.
allrw @mkc_var_substc.
unfold mkc_ffatoms.
apply inhabited_free_from_atoms.
exists u; dands; eauto 3 with slow.
* apply tequality_base.
* apply equality_in_base_iff; spcast; auto.
Qed.
Lemma type_mkc_nout {o} :
forall lib, @type o lib mkc_nout.
Proof.
introv.
unfold mkc_nout.
apply tequality_set; dands; auto.
introv eb.
allrw @mkcv_ffatoms_substc.
allrw @mkc_var_substc.
unfold mkc_ffatoms.
apply tequality_free_from_atoms; dands; eauto 3 with slow.
Qed.
Hint Resolve type_mkc_nout : slow.
Lemma tequality_natk2nout {o} :
forall lib (a b : @CTerm o),
tequality lib (natk2nout a) (natk2nout b)
<=> {k1 : Z
, {k2 : Z
, (a) ===>(lib) (mkc_integer k1)
# (b) ===>(lib) (mkc_integer k2)
# (forall k : Z,
(0 <= k)%Z ->
((k < k1)%Z # (k < k2)%Z){+}(k1 <= k)%Z # (k2 <= k)%Z)}}.
Proof.
introv.
unfold natk2nout.
rw @tequality_mkc_fun.
rw @tequality_mkc_natk.
split; intro k; exrepnd; dands; eauto 3 with slow.
- spcast; exists k1 k0; dands; spcast; auto.
- spcast; exists k1 k2; dands; spcast; auto.
- introv inh; apply type_mkc_nout.
Qed.
Lemma tequality_natk2nout_nat {o} :
forall lib n,
@tequality o lib (natk2nout (mkc_nat n)) (natk2nout (mkc_nat n)).
Proof.
introv.
apply tequality_natk2nout.
exists (Z.of_nat n) (Z.of_nat n).
dands; spcast; try (apply computes_to_valc_refl; eauto 3 with slow).
introv ltk.
destruct (Z_lt_le_dec k (Z.of_nat n)); sp.
Qed.
Hint Resolve tequality_natk2nout_nat : slow.
Lemma type_nat2nout {o} :
forall (lib : @library o), type lib nat2nout.
Proof.
introv.
unfold nat2nout.
apply type_mkc_fun; dands; eauto 3 with slow.
Qed.
Hint Resolve type_nat2nout : slow.
(* ========================== *)
Lemma implies_equality_natk2nat {o} :
forall lib (f g : @CTerm o) n,
(forall m,
m < n
-> {k : nat
& computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)
# computes_to_valc lib (mkc_apply g (mkc_nat m)) (mkc_nat k)})
-> equality lib f g (natk2nat (mkc_nat n)).
Proof.
introv imp.
apply equality_in_fun; dands; eauto 3 with slow.
{ apply type_mkc_natk.
exists (Z.of_nat n); spcast.
apply computes_to_valc_refl; eauto 3 with slow. }
introv e.
apply equality_in_natk in e; exrepnd; spcast.
eapply equality_respects_cequivc_left;
[apply implies_cequivc_apply;
[apply cequivc_refl
|apply cequivc_sym;
apply computes_to_valc_implies_cequivc;
exact e0]
|].
eapply equality_respects_cequivc_right;
[apply implies_cequivc_apply;
[apply cequivc_refl
|apply cequivc_sym;
apply computes_to_valc_implies_cequivc;
exact e2]
|].
clear dependent a.
clear dependent a'.
apply computes_to_valc_isvalue_eq in e3; eauto 3 with slow.
rw @mkc_nat_eq in e3; ginv.
assert (m < n) as ltm by omega.
clear e1.
apply equality_in_tnat.
pose proof (imp m ltm) as h; exrepnd.
exists k; dands; spcast; auto.
Qed.
Lemma implies_member_natk2nat {o} :
forall lib (f : @CTerm o) n,
(forall m,
m < n
-> {k : nat & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)})
-> member lib f (natk2nat (mkc_nat n)).
Proof.
introv imp.
apply implies_equality_natk2nat.
introv ltm.
apply imp in ltm; exrepnd.
exists k; auto.
Qed.
Lemma equality_natk2nat_implies {o} :
forall lib m (f g : @CTerm o) n,
m < n
-> equality lib f g (natk2nat (mkc_nat n))
-> {k : nat
& computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)
# computes_to_valc lib (mkc_apply g (mkc_nat m)) (mkc_nat k)}.
Proof.
introv ltm mem.
apply equality_in_fun in mem; repnd.
clear mem0 mem1.
pose proof (mem (mkc_nat m) (mkc_nat m)) as h; clear mem.
autodimp h hyp.
{ apply equality_in_natk.
exists m (Z.of_nat n); dands; spcast; try omega;
try (apply computes_to_valc_refl; eauto 2 with slow). }
apply equality_in_tnat in h.
apply equality_of_nat_imp_tt in h.
unfold equality_of_nat_tt in h; exrepnd.
exists k; auto.
Qed.
Lemma member_natk2nat_implies {o} :
forall lib m (f : @CTerm o) n,
m < n
-> member lib f (natk2nat (mkc_nat n))
-> {k : nat & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)}.
Proof.
introv ltm mem.
eapply equality_natk2nat_implies in mem;[|exact ltm].
exrepnd.
exists k; auto.
Qed.
(* ========================== *)
Definition eq_kseq {o} lib (s1 s2 : @CTerm o) (n : nat) :=
equality lib s1 s2 (natk2nat (mkc_nat n)).
Lemma eq_kseq_left {o} :
forall lib (seq1 seq2 : @CTerm o) k,
eq_kseq lib seq1 seq2 k
-> eq_kseq lib seq1 seq1 k.
Proof.
introv e.
apply equality_refl in e; auto.
Qed.
Definition fun_sim_eq {o} lib s1 H (t : @NTerm o) w (u : CTerm) :=
{s2 : CSub
& {c2 : cover_vars t s2
& similarity lib s1 s2 H
# u = lsubstc t w s2 c2}}.
|
#include <algorithm>
#include <unordered_map>
#include <Eigen/QR>
#include <descriptor-projection/build-projection-matrix.h>
#include <descriptor-projection/descriptor-projection.h>
#include <descriptor-projection/flags.h>
#include <vi-map/vertex.h>
namespace descriptor_projection {
// Compute the covariance of the descriptors, rows are states, columns are
// samples.
void ComputeCovariance(
const Eigen::MatrixXf& data, Eigen::MatrixXf* covariance) {
CHECK_NOTNULL(covariance);
CHECK_GT(data.cols(), 0) << "Data must not be empty!";
VLOG(4) << "Got " << data.cols()
<< " samples to compute the covariance from.";
covariance->setZero(data.rows(), data.rows());
constexpr int kBlockSize = 10000;
const int num_blocks = data.cols() / kBlockSize + 1;
for (int i = 0; i < num_blocks; ++i) {
const int block_start = i * kBlockSize;
const int block_size =
std::min<int>((i + 1) * kBlockSize, data.cols()) - block_start;
const Eigen::Block<const Eigen::MatrixXf>& data_block =
data.block(0, block_start, data.rows(), block_size);
const Eigen::MatrixXf centered =
data_block.colwise() - data_block.rowwise().mean();
double normalizer = std::max(static_cast<int>(data_block.cols() - 1), 1);
covariance->noalias() += (centered * centered.adjoint()) / normalizer;
}
(*covariance) /= num_blocks;
}
void BuildListOfMatchesAndNonMatches(
const Eigen::MatrixXf& all_descriptors, const std::vector<Track>& tracks,
std::vector<descriptor_projection::DescriptorMatch>* matches,
std::vector<descriptor_projection::DescriptorMatch>* non_matches) {
CHECK_NOTNULL(matches);
CHECK_NOTNULL(non_matches);
for (const Track& track : tracks) {
// Add pairs of matching descriptors to the list of matches.
// TODO(slynen): Consider taking random pairs to not under-estimate the
// variance.
for (size_t i = 1; i < track.size(); ++i) {
matches->emplace_back(track[i - 1], track[i]);
}
}
std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<> distribution(0, all_descriptors.cols() - 1);
for (size_t i = 1; i < static_cast<size_t>(all_descriptors.cols()) &&
i < matches->size() * 2;
++i) {
unsigned int index_a = distribution(generator);
unsigned int index_b = distribution(generator);
if (index_a == index_b) {
continue;
}
non_matches->emplace_back(index_a, index_b);
}
}
void BuildCovarianceMatricesOfMatchesAndNonMatches(
unsigned int descriptor_size, const Eigen::MatrixXf& all_descriptors,
const std::vector<Track>& tracks, unsigned int* sample_size_matches,
unsigned int* sample_size_non_matches, Eigen::MatrixXf* cov_matches,
Eigen::MatrixXf* cov_non_matches) {
CHECK_NOTNULL(sample_size_matches);
CHECK_NOTNULL(sample_size_non_matches);
CHECK_NOTNULL(cov_matches);
CHECK_NOTNULL(cov_non_matches);
{ // Scope to limit memory usage.
unsigned int too_short_tracks = 0;
unsigned int long_enough_tracks = 0;
constexpr size_t kMinTrackLength = 5;
size_t number_of_used_tracks = 0;
Eigen::MatrixXf sumMuMu;
sumMuMu.setZero(descriptor_size, descriptor_size);
std::vector<size_t> descriptors_from_tracks;
descriptors_from_tracks.reserve(500);
// Centering.
constexpr int kMaxNumSamples = 50000;
for (const Track& track : tracks) {
if (track.size() < kMinTrackLength) {
++too_short_tracks;
continue;
}
if (number_of_used_tracks >= kMaxNumSamples) {
LOG(WARNING) << "Truncated descriptors to " << kMaxNumSamples << ".";
break;
}
++long_enough_tracks;
Eigen::Matrix<float, Eigen::Dynamic, 1> mean;
mean.resize(descriptor_size, Eigen::NoChange);
mean.setZero();
for (const size_t& descriptor_idx : track) {
descriptors_from_tracks.push_back(descriptor_idx);
mean += all_descriptors.block(0, descriptor_idx, descriptor_size, 1);
}
mean /= track.size();
CHECK_LE(mean.maxCoeff(), 1.0);
CHECK_GE(mean.minCoeff(), 0.0);
Eigen::MatrixXf mu_sq_current = (mean * mean.transpose()).eval();
sumMuMu += mu_sq_current * track.size();
++number_of_used_tracks;
}
VLOG(3) << "Got " << long_enough_tracks << " tracks out of "
<< tracks.size() << " (dropped " << too_short_tracks
<< " tracks because they were too short)";
CHECK(!descriptors_from_tracks.empty());
VLOG(3) << "Computing matches covariance from "
<< descriptors_from_tracks.size()
<< " matches (descriptor size: " << descriptor_size << ")";
*sample_size_matches = descriptors_from_tracks.size();
Eigen::MatrixXf matches;
matches.resize(descriptor_size, descriptors_from_tracks.size());
matches.setZero();
int matched_idx = 0;
for (const size_t& descriptor_idx : descriptors_from_tracks) {
matches.block(0, matched_idx, descriptor_size, 1) =
all_descriptors.block(0, descriptor_idx, descriptor_size, 1);
++matched_idx;
}
CHECK_GT(descriptors_from_tracks.size(), number_of_used_tracks);
// Covariance computation for matches.
cov_matches->noalias() =
(matches * matches.transpose() - sumMuMu) * 2.0 /
static_cast<float>(
descriptors_from_tracks.size() - number_of_used_tracks);
} // Scope to limit memory usage.
// Use all descriptors to estimate the non-matching covariance.
*sample_size_non_matches = all_descriptors.cols();
// Compute sample covariances non matched descriptors.
ComputeCovariance(all_descriptors, cov_non_matches);
*cov_non_matches *= 2.0f;
}
void ComputeProjectionMatrix(
const Eigen::MatrixXf& cov_matches, const Eigen::MatrixXf& cov_non_matches,
Eigen::MatrixXf* A) {
CHECK_NOTNULL(A);
const int dimensionality = cov_matches.cols();
A->resize(dimensionality, dimensionality);
Eigen::JacobiSVD<Eigen::MatrixXf> svd(cov_matches, Eigen::ComputeFullV);
CHECK_NE(svd.singularValues().minCoeff(), 0)
<< "Rank deficiency for matrix"
" of samples detected. Probably too little matches.";
Eigen::MatrixXf Av =
svd.singularValues().cwiseSqrt().cwiseInverse().asDiagonal() *
svd.matrixV().transpose();
Eigen::JacobiSVD<Eigen::MatrixXf> svd_d(
Av * cov_non_matches * Av.transpose(), Eigen::ComputeFullV);
Eigen::MatrixXf singular_values_sqrt_inv =
svd_d.singularValues().cwiseSqrt().cwiseInverse().asDiagonal();
Eigen::MatrixXf eye;
eye.resize(dimensionality, dimensionality);
eye.setIdentity();
*A = (eye - singular_values_sqrt_inv) * svd_d.matrixV().transpose() *
svd.singularValues().cwiseInverse().asDiagonal() *
svd.matrixV().transpose();
}
} // namespace descriptor_projection
|
section \<open>Multisets by Lists\<close>
theory IICF_List_Mset
imports "../Intf/IICF_Multiset"
begin
subsection \<open>Abstract Operations\<close>
definition "list_mset_rel \<equiv> br mset (\<lambda>_. True)"
lemma lms_empty_aref: "([],op_mset_empty) \<in> list_mset_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv)
(*definition [simp]: "list_single x \<equiv> [x]"
lemma lms_single_aref: "(list_single,op_mset_single) \<in> Id \<rightarrow> list_mset_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv split: list.splits)*)
lemma lms_is_empty_aref: "(is_Nil,op_mset_is_empty) \<in> list_mset_rel \<rightarrow> bool_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv split: list.splits)
lemma lms_insert_aref: "((#), op_mset_insert) \<in> Id \<rightarrow> list_mset_rel \<rightarrow> list_mset_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv)
lemma lms_union_aref: "((@), op_mset_plus) \<in> list_mset_rel \<rightarrow> list_mset_rel \<rightarrow> list_mset_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv)
lemma lms_pick_aref: "(\<lambda>x#l \<Rightarrow> RETURN (x,l), mop_mset_pick) \<in> list_mset_rel \<rightarrow> \<langle>Id \<times>\<^sub>r list_mset_rel\<rangle>nres_rel"
unfolding list_mset_rel_def mop_mset_pick_alt[abs_def]
apply1 (refine_vcg nres_relI fun_relI)
apply1 (clarsimp simp: in_br_conv neq_Nil_conv)
apply1 (refine_vcg RETURN_SPEC_refine)
applyS (clarsimp simp: in_br_conv algebra_simps)
done
definition "list_contains x l \<equiv> list_ex ((=) x) l"
lemma lms_contains_aref: "(list_contains, op_mset_contains) \<in> Id \<rightarrow> list_mset_rel \<rightarrow> bool_rel"
unfolding list_mset_rel_def list_contains_def[abs_def]
by (auto simp: in_br_conv list_ex_iff in_multiset_in_set)
fun list_remove1 :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"list_remove1 x [] = []"
| "list_remove1 x (y#ys) = (if x=y then ys else y#list_remove1 x ys)"
lemma lms_count_aref: "(list_count, op_mset_count) \<in> Id \<rightarrow> list_mset_rel \<rightarrow> nat_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv)
definition list_remove_all :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"list_remove_all xs ys \<equiv> fold list_remove1 ys xs"
lemma list_remove_all_mset[simp]: "mset (list_remove_all xs ys) = mset xs - mset ys"
unfolding list_remove_all_def
by (induction ys arbitrary: xs) (auto simp: algebra_simps)
lemma lms_minus_aref: "(list_remove_all,op_mset_minus) \<in> list_mset_rel \<rightarrow> list_mset_rel \<rightarrow> list_mset_rel"
unfolding list_mset_rel_def by (auto simp: in_br_conv)
subsection \<open>Declaration of Implementations\<close>
definition "list_mset_assn A \<equiv> pure (list_mset_rel O \<langle>the_pure A\<rangle>mset_rel)"
declare list_mset_assn_def[symmetric,fcomp_norm_unfold]
lemma [safe_constraint_rules]: "is_pure (list_mset_assn A)" unfolding list_mset_assn_def by simp
sepref_decl_impl (no_register) lms_empty: lms_empty_aref[sepref_param] .
(*sepref_decl_impl (no_register) lms_single: lms_single_aref[sepref_param] .*)
definition [simp]: "op_list_mset_empty \<equiv> op_mset_empty"
lemma lms_fold_custom_empty:
"{#} = op_list_mset_empty"
"op_mset_empty = op_list_mset_empty"
by auto
sepref_register op_list_mset_empty
lemmas [sepref_fr_rules] = lms_empty_hnr[folded op_list_mset_empty_def]
(*
definition [simp]: "op_list_mset_single \<equiv> op_mset_single"
lemma lms_fold_custom_single:
"{#x#} = op_list_mset_single x"
"op_mset_single x = op_list_mset_single x"
by auto
sepref_register op_list_mset_single
lemmas [sepref_fr_rules] = lms_single_hnr[folded op_list_mset_single_def]
*)
sepref_decl_impl lms_is_empty: lms_is_empty_aref[sepref_param] .
sepref_decl_impl lms_insert: lms_insert_aref[sepref_param] .
sepref_decl_impl lms_union: lms_union_aref[sepref_param] .
\<comment> \<open>Some extra work is required for nondetermistic ops\<close>
lemma lms_pick_aref':
"(\<lambda>x#l \<Rightarrow> return (x,l), mop_mset_pick) \<in> (pure list_mset_rel)\<^sup>k \<rightarrow>\<^sub>a prod_assn id_assn (pure list_mset_rel)"
apply (simp only: prod_assn_pure_conv)
apply sepref_to_hoare
apply (sep_auto simp: refine_pw_simps list_mset_rel_def in_br_conv algebra_simps eintros del: exI)
done
sepref_decl_impl (ismop) lms_pick: lms_pick_aref' .
sepref_decl_impl lms_contains: lms_contains_aref[sepref_param] .
sepref_decl_impl lms_remove: lms_remove_aref[sepref_param] .
sepref_decl_impl lms_count: lms_count_aref[sepref_param] .
sepref_decl_impl lms_minus: lms_minus_aref[sepref_param] .
end
|
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.NConnected
open import lib.types.Empty
open import lib.types.Nat
open import lib.types.Paths
open import lib.types.Pi
open import lib.types.Pointed
open import lib.types.Sigma
open import lib.types.TLevel
open import lib.types.Truncation
module lib.types.LoopSpace where
{- loop space -}
module _ {i} where
⊙Ω : Ptd i → Ptd i
⊙Ω ⊙[ A , a ] = ⊙[ (a == a) , idp ]
Ω : Ptd i → Type i
Ω = de⊙ ∘ ⊙Ω
module _ {i} {X : Ptd i} where
Ω-! : Ω X → Ω X
Ω-! = !
Ω-∙ : Ω X → Ω X → Ω X
Ω-∙ = _∙_
{- pointed versions of functions on paths -}
⊙Ω-∙ : ∀ {i} {X : Ptd i} → ⊙Ω X ⊙× ⊙Ω X ⊙→ ⊙Ω X
⊙Ω-∙ = (uncurry Ω-∙ , idp)
⊙Ω-fmap : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → ⊙Ω X ⊙→ ⊙Ω Y
⊙Ω-fmap (f , idp) = ap f , idp
Ω-fmap : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → (Ω X → Ω Y)
Ω-fmap F = fst (⊙Ω-fmap F)
Ω-fmap-β : ∀ {i j} {X : Ptd i} {Y : Ptd j} (F : X ⊙→ Y) (p : Ω X)
→ Ω-fmap F p == ! (snd F) ∙ ap (fst F) p ∙' snd F
Ω-fmap-β (_ , idp) _ = idp
Ω-isemap : ∀ {i j} {X : Ptd i} {Y : Ptd j}
(F : X ⊙→ Y) → is-equiv (fst F) → is-equiv (Ω-fmap F)
Ω-isemap (f , idp) e = ap-is-equiv e _ _
Ω-emap : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ (X ⊙≃ Y) → (Ω X ≃ Ω Y)
Ω-emap (F , F-is-equiv) = Ω-fmap F , Ω-isemap F F-is-equiv
⊙Ω-emap : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ (X ⊙≃ Y) → (⊙Ω X ⊙≃ ⊙Ω Y)
⊙Ω-emap (F , F-is-equiv) = ⊙Ω-fmap F , Ω-isemap F F-is-equiv
⊙Ω-fmap2 : ∀ {i j k} {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
→ X ⊙× Y ⊙→ Z → ⊙Ω X ⊙× ⊙Ω Y ⊙→ ⊙Ω Z
⊙Ω-fmap2 (f , idp) = (λ{(p , q) → ap2 (curry f) p q}) , idp
⊙Ω-fmap-∘ : ∀ {i j k} {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
(g : Y ⊙→ Z) (f : X ⊙→ Y)
→ ⊙Ω-fmap (g ⊙∘ f) == ⊙Ω-fmap g ⊙∘ ⊙Ω-fmap f
⊙Ω-fmap-∘ (g , idp) (f , idp) = ⊙λ=' (λ p → ap-∘ g f p) idp
⊙Ω-csmap : ∀ {i₀ i₁ j₀ j₁} {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquare f g hX hY
→ ⊙CommSquare (⊙Ω-fmap f) (⊙Ω-fmap g) (⊙Ω-fmap hX) (⊙Ω-fmap hY)
⊙Ω-csmap {f = f} {g} {hX} {hY} (⊙comm-sqr cs) = ⊙comm-sqr $ ⊙app= $
⊙Ω-fmap hY ⊙∘ ⊙Ω-fmap f
=⟨ ! $ ⊙Ω-fmap-∘ hY f ⟩
⊙Ω-fmap (hY ⊙∘ f)
=⟨ ap ⊙Ω-fmap $ ⊙λ= cs ⟩
⊙Ω-fmap (g ⊙∘ hX)
=⟨ ⊙Ω-fmap-∘ g hX ⟩
⊙Ω-fmap g ⊙∘ ⊙Ω-fmap hX
=∎
⊙Ω-csemap : ∀ {i₀ i₁ j₀ j₁} {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquareEquiv f g hX hY
→ ⊙CommSquareEquiv (⊙Ω-fmap f) (⊙Ω-fmap g) (⊙Ω-fmap hX) (⊙Ω-fmap hY)
⊙Ω-csemap {f = f} {g} {hX} {hY} (⊙comm-sqr cs , hX-ise , hY-ise) =
(⊙comm-sqr $ ⊙app= $
⊙Ω-fmap hY ⊙∘ ⊙Ω-fmap f
=⟨ ! $ ⊙Ω-fmap-∘ hY f ⟩
⊙Ω-fmap (hY ⊙∘ f)
=⟨ ap ⊙Ω-fmap $ ⊙λ= cs ⟩
⊙Ω-fmap (g ⊙∘ hX)
=⟨ ⊙Ω-fmap-∘ g hX ⟩
⊙Ω-fmap g ⊙∘ ⊙Ω-fmap hX
=∎) ,
Ω-isemap hX hX-ise , Ω-isemap hY hY-ise
⊙Ω-fmap-idf : ∀ {i} {X : Ptd i} → ⊙Ω-fmap (⊙idf X) == ⊙idf _
⊙Ω-fmap-idf = ⊙λ=' ap-idf idp
⊙Ω-fmap2-fst : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ ⊙Ω-fmap2 {X = X} {Y = Y} ⊙fst == ⊙fst
⊙Ω-fmap2-fst = ⊙λ=' (uncurry ap2-fst) idp
⊙Ω-fmap2-snd : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ ⊙Ω-fmap2 {X = X} {Y = Y} ⊙snd == ⊙snd
⊙Ω-fmap2-snd = ⊙λ=' (uncurry ap2-snd) idp
⊙Ω-fmap-fmap2 : ∀ {i j k l} {X : Ptd i} {Y : Ptd j} {Z : Ptd k} {W : Ptd l}
(G : Z ⊙→ W) (F : X ⊙× Y ⊙→ Z)
→ ⊙Ω-fmap G ⊙∘ ⊙Ω-fmap2 F == ⊙Ω-fmap2 (G ⊙∘ F)
⊙Ω-fmap-fmap2 (g , idp) (f , idp) =
⊙λ=' (uncurry (ap-ap2 g (curry f))) idp
⊙Ω-fmap2-fmap : ∀ {i j k l m}
{X : Ptd i} {Y : Ptd j} {U : Ptd k} {V : Ptd l} {Z : Ptd m}
(G : (U ⊙× V) ⊙→ Z) (F₁ : X ⊙→ U) (F₂ : Y ⊙→ V)
→ ⊙Ω-fmap2 G ⊙∘ ⊙×-fmap (⊙Ω-fmap F₁) (⊙Ω-fmap F₂) == ⊙Ω-fmap2 (G ⊙∘ ⊙×-fmap F₁ F₂)
⊙Ω-fmap2-fmap (g , idp) (f₁ , idp) (f₂ , idp) =
⊙λ=' (λ {(p , q) → ap2-ap-l (curry g) f₁ p (ap f₂ q)
∙ ap2-ap-r (λ x v → g (f₁ x , v)) f₂ p q})
idp
⊙Ω-fmap2-diag : ∀ {i j} {X : Ptd i} {Y : Ptd j} (F : X ⊙× X ⊙→ Y)
→ ⊙Ω-fmap2 F ⊙∘ ⊙diag == ⊙Ω-fmap (F ⊙∘ ⊙diag)
⊙Ω-fmap2-diag (f , idp) = ⊙λ=' (ap2-diag (curry f)) idp
{- iterated loop spaces. [Ω^] and [Ω^'] iterates [Ω] from different sides:
[Ω^ (S n) X = Ω (Ω^ n X)] and [Ω^' (S n) X = Ω^' n (Ω X)]. -}
module _ {i} where
⊙Ω^ : (n : ℕ) → Ptd i → Ptd i
⊙Ω^ O X = X
⊙Ω^ (S n) X = ⊙Ω (⊙Ω^ n X)
Ω^ : (n : ℕ) → Ptd i → Type i
Ω^ n X = de⊙ (⊙Ω^ n X)
⊙Ω^' : (n : ℕ) → Ptd i → Ptd i
⊙Ω^' O X = X
⊙Ω^' (S n) X = (⊙Ω^' n (⊙Ω X))
Ω^' : (n : ℕ) → Ptd i → Type i
Ω^' n X = de⊙ (⊙Ω^' n X)
{- [⊙Ω^-fmap] and [⊙Ω^-fmap2] for higher loop spaces -}
⊙Ω^-fmap : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → ⊙Ω^ n X ⊙→ ⊙Ω^ n Y
⊙Ω^-fmap O F = F
⊙Ω^-fmap (S n) F = ⊙Ω-fmap (⊙Ω^-fmap n F)
Ω^-fmap : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → (de⊙ (⊙Ω^ n X) → de⊙ (⊙Ω^ n Y))
Ω^-fmap n F = fst (⊙Ω^-fmap n F)
⊙Ω^-csmap : ∀ {i₀ i₁ j₀ j₁} (n : ℕ) {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquare f g hX hY
→ ⊙CommSquare (⊙Ω^-fmap n f) (⊙Ω^-fmap n g) (⊙Ω^-fmap n hX) (⊙Ω^-fmap n hY)
⊙Ω^-csmap O cs = cs
⊙Ω^-csmap (S n) cs = ⊙Ω-csmap (⊙Ω^-csmap n cs)
⊙Ω^'-fmap : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → ⊙Ω^' n X ⊙→ ⊙Ω^' n Y
⊙Ω^'-fmap O F = F
⊙Ω^'-fmap (S n) F = ⊙Ω^'-fmap n (⊙Ω-fmap F)
⊙Ω^'-csmap : ∀ {i₀ i₁ j₀ j₁} (n : ℕ) {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquare f g hX hY
→ ⊙CommSquare (⊙Ω^'-fmap n f) (⊙Ω^'-fmap n g) (⊙Ω^'-fmap n hX) (⊙Ω^'-fmap n hY)
⊙Ω^'-csmap O cs = cs
⊙Ω^'-csmap (S n) cs = ⊙Ω^'-csmap n (⊙Ω-csmap cs)
Ω^'-fmap : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ X ⊙→ Y → (de⊙ (⊙Ω^' n X) → de⊙ (⊙Ω^' n Y))
Ω^'-fmap n F = fst (⊙Ω^'-fmap n F)
⊙Ω^-fmap2 : ∀ {i j k} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
→ ((X ⊙× Y) ⊙→ Z)
→ ((⊙Ω^ n X ⊙× ⊙Ω^ n Y) ⊙→ ⊙Ω^ n Z)
⊙Ω^-fmap2 O F = F
⊙Ω^-fmap2 (S n) F = ⊙Ω-fmap2 (⊙Ω^-fmap2 n F)
Ω^-fmap2 : ∀ {i j k} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
→ ((X ⊙× Y) ⊙→ Z)
→ ((Ω^ n X) × (Ω^ n Y) → Ω^ n Z)
Ω^-fmap2 n F = fst (⊙Ω^-fmap2 n F)
⊙Ω^'-fmap2 : ∀ {i j k} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
→ ((X ⊙× Y) ⊙→ Z)
→ ((⊙Ω^' n X ⊙× ⊙Ω^' n Y) ⊙→ ⊙Ω^' n Z)
⊙Ω^'-fmap2 O F = F
⊙Ω^'-fmap2 (S n) F = ⊙Ω^'-fmap2 n (⊙Ω-fmap2 F)
Ω^'-fmap2 : ∀ {i j k} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
→ ((X ⊙× Y) ⊙→ Z)
→ ((Ω^' n X) × (Ω^' n Y) → Ω^' n Z)
Ω^'-fmap2 n F = fst (⊙Ω^'-fmap2 n F)
⊙Ω^-fmap-∘ : ∀ {i j k} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
(g : Y ⊙→ Z) (f : X ⊙→ Y)
→ ⊙Ω^-fmap n (g ⊙∘ f) == ⊙Ω^-fmap n g ⊙∘ ⊙Ω^-fmap n f
⊙Ω^-fmap-∘ O _ _ = idp
⊙Ω^-fmap-∘ (S n) g f = ap ⊙Ω-fmap (⊙Ω^-fmap-∘ n g f)
∙ ⊙Ω-fmap-∘ (⊙Ω^-fmap n g) (⊙Ω^-fmap n f)
⊙Ω^-fmap-idf : ∀ {i} (n : ℕ) {X : Ptd i} → ⊙Ω^-fmap n (⊙idf X) == ⊙idf _
⊙Ω^-fmap-idf O = idp
⊙Ω^-fmap-idf (S n) = ap ⊙Ω-fmap (⊙Ω^-fmap-idf n) ∙ ⊙Ω-fmap-idf
Ω^-fmap-idf : ∀ {i} (n : ℕ) {X : Ptd i} → Ω^-fmap n (⊙idf X) == idf _
Ω^-fmap-idf n = fst= $ ⊙Ω^-fmap-idf n
⊙Ω^'-fmap-idf : ∀ {i} (n : ℕ) {X : Ptd i} → ⊙Ω^'-fmap n (⊙idf X) == ⊙idf _
⊙Ω^'-fmap-idf O = idp
⊙Ω^'-fmap-idf (S n) = ap (⊙Ω^'-fmap n) ⊙Ω-fmap-idf ∙ ⊙Ω^'-fmap-idf n
Ω^'-fmap-idf : ∀ {i} (n : ℕ) {X : Ptd i} → Ω^'-fmap n (⊙idf X) == idf _
Ω^'-fmap-idf n = fst= $ ⊙Ω^'-fmap-idf n
⊙Ω^-fmap-fmap2 : ∀ {i j k l} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k} {W : Ptd l}
(G : Z ⊙→ W) (F : (X ⊙× Y) ⊙→ Z)
→ ⊙Ω^-fmap n G ⊙∘ ⊙Ω^-fmap2 n F == ⊙Ω^-fmap2 n (G ⊙∘ F)
⊙Ω^-fmap-fmap2 O G F = idp
⊙Ω^-fmap-fmap2 (S n) G F = ⊙Ω-fmap-fmap2 (⊙Ω^-fmap n G) (⊙Ω^-fmap2 n F) ∙ ap ⊙Ω-fmap2 (⊙Ω^-fmap-fmap2 n G F)
Ω^-fmap-fmap2 : ∀ {i j k l} (n : ℕ) {X : Ptd i} {Y : Ptd j} {Z : Ptd k} {W : Ptd l}
(G : Z ⊙→ W) (F : (X ⊙× Y) ⊙→ Z)
→ Ω^-fmap n G ∘ Ω^-fmap2 n F == Ω^-fmap2 n (G ⊙∘ F)
Ω^-fmap-fmap2 n G F = fst= $ ⊙Ω^-fmap-fmap2 n G F
⊙Ω^-fmap2-fst : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ ⊙Ω^-fmap2 n {X} {Y} ⊙fst == ⊙fst
⊙Ω^-fmap2-fst O = idp
⊙Ω^-fmap2-fst (S n) = ap ⊙Ω-fmap2 (⊙Ω^-fmap2-fst n) ∙ ⊙Ω-fmap2-fst
Ω^-fmap2-fst : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ Ω^-fmap2 n {X} {Y} ⊙fst == fst
Ω^-fmap2-fst n = fst= $ ⊙Ω^-fmap2-fst n
⊙Ω^-fmap2-snd : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ ⊙Ω^-fmap2 n {X} {Y} ⊙snd == ⊙snd
⊙Ω^-fmap2-snd O = idp
⊙Ω^-fmap2-snd (S n) = ap ⊙Ω-fmap2 (⊙Ω^-fmap2-snd n) ∙ ⊙Ω-fmap2-snd
Ω^-fmap2-snd : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j}
→ Ω^-fmap2 n {X} {Y} ⊙snd == snd
Ω^-fmap2-snd n = fst= $ ⊙Ω^-fmap2-snd n
⊙Ω^-fmap2-fmap : ∀ {i j k l m} (n : ℕ)
{X : Ptd i} {Y : Ptd j} {U : Ptd k} {V : Ptd l} {Z : Ptd m}
(G : (U ⊙× V) ⊙→ Z) (F₁ : X ⊙→ U) (F₂ : Y ⊙→ V)
→ ⊙Ω^-fmap2 n G ⊙∘ ⊙×-fmap (⊙Ω^-fmap n F₁) (⊙Ω^-fmap n F₂) == ⊙Ω^-fmap2 n (G ⊙∘ ⊙×-fmap F₁ F₂)
⊙Ω^-fmap2-fmap O G F₁ F₂ = idp
⊙Ω^-fmap2-fmap (S n) G F₁ F₂ =
⊙Ω-fmap2-fmap (⊙Ω^-fmap2 n G) (⊙Ω^-fmap n F₁) (⊙Ω^-fmap n F₂) ∙ ap ⊙Ω-fmap2 (⊙Ω^-fmap2-fmap n G F₁ F₂)
Ω^-fmap2-fmap : ∀ {i j k l m} (n : ℕ)
{X : Ptd i} {Y : Ptd j} {U : Ptd k} {V : Ptd l} {Z : Ptd m}
(G : (U ⊙× V) ⊙→ Z) (F₁ : X ⊙→ U) (F₂ : Y ⊙→ V)
→ Ω^-fmap2 n G ∘ ×-fmap (Ω^-fmap n F₁) (Ω^-fmap n F₂) == Ω^-fmap2 n (G ⊙∘ ⊙×-fmap F₁ F₂)
Ω^-fmap2-fmap n G F₁ F₂ = fst= $ ⊙Ω^-fmap2-fmap n G F₁ F₂
⊙Ω^-fmap2-diag : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j} (F : X ⊙× X ⊙→ Y)
→ ⊙Ω^-fmap2 n F ⊙∘ ⊙diag == ⊙Ω^-fmap n (F ⊙∘ ⊙diag)
⊙Ω^-fmap2-diag O F = idp
⊙Ω^-fmap2-diag (S n) F = ⊙Ω-fmap2-diag (⊙Ω^-fmap2 n F) ∙ ap ⊙Ω-fmap (⊙Ω^-fmap2-diag n F)
Ω^-fmap2-diag : ∀ {i j} (n : ℕ) {X : Ptd i} {Y : Ptd j} (F : X ⊙× X ⊙→ Y)
→ Ω^-fmap2 n F ∘ diag == Ω^-fmap n (F ⊙∘ ⊙diag)
Ω^-fmap2-diag n F = fst= $ ⊙Ω^-fmap2-diag n F
{- for n ≥ 1, we have a group structure on the loop space -}
module _ {i} (n : ℕ) {X : Ptd i} where
Ω^S-! : Ω^ (S n) X → Ω^ (S n) X
Ω^S-! = Ω-!
Ω^S-∙ : Ω^ (S n) X → Ω^ (S n) X → Ω^ (S n) X
Ω^S-∙ = Ω-∙
module _ {i} where
Ω^'S-! : (n : ℕ) {X : Ptd i} → Ω^' (S n) X → Ω^' (S n) X
Ω^'S-! O = Ω-!
Ω^'S-! (S n) {X} = Ω^'S-! n {⊙Ω X}
Ω^'S-∙ : (n : ℕ) {X : Ptd i} → Ω^' (S n) X → Ω^' (S n) X → Ω^' (S n) X
Ω^'S-∙ O = Ω-∙
Ω^'S-∙ (S n) {X} = Ω^'S-∙ n {⊙Ω X}
idp^ : ∀ {i} (n : ℕ) {X : Ptd i} → Ω^ n X
idp^ n {X} = pt (⊙Ω^ n X)
idp^' : ∀ {i} (n : ℕ) {X : Ptd i} → Ω^' n X
idp^' n {X} = pt (⊙Ω^' n X)
module _ {i} (n : ℕ) {X : Ptd i} where
{- Prove these as lemmas now
- so we don't have to deal with the n = O case later -}
Ω^S-∙-unit-l : (q : Ω^ (S n) X)
→ (Ω^S-∙ n (idp^ (S n)) q) == q
Ω^S-∙-unit-l _ = idp
Ω^S-∙-unit-r : (q : Ω^ (S n) X)
→ (Ω^S-∙ n q (idp^ (S n))) == q
Ω^S-∙-unit-r = ∙-unit-r
Ω^S-∙-assoc : (p q r : Ω^ (S n) X)
→ Ω^S-∙ n (Ω^S-∙ n p q) r == Ω^S-∙ n p (Ω^S-∙ n q r)
Ω^S-∙-assoc = ∙-assoc
Ω^S-!-inv-l : (p : Ω^ (S n) X)
→ Ω^S-∙ n (Ω^S-! n p) p == idp^ (S n)
Ω^S-!-inv-l = !-inv-l
Ω^S-!-inv-r : (p : Ω^ (S n) X)
→ Ω^S-∙ n p (Ω^S-! n p) == idp^ (S n)
Ω^S-!-inv-r = !-inv-r
module _ {i} where
Ω^'S-∙-unit-l : (n : ℕ) {X : Ptd i} (q : Ω^' (S n) X)
→ (Ω^'S-∙ n (idp^' (S n)) q) == q
Ω^'S-∙-unit-l O _ = idp
Ω^'S-∙-unit-l (S n) = Ω^'S-∙-unit-l n
Ω^'S-∙-unit-r : (n : ℕ) {X : Ptd i} (q : Ω^' (S n) X)
→ (Ω^'S-∙ n q (idp^' (S n))) == q
Ω^'S-∙-unit-r O = ∙-unit-r
Ω^'S-∙-unit-r (S n) = Ω^'S-∙-unit-r n
Ω^'S-∙-assoc : (n : ℕ) {X : Ptd i} (p q r : Ω^' (S n) X)
→ Ω^'S-∙ n (Ω^'S-∙ n p q) r == Ω^'S-∙ n p (Ω^'S-∙ n q r)
Ω^'S-∙-assoc O = ∙-assoc
Ω^'S-∙-assoc (S n) = Ω^'S-∙-assoc n
Ω^'S-!-inv-l : (n : ℕ) {X : Ptd i} (p : Ω^' (S n) X)
→ Ω^'S-∙ n (Ω^'S-! n p) p == idp^' (S n)
Ω^'S-!-inv-l O = !-inv-l
Ω^'S-!-inv-l (S n) = Ω^'S-!-inv-l n
Ω^'S-!-inv-r : (n : ℕ) {X : Ptd i} (p : Ω^' (S n) X)
→ Ω^'S-∙ n p (Ω^'S-! n p) == idp^' (S n)
Ω^'S-!-inv-r O = !-inv-r
Ω^'S-!-inv-r (S n) = Ω^'S-!-inv-r n
module _ where
Ω-fmap-∙ : ∀ {i j} {X : Ptd i} {Y : Ptd j} (F : X ⊙→ Y) (p q : Ω X)
→ Ω-fmap F (p ∙ q) == Ω-fmap F p ∙ Ω-fmap F q
Ω-fmap-∙ (f , idp) p q = ap-∙ f p q
Ω^S-fmap-∙ : ∀ {i j} (n : ℕ)
{X : Ptd i} {Y : Ptd j} (F : X ⊙→ Y) (p q : Ω^ (S n) X)
→ Ω^-fmap (S n) F (Ω^S-∙ n p q)
== Ω^S-∙ n (Ω^-fmap (S n) F p) (Ω^-fmap (S n) F q)
Ω^S-fmap-∙ n F = Ω-fmap-∙ (⊙Ω^-fmap n F)
Ω^'S-fmap-∙ : ∀ {i j} (n : ℕ)
{X : Ptd i} {Y : Ptd j} (F : X ⊙→ Y) (p q : Ω^' (S n) X)
→ Ω^'-fmap (S n) F (Ω^'S-∙ n p q)
== Ω^'S-∙ n (Ω^'-fmap (S n) F p) (Ω^'-fmap (S n) F q)
Ω^'S-fmap-∙ O = Ω-fmap-∙
Ω^'S-fmap-∙ (S n) F = Ω^'S-fmap-∙ n (⊙Ω-fmap F)
{- [Ω^] preserves (pointed) equivalences -}
module _ {i j} {X : Ptd i} {Y : Ptd j} where
Ω^-isemap : (n : ℕ) (F : X ⊙→ Y) (e : is-equiv (fst F))
→ is-equiv (Ω^-fmap n F)
Ω^-isemap O F e = e
Ω^-isemap (S n) F e = Ω-isemap (⊙Ω^-fmap n F) (Ω^-isemap n F e)
⊙Ω^-isemap = Ω^-isemap
Ω^-emap : (n : ℕ) → X ⊙≃ Y → Ω^ n X ≃ Ω^ n Y
Ω^-emap n (F , e) = Ω^-fmap n F , Ω^-isemap n F e
⊙Ω^-emap : (n : ℕ) → X ⊙≃ Y → ⊙Ω^ n X ⊙≃ ⊙Ω^ n Y
⊙Ω^-emap n (F , e) = ⊙Ω^-fmap n F , ⊙Ω^-isemap n F e
⊙Ω^-csemap : ∀ {i₀ i₁ j₀ j₁} (n : ℕ) {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquareEquiv f g hX hY
→ ⊙CommSquareEquiv (⊙Ω^-fmap n f) (⊙Ω^-fmap n g) (⊙Ω^-fmap n hX) (⊙Ω^-fmap n hY)
⊙Ω^-csemap n {hX = hX} {hY} (cs , hX-ise , hY-ise) = ⊙Ω^-csmap n cs , Ω^-isemap n hX hX-ise , Ω^-isemap n hY hY-ise
{- [Ω^'] preserves (pointed) equivalences too -}
module _ {i j} where
Ω^'-isemap : {X : Ptd i} {Y : Ptd j} (n : ℕ) (F : X ⊙→ Y) (e : is-equiv (fst F))
→ is-equiv (Ω^'-fmap n F)
Ω^'-isemap O F e = e
Ω^'-isemap (S n) F e = Ω^'-isemap n (⊙Ω-fmap F) (Ω-isemap F e)
⊙Ω^'-isemap = Ω^'-isemap
Ω^'-emap : {X : Ptd i} {Y : Ptd j} (n : ℕ) → X ⊙≃ Y → Ω^' n X ≃ Ω^' n Y
Ω^'-emap n (F , e) = Ω^'-fmap n F , Ω^'-isemap n F e
⊙Ω^'-emap : {X : Ptd i} {Y : Ptd j} (n : ℕ) → X ⊙≃ Y → ⊙Ω^' n X ⊙≃ ⊙Ω^' n Y
⊙Ω^'-emap n (F , e) = ⊙Ω^'-fmap n F , ⊙Ω^'-isemap n F e
⊙Ω^'-csemap : ∀ {i₀ i₁ j₀ j₁} (n : ℕ) {X₀ : Ptd i₀} {X₁ : Ptd i₁}
{Y₀ : Ptd j₀} {Y₁ : Ptd j₁} {f : X₀ ⊙→ Y₀} {g : X₁ ⊙→ Y₁}
{hX : X₀ ⊙→ X₁} {hY : Y₀ ⊙→ Y₁}
→ ⊙CommSquareEquiv f g hX hY
→ ⊙CommSquareEquiv (⊙Ω^'-fmap n f) (⊙Ω^'-fmap n g) (⊙Ω^'-fmap n hX) (⊙Ω^'-fmap n hY)
⊙Ω^'-csemap n {hX = hX} {hY} (cs , hX-ise , hY-ise) = ⊙Ω^'-csmap n cs , Ω^'-isemap n hX hX-ise , Ω^'-isemap n hY hY-ise
Ω^-level : ∀ {i} (m : ℕ₋₂) (n : ℕ) (X : Ptd i)
→ (has-level (⟨ n ⟩₋₂ +2+ m) (de⊙ X) → has-level m (Ω^ n X))
Ω^-level m O X pX = pX
Ω^-level m (S n) X pX =
has-level-apply (Ω^-level (S m) n X
(transport (λ k → has-level k (de⊙ X)) (! (+2+-βr ⟨ n ⟩₋₂ m)) pX))
(idp^ n) (idp^ n)
{- As for the levels of [Ω^'], these special cases can avoid
trailing constants, and it seems we only need the following
two special cases. -}
Ω^'-is-set : ∀ {i} (n : ℕ) (X : Ptd i)
→ (has-level ⟨ n ⟩ (de⊙ X) → is-set (Ω^' n X))
Ω^'-is-set O X pX = pX
Ω^'-is-set (S n) X pX = Ω^'-is-set n (⊙Ω X) (has-level-apply pX (pt X) (pt X))
Ω^'-is-prop : ∀ {i} (n : ℕ) (X : Ptd i)
→ (has-level ⟨ n ⟩₋₁ (de⊙ X) → is-prop (Ω^' n X))
Ω^'-is-prop O X pX = pX
Ω^'-is-prop (S n) X pX = Ω^'-is-prop n (⊙Ω X) (has-level-apply pX (pt X) (pt X))
Ω^-conn : ∀ {i} (m : ℕ₋₂) (n : ℕ) (X : Ptd i)
→ (is-connected (⟨ n ⟩₋₂ +2+ m) (de⊙ X)) → is-connected m (Ω^ n X)
Ω^-conn m O X pX = pX
Ω^-conn m (S n) X pX =
path-conn $ Ω^-conn (S m) n X $
transport (λ k → is-connected k (de⊙ X)) (! (+2+-βr ⟨ n ⟩₋₂ m)) pX
{- Eckmann-Hilton argument -}
module _ {i} {X : Ptd i} where
Ω-fmap2-∙ : (α β : Ω^ 2 X) → ap2 _∙_ α β == Ω^S-∙ 1 α β
Ω-fmap2-∙ α β = ap2-out _∙_ α β ∙ ap2 _∙_ (lemma α) (ap-idf β)
where
lemma : ∀ {i} {A : Type i} {x y : A} {p q : x == y} (α : p == q)
→ ap (λ r → r ∙ idp) α == ∙-unit-r p ∙ α ∙' ! (∙-unit-r q)
lemma {p = idp} idp = idp
⊙Ω-fmap2-∙ : ⊙Ω-fmap2 (⊙Ω-∙ {X = X}) == ⊙Ω-∙
⊙Ω-fmap2-∙ = ⊙λ=' (uncurry Ω-fmap2-∙) idp
Ω^2-∙-comm : (α β : Ω^ 2 X) → Ω^S-∙ 1 α β == Ω^S-∙ 1 β α
Ω^2-∙-comm α β = ! (⋆2=Ω^S-∙ α β) ∙ ⋆2=⋆'2 α β ∙ ⋆'2=Ω^S-∙ α β
where
⋆2=Ω^S-∙ : (α β : Ω^ 2 X) → α ⋆2 β == Ω^S-∙ 1 α β
⋆2=Ω^S-∙ α β = ap (λ π → π ∙ β) (∙-unit-r α)
⋆'2=Ω^S-∙ : (α β : Ω^ 2 X) → α ⋆'2 β == Ω^S-∙ 1 β α
⋆'2=Ω^S-∙ α β = ap (λ π → β ∙ π) (∙-unit-r α)
{- NOT USED and DUPLICATE of [Ω^S-Trunc-preiso] in lib.groups.HomotopyGroup.
XXX Should be an equivalence.
{- Pushing truncation through loop space -}
module _ {i} where
Trunc-Ω^-conv : (m : ℕ₋₂) (n : ℕ) (X : Ptd i)
→ ⊙Trunc m (⊙Ω^ n X) == ⊙Ω^ n (⊙Trunc (⟨ n ⟩₋₂ +2+ m) X)
Trunc-Ω^-conv m O X = idp
Trunc-Ω^-conv m (S n) X =
⊙Trunc m (⊙Ω^ (S n) X)
=⟨ ! (pair= (Trunc=-path [ _ ] [ _ ]) (↓-idf-ua-in _ idp)) ⟩
⊙Ω (⊙Trunc (S m) (⊙Ω^ n X))
=⟨ ap ⊙Ω (Trunc-Ω^-conv (S m) n X) ⟩
⊙Ω^ (S n) (⊙Trunc (⟨ n ⟩₋₂ +2+ S m) X)
=⟨ +2+-βr ⟨ n ⟩₋₂ m |in-ctx (λ k → ⊙Ω^ (S n) (⊙Trunc k X)) ⟩
⊙Ω^ (S n) (⊙Trunc (S ⟨ n ⟩₋₂ +2+ m) X) =∎
Ω-Trunc-econv : (m : ℕ₋₂) (X : Ptd i)
→ Ω (⊙Trunc (S m) X) ≃ Trunc m (Ω X)
Ω-Trunc-econv m X = Trunc=-equiv [ pt X ] [ pt X ]
-}
{- Our definition of [Ω^] builds up loops from the outside,
- but this is equivalent to building up from the inside -}
module _ {i} where
⊙Ω^-Ω-split : (n : ℕ) (X : Ptd i)
→ (⊙Ω^ (S n) X ⊙→ ⊙Ω^ n (⊙Ω X))
⊙Ω^-Ω-split O _ = (idf _ , idp)
⊙Ω^-Ω-split (S n) X = ⊙Ω-fmap (⊙Ω^-Ω-split n X)
Ω^-Ω-split : (n : ℕ) (X : Ptd i)
→ (Ω^ (S n) X → Ω^ n (⊙Ω X))
Ω^-Ω-split n X = fst (⊙Ω^-Ω-split n X)
Ω^S-Ω-split-∙ : (n : ℕ)
(X : Ptd i) (p q : Ω^ (S (S n)) X)
→ Ω^-Ω-split (S n) X (Ω^S-∙ (S n) p q)
== Ω^S-∙ n (Ω^-Ω-split (S n) X p) (Ω^-Ω-split (S n) X q)
Ω^S-Ω-split-∙ n X p q =
Ω^S-fmap-∙ 0 (⊙Ω^-Ω-split n X) p q
Ω^-Ω-split-is-equiv : (n : ℕ) (X : Ptd i)
→ is-equiv (Ω^-Ω-split n X)
Ω^-Ω-split-is-equiv O X = is-eq (idf _) (idf _) (λ _ → idp) (λ _ → idp)
Ω^-Ω-split-is-equiv (S n) X =
⊙Ω^-isemap 1 (⊙Ω^-Ω-split n X) (Ω^-Ω-split-is-equiv n X)
Ω^-Ω-split-equiv : (n : ℕ) (X : Ptd i) → Ω^ (S n) X ≃ Ω^ n (⊙Ω X)
Ω^-Ω-split-equiv n X = _ , Ω^-Ω-split-is-equiv n X
module _ {i j} (X : Ptd i) (Y : Ptd j) where
Ω-× : Ω (X ⊙× Y) ≃ Ω X × Ω Y
Ω-× = equiv
(λ p → fst×= p , snd×= p)
(λ p → pair×= (fst p) (snd p))
(λ p → pair×= (fst×=-β (fst p) (snd p)) (snd×=-β (fst p) (snd p)))
(! ∘ pair×=-η)
⊙Ω-× : ⊙Ω (X ⊙× Y) ⊙≃ ⊙Ω X ⊙× ⊙Ω Y
⊙Ω-× = ≃-to-⊙≃ Ω-× idp
Ω-×-∙ : ∀ (p q : Ω (X ⊙× Y))
→ –> Ω-× (p ∙ q) == (fst (–> Ω-× p) ∙ fst (–> Ω-× q) , snd (–> Ω-× p) ∙ snd (–> Ω-× q))
Ω-×-∙ p q = pair×= (Ω-fmap-∙ ⊙fst p q) (Ω-fmap-∙ ⊙snd p q)
module _ {i j} where
⊙Ω^-× : ∀ (n : ℕ) (X : Ptd i) (Y : Ptd j)
→ ⊙Ω^ n (X ⊙× Y) ⊙≃ ⊙Ω^ n X ⊙× ⊙Ω^ n Y
⊙Ω^-× O _ _ = ⊙ide _
⊙Ω^-× (S n) X Y = ⊙Ω-× (⊙Ω^ n X) (⊙Ω^ n Y) ⊙∘e ⊙Ω-emap (⊙Ω^-× n X Y)
⊙Ω^'-× : ∀ (n : ℕ) (X : Ptd i) (Y : Ptd j)
→ ⊙Ω^' n (X ⊙× Y) ⊙≃ ⊙Ω^' n X ⊙× ⊙Ω^' n Y
⊙Ω^'-× O _ _ = ⊙ide _
⊙Ω^'-× (S n) X Y = ⊙Ω^'-× n (⊙Ω X) (⊙Ω Y) ⊙∘e ⊙Ω^'-emap n (⊙Ω-× X Y)
|
= = Edibility = =
|
#ifndef LOGSPLINEPDF
#define LOGSPLINEPDF
#include <gsl/gsl_rng.h>
#include "splinetable.h"
#ifdef __cplusplus
extern "C" {
#endif
void logsplinepdf_n_sample(double *result, int results, int burnin,
double *coords, int dim, struct splinetable *table, int derivatives,
double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),
void *proposal_info, const gsl_rng *rng);
void splinepdf_n_sample(double *result, int results, int burnin,
double *coords, int dim, struct splinetable *table, int derivatives,
double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),
void *proposal_info, const gsl_rng *rng);
#ifdef __cplusplus
}
#endif
#endif
|
Beautiful Medium Length Hairstyles With Bangs – Medium length hair is suits all long that can make you turn head without having to spend hours in front of a mirror. Get ready to make the change by choosing the latest mid-length haircuts with bangs.
Medium length haircut is the new keyword as far as trends go, the haircuts because they are suitable for everyone and they are easy to style, creating a perfect balance between flexibility and maintenance. Medium length haircuts look stunning especially if paired with a set of stylish bangs, which not only make the best of a person’s facial features, but also add a little twist to the ordinary display. Long haircuts with bangs Medium look amazing and can certainly bring a different air to look at You, regardless of your natural hair texture.
This season, medium length haircuts are all about nature, easy texture that promote low maintenance and requires a minimum amount of products and tools. Layers are really the perfect choice if you are in love with your hair volume, because they help to remove some of the weight of the hair, allow hair to receive more texture. Medium layered haircuts, either soft or wavy, can be paired with side sweeping bangs styles, as well as blunt or asymmetrical cut bangs long or short, the results allow you to get a unique look. Add a little texture through midi You with product support and sweeping bangs You volumizing sideways to see the slums or channeling your inner diva on the outside with going straight or curly. |
[STATEMENT]
lemma env_map_env [simp]: "env (map ENV w) = map ENV w"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. env (map ENV w) = map ENV w
[PROOF STEP]
by (unfold env_def) simp |
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Sean Leather
-/
import algebra.group.opposite
import algebra.free_monoid.basic
import control.traversable.instances
import control.traversable.lemmas
import category_theory.endomorphism
import category_theory.types
import category_theory.category.Kleisli
/-!
# List folds generalized to `traversable`
Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the
reconstructed data structure and, in a state monad, we care about the final state.
The obvious way to define `foldl` would be to use the state monad but it
is nicer to reason about a more abstract interface with `fold_map` as a
primitive and `fold_map_hom` as a defining property.
```
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ...
lemma fold_map_hom (α β)
[monoid α] [monoid β] (f : α →* β)
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
...
```
`fold_map` uses a monoid ω to accumulate a value for every element of
a data structure and `fold_map_hom` uses a monoid homomorphism to
substitute the monoid used by `fold_map`. The two are sufficient to
define `foldl`, `foldr` and `to_list`. `to_list` permits the
formulation of specifications in terms of operations on lists.
Each fold function can be defined using a specialized
monoid. `to_list` uses a free monoid represented as a list with
concatenation while `foldl` uses endofunctions together with function
composition.
The definition through monoids uses `traverse` together with the
applicative functor `const m` (where `m` is the monoid). As an
implementation, `const` guarantees that no resource is spent on
reconstructing the structure during traversal.
A special class could be defined for `foldable`, similarly to Haskell,
but the author cannot think of instances of `foldable` that are not also
`traversable`.
-/
universes u v
open ulift category_theory mul_opposite
namespace monoid
variables {m : Type u → Type u} [monad m]
variables {α β : Type u}
/--
For a list, foldl f x [y₀,y₁] reduces as follows:
```
calc foldl f x [y₀,y₁]
= foldl f (f x y₀) [y₁] : rfl
... = foldl f (f (f x y₀) y₁) [] : rfl
... = f (f x y₀) y₁ : rfl
```
with
```
f : α → β → α
x : α
[y₀,y₁] : list β
```
We can view the above as a composition of functions:
```
... = f (f x y₀) y₁ : rfl
... = flip f y₁ (flip f y₀ x) : rfl
... = (flip f y₁ ∘ flip f y₀) x : rfl
```
We can use traverse and const to construct this composition:
```
calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x
= const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x
... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘
((::) <$> const.mk' (flip f y₀)) ) x
... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x
... = const.run ( flip f y₁ ∘ flip f y₀ ) x
... = f (f x y₀) y₁
```
And this is how `const` turns a monoid into an applicative functor and
how the monoid of endofunctions define `foldl`.
-/
@[reducible] def foldl (α : Type u) : Type u := (End α)ᵐᵒᵖ
def foldl.mk (f : α → α) : foldl α := op f
def foldl.get (x : foldl α) : α → α := unop x
@[simps] def foldl.of_free_monoid (f : β → α → β) : free_monoid α →* monoid.foldl β :=
{ to_fun := λ xs, op $ flip (list.foldl f) xs.to_list,
map_one' := rfl,
map_mul' := by intros; simp only [free_monoid.to_list_mul, flip, unop_op,
list.foldl_append, op_inj]; refl }
@[reducible] def foldr (α : Type u) : Type u := End α
def foldr.mk (f : α → α) : foldr α := f
def foldr.get (x : foldr α) : α → α := x
@[simps] def foldr.of_free_monoid (f : α → β → β) : free_monoid α →* monoid.foldr β :=
{ to_fun := λ xs, flip (list.foldr f) xs.to_list,
map_one' := rfl,
map_mul' := λ xs ys, funext $ λ z, list.foldr_append _ _ _ _ }
@[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u :=
mul_opposite $ End $ Kleisli.mk m α
def mfoldl.mk (f : α → m α) : mfoldl m α := op f
def mfoldl.get (x : mfoldl m α) : α → m α := unop x
@[simps] def mfoldl.of_free_monoid [is_lawful_monad m] (f : β → α → m β) :
free_monoid α →* monoid.mfoldl m β :=
{ to_fun := λ xs, op $ flip (list.mfoldl f) xs.to_list,
map_one' := rfl,
map_mul' := by intros; apply unop_injective; ext; apply list.mfoldl_append }
@[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u :=
End $ Kleisli.mk m α
def mfoldr.mk (f : α → m α) : mfoldr m α := f
def mfoldr.get (x : mfoldr m α) : α → m α := x
@[simps] def mfoldr.of_free_monoid [is_lawful_monad m] (f : α → β → m β) :
free_monoid α →* monoid.mfoldr m β :=
{ to_fun := λ xs, flip (list.mfoldr f) xs.to_list,
map_one' := rfl,
map_mul' := by intros; ext; apply list.mfoldr_append }
end monoid
namespace traversable
open monoid functor
section defs
variables {α β : Type u} {t : Type u → Type u} [traversable t]
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω :=
traverse (const.mk' ∘ f)
def foldl (f : α → β → α) (x : α) (xs : t β) : α :=
(fold_map (foldl.mk ∘ flip f) xs).get x
def foldr (f : α → β → β) (x : β) (xs : t α) : β :=
(fold_map (foldr.mk ∘ f) xs).get x
/--
Conceptually, `to_list` collects all the elements of a collection
in a list. This idea is formalized by
`lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`.
The definition of `to_list` is based on `foldl` and `list.cons` for
speed. It is faster than using `fold_map free_monoid.mk` because, by
using `foldl` and `list.cons`, each insertion is done in constant
time. As a consequence, `to_list` performs in linear.
On the other hand, `fold_map free_monoid.mk` creates a singleton list
around each element and concatenates all the resulting lists. In
`xs ++ ys`, concatenation takes a time proportional to `length xs`. Since
the order in which concatenation is evaluated is unspecified, nothing
prevents each element of the traversable to be appended at the end
`xs ++ [x]` which would yield a `O(n²)` run time. -/
def to_list : t α → list α :=
list.reverse ∘ foldl (flip list.cons) []
def length (xs : t α) : ℕ :=
down $ foldl (λ l _, up $ l.down + 1) (up 0) xs
variables {m : Type u → Type u} [monad m]
def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α :=
(fold_map (mfoldl.mk ∘ flip f) xs).get x
def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β :=
(fold_map (mfoldr.mk ∘ f) xs).get x
end defs
section applicative_transformation
variables {α β γ : Type u}
open function (hiding const)
def map_fold [monoid α] [monoid β] (f : α →* β) :
applicative_transformation (const α) (const β) :=
{ app := λ x, f,
preserves_seq' := by { intros, simp only [f.map_mul, (<*>)], },
preserves_pure' := by { intros, simp only [f.map_one, pure] } }
lemma free.map_eq_map (f : α → β) (xs : list α) :
f <$> xs = (free_monoid.map f (free_monoid.of_list xs)).to_list := rfl
lemma foldl.unop_of_free_monoid (f : β → α → β) (xs : free_monoid α) (a : β) :
unop (foldl.of_free_monoid f xs) a = list.foldl f a xs.to_list := rfl
variables (m : Type u → Type u) [monad m] [is_lawful_monad m]
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
open is_lawful_traversable
lemma fold_map_hom [monoid α] [monoid β] (f : α →* β)
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
calc f (fold_map g x)
= f (traverse (const.mk' ∘ g) x) : rfl
... = (map_fold f).app _ (traverse (const.mk' ∘ g) x) : rfl
... = traverse ((map_fold f).app _ ∘ (const.mk' ∘ g)) x :
naturality (map_fold f) _ _
... = fold_map (f ∘ g) x : rfl
lemma fold_map_hom_free
[monoid β] (f : free_monoid α →* β) (x : t α) :
f (fold_map free_monoid.of x) = fold_map (f ∘ free_monoid.of) x :=
fold_map_hom f _ x
end applicative_transformation
section equalities
open is_lawful_traversable list (cons)
variables {α β γ : Type u}
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
@[simp]
lemma foldl.of_free_monoid_comp_of (f : α → β → α) :
foldl.of_free_monoid f ∘ free_monoid.of = foldl.mk ∘ flip f := rfl
@[simp]
lemma foldr.of_free_monoid_comp_of (f : β → α → α) :
foldr.of_free_monoid f ∘ free_monoid.of = foldr.mk ∘ f := rfl
@[simp]
lemma mfoldl.of_free_monoid_comp_of {m} [monad m] [is_lawful_monad m] (f : α → β → m α) :
mfoldl.of_free_monoid f ∘ free_monoid.of = mfoldl.mk ∘ flip f :=
by { ext1 x, simp [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip], refl }
@[simp]
lemma mfoldr.of_free_monoid_comp_of {m} [monad m] [is_lawful_monad m] (f : β → α → m α) :
mfoldr.of_free_monoid f ∘ free_monoid.of = mfoldr.mk ∘ f :=
by { ext, simp [(∘), mfoldr.of_free_monoid, mfoldr.mk, flip] }
lemma to_list_spec (xs : t α) :
to_list xs = free_monoid.to_list (fold_map free_monoid.of xs) :=
eq.symm $
calc free_monoid.to_list (fold_map free_monoid.of xs)
= free_monoid.to_list (fold_map free_monoid.of xs).reverse.reverse
: by simp only [list.reverse_reverse]
... = free_monoid.to_list (list.foldr cons [] (fold_map free_monoid.of xs).reverse).reverse
: by simp only [list.foldr_eta]
... = (unop (foldl.of_free_monoid (flip cons) (fold_map free_monoid.of xs)) []).reverse
: by simp [flip, list.foldr_reverse, foldl.of_free_monoid, unop_op]
... = to_list xs : begin
rw fold_map_hom_free (foldl.of_free_monoid (flip $ @cons α)),
{ simp only [to_list, foldl, list.reverse_inj, foldl.get,
foldl.of_free_monoid_comp_of] },
{ apply_instance }
end
lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) :
fold_map g (f <$> xs) = fold_map (g ∘ f) xs :=
by simp only [fold_map,traverse_map]
lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) :
foldl f x xs = list.foldl f x (to_list xs) :=
begin
rw [← free_monoid.to_list_of_list (to_list xs), ← foldl.unop_of_free_monoid],
simp only [foldl, to_list_spec, fold_map_hom_free,
foldl.of_free_monoid_comp_of, foldl.get, free_monoid.of_list_to_list]
end
lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) :
foldr f x xs = list.foldr f x (to_list xs) :=
begin
change _ = foldr.of_free_monoid _ (free_monoid.of_list $ to_list xs) _,
rw [to_list_spec, foldr, foldr.get, free_monoid.of_list_to_list, fold_map_hom_free,
foldr.of_free_monoid_comp_of]
end
/-
-/
lemma to_list_map (f : α → β) (xs : t α) :
to_list (f <$> xs) = f <$> to_list xs :=
by simp only [to_list_spec, free.map_eq_map, fold_map_hom, fold_map_map,
free_monoid.of_list_to_list, free_monoid.map_of, (∘)]
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) :
foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l :=
by simp only [foldl, fold_map_map, (∘), flip]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) :
foldr f a (g <$> l) = foldr (f ∘ g) a l :=
by simp only [foldr, fold_map_map, (∘), flip]
@[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs :=
begin
simp only [to_list_spec, fold_map, traverse],
induction xs,
case list.nil { refl },
case list.cons : _ _ ih { conv_rhs { rw [← ih] }, refl }
end
theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) :=
begin
unfold length,
rw foldl_to_list,
generalize : to_list xs = ys,
let f := λ (n : ℕ) (a : α), n + 1,
transitivity list.foldl f 0 ys,
{ generalize : 0 = n,
induction ys with _ _ ih generalizing n,
{ simp only [list.foldl_nil] },
{ simp only [list.foldl, ih (n+1)] } },
{ induction ys with _ tl ih,
{ simp only [list.length, list.foldl_nil] },
{ simp only [list.foldl, list.length],
rw [← ih],
exact tl.foldl_hom (λx, x+1) f f 0 (λ n x, rfl) } }
end
variables {m : Type u → Type u} [monad m] [is_lawful_monad m]
lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} :
mfoldl f x xs = list.mfoldl f x (to_list xs) :=
calc mfoldl f x xs = unop (mfoldl.of_free_monoid f (free_monoid.of_list $ to_list xs)) x :
by simp only [mfoldl, to_list_spec, fold_map_hom_free (mfoldl.of_free_monoid f),
mfoldl.of_free_monoid_comp_of, mfoldl.get, free_monoid.of_list_to_list]
... = list.mfoldl f x (to_list xs) : by simp [mfoldl.of_free_monoid, unop_op, flip]
lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) :
mfoldr f x xs = list.mfoldr f x (to_list xs) :=
begin
change _ = mfoldr.of_free_monoid f (free_monoid.of_list $ to_list xs) x,
simp only [mfoldr, to_list_spec, fold_map_hom_free (mfoldr.of_free_monoid f),
mfoldr.of_free_monoid_comp_of, mfoldr.get, free_monoid.of_list_to_list]
end
@[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) :
mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l :=
by simp only [mfoldl, fold_map_map, (∘), flip]
@[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) :
mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l :=
by simp only [mfoldr, fold_map_map, (∘), flip]
end equalities
end traversable
|
/-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Multiplicity and prime factors. We have:
mult p n := the greatest power of p dividing n if p > 1 and n > 0, and 0 otherwise.
prime_factors n := the finite set of prime factors of n, assuming n > 0
-/
import data.nat data.finset .primes algebra.group_bigops
open eq.ops finset well_founded decidable
namespace nat
-- TODO: this should be proved more generally in ring_bigops
theorem Prod_pos {A : Type} [deceqA : decidable_eq A]
{s : finset A} {f : A → ℕ} (fpos : ∀ n, n ∈ s → f n > 0) :
(∏ n ∈ s, f n) > 0 :=
begin
induction s with a s anins ih,
{rewrite Prod_empty; exact zero_lt_one},
rewrite [!Prod_insert_of_not_mem anins],
exact (mul_pos (fpos a (mem_insert a _)) (ih (forall_of_forall_insert fpos)))
end
/- multiplicity -/
theorem mult_rec_decreasing {p n : ℕ} (Hp : p > 1) (Hn : n > 0) : n / p < n :=
have H' : n < n * p,
by rewrite [-mul_one n at {1}]; apply mul_lt_mul_of_pos_left Hp Hn,
nat.div_lt_of_lt_mul H'
private definition mult.F (p : ℕ) (n : ℕ) (f: Π {m : ℕ}, m < n → ℕ) : ℕ :=
if H : (p > 1 ∧ n > 0) ∧ p ∣ n then
succ (f (mult_rec_decreasing (and.left (and.left H)) (and.right (and.left H))))
else 0
definition mult (p n : ℕ) : ℕ := fix (mult.F p) n
theorem mult_rec {p n : ℕ} (pgt1 : p > 1) (ngt0 : n > 0) (pdivn : p ∣ n) :
mult p n = succ (mult p (n / p)) :=
have (p > 1 ∧ n > 0) ∧ p ∣ n, from and.intro (and.intro pgt1 ngt0) pdivn,
eq.trans (well_founded.fix_eq (mult.F p) n) (dif_pos this)
private theorem mult_base {p n : ℕ} (H : ¬ ((p > 1 ∧ n > 0) ∧ p ∣ n)) :
mult p n = 0 :=
eq.trans (well_founded.fix_eq (mult.F p) n) (dif_neg H)
theorem mult_zero_right (p : ℕ) : mult p 0 = 0 :=
mult_base (assume H, !lt.irrefl (and.right (and.left H)))
theorem mult_eq_zero_of_not_dvd {p n : ℕ} (H : ¬ p ∣ n) : mult p n = 0 :=
mult_base (assume H', H (and.right H'))
theorem mult_eq_zero_of_le_one {p : ℕ} (n : ℕ) (H : p ≤ 1) : mult p n = 0 :=
mult_base (assume H', not_lt_of_ge H (and.left (and.left H')))
theorem mult_zero_left (n : ℕ) : mult 0 n = 0 :=
mult_eq_zero_of_le_one n !dec_trivial
theorem mult_one_left (n : ℕ) : mult 1 n = 0 :=
mult_eq_zero_of_le_one n !dec_trivial
theorem mult_pos_of_dvd {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pdvdn : p ∣ n) : mult p n > 0 :=
by rewrite (mult_rec pgt1 npos pdvdn); apply succ_pos
theorem not_dvd_of_mult_eq_zero {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (H : mult p n = 0) :
¬ p ∣ n :=
suppose p ∣ n,
ne_of_gt (mult_pos_of_dvd pgt1 npos this) H
theorem dvd_of_mult_pos {p n : ℕ} (H : mult p n > 0) : p ∣ n :=
by_contradiction (suppose ¬ p ∣ n, ne_of_gt H (mult_eq_zero_of_not_dvd this))
/- properties of mult -/
theorem mult_eq_zero_of_prime_of_ne {p q : ℕ} (primep : prime p) (primeq : prime q)
(pneq : p ≠ q) :
mult p q = 0 :=
mult_eq_zero_of_not_dvd (not_dvd_of_prime_of_coprime primep (coprime_primes primep primeq pneq))
theorem pow_mult_dvd (p n : ℕ) : p^(mult p n) ∣ n :=
begin
induction n using nat.strong_induction_on with [n, ih],
cases eq_zero_or_pos n with [nz, npos],
{rewrite nz, apply dvd_zero},
cases le_or_gt p 1 with [ple1, pgt1],
{rewrite [!mult_eq_zero_of_le_one ple1, pow_zero], apply one_dvd},
cases (or.swap (em (p ∣ n))) with [pndvdn, pdvdn],
{rewrite [mult_eq_zero_of_not_dvd pndvdn, pow_zero], apply one_dvd},
show p ^ (mult p n) ∣ n, from dvd.elim pdvdn
(take n',
suppose n = p * n',
have p > 0, from lt.trans zero_lt_one pgt1,
have n / p = n', from !nat.div_eq_of_eq_mul_right this `n = p * n'`,
have n' < n,
by rewrite -this; apply mult_rec_decreasing pgt1 npos,
begin
rewrite [mult_rec pgt1 npos pdvdn, `n / p = n'`, pow_succ], subst n,
apply mul_dvd_mul !dvd.refl,
apply ih _ this
end)
end
theorem mult_one_right (p : ℕ) : mult p 1 = 0:=
have H : p^(mult p 1) = 1, from eq_one_of_dvd_one !pow_mult_dvd,
or.elim (le_or_gt p 1)
(suppose p ≤ 1, by rewrite [!mult_eq_zero_of_le_one this])
(suppose p > 1,
by_contradiction
(suppose mult p 1 ≠ 0,
have mult p 1 > 0, from pos_of_ne_zero this,
have p^(mult p 1) > 1, from pow_gt_one `p > 1` this,
show false, by rewrite H at this; apply !lt.irrefl this))
private theorem mult_pow_mul {p n : ℕ} (i : ℕ) (pgt1 : p > 1) (npos : n > 0) :
mult p (p^i * n) = i + mult p n :=
begin
induction i with [i, ih],
{krewrite [pow_zero, one_mul, zero_add]},
have p > 0, from lt.trans zero_lt_one pgt1,
have psin_pos : p^(succ i) * n > 0, from mul_pos (!pow_pos_of_pos this) npos,
have p ∣ p^(succ i) * n, by rewrite [pow_succ, mul.assoc]; apply dvd_mul_right,
rewrite [mult_rec pgt1 psin_pos this, pow_succ', mul.right_comm, !nat.mul_div_cancel `p > 0`, ih],
rewrite [add.comm i, add.comm (succ i)]
end
theorem mult_pow_self {p : ℕ} (i : ℕ) (pgt1 : p > 1) : mult p (p^i) = i :=
by rewrite [-(mul_one (p^i)), mult_pow_mul i pgt1 zero_lt_one, mult_one_right]
theorem mult_self {p : ℕ} (pgt1 : p > 1) : mult p p = 1 :=
by rewrite [-pow_one p at {2}]; apply mult_pow_self 1 pgt1
theorem le_mult {p i n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pidvd : p^i ∣ n) : i ≤ mult p n :=
dvd.elim pidvd
(take m,
suppose n = p^i * m,
have m > 0, from pos_of_mul_pos_left (this ▸ npos),
by subst n; rewrite [mult_pow_mul i pgt1 this]; apply le_add_right)
theorem not_dvd_div_pow_mult {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) : ¬ p ∣ n / p^(mult p n) :=
assume pdvd : p ∣ n / p^(mult p n),
obtain m (H : n / p^(mult p n) = p * m), from exists_eq_mul_right_of_dvd pdvd,
have n = p^(succ (mult p n)) * m, from
calc
n = p^mult p n * (n / p^mult p n) : by rewrite (nat.mul_div_cancel' !pow_mult_dvd)
... = p^(succ (mult p n)) * m : by rewrite [H, pow_succ', mul.assoc],
have p^(succ (mult p n)) ∣ n, by rewrite this at {2}; apply dvd_mul_right,
have succ (mult p n) ≤ mult p n, from le_mult pgt1 npos this,
show false, from !not_succ_le_self this
theorem mult_mul {p m n : ℕ} (primep : prime p) (mpos : m > 0) (npos : n > 0) :
mult p (m * n) = mult p m + mult p n :=
let m' := m / p^mult p m, n' := n / p^mult p n in
have p > 1, from gt_one_of_prime primep,
have meq : m = p^mult p m * m', by rewrite (nat.mul_div_cancel' !pow_mult_dvd),
have neq : n = p^mult p n * n', by rewrite (nat.mul_div_cancel' !pow_mult_dvd),
have m'pos : m' > 0, from pos_of_mul_pos_left (meq ▸ mpos),
have n'pos : n' > 0, from pos_of_mul_pos_left (neq ▸ npos),
have npdvdm' : ¬ p ∣ m', from !not_dvd_div_pow_mult `p > 1` mpos,
have npdvdn' : ¬ p ∣ n', from !not_dvd_div_pow_mult `p > 1` npos,
have npdvdm'n' : ¬ p ∣ m' * n', from not_dvd_mul_of_prime primep npdvdm' npdvdn',
have m'n'pos : m' * n' > 0, from mul_pos m'pos n'pos,
have multm'n' : mult p (m' * n') = 0, from mult_eq_zero_of_not_dvd npdvdm'n',
calc
mult p (m * n) = mult p (p^(mult p m + mult p n) * (m' * n')) :
by rewrite [pow_add, mul.right_comm, -mul.assoc, -meq, mul.assoc,
mul.comm (n / _), -neq]
... = mult p m + mult p n :
by rewrite [!mult_pow_mul `p > 1` m'n'pos, multm'n']
theorem mult_pow {p m : ℕ} (n : ℕ) (mpos : m > 0) (primep : prime p) :
mult p (m^n) = n * mult p m :=
begin
induction n with n ih,
krewrite [pow_zero, mult_one_right, zero_mul],
rewrite [pow_succ, mult_mul primep mpos (!pow_pos_of_pos mpos), ih, succ_mul, add.comm]
end
theorem dvd_of_forall_prime_mult_le {m n : ℕ} (mpos : m > 0)
(H : ∀ {p}, prime p → mult p m ≤ mult p n) :
m ∣ n :=
begin
revert H, revert n,
induction m using nat.strong_induction_on with [m, ih],
cases (decidable.em (m = 1)) with [meq, mneq],
{intros, rewrite meq, apply one_dvd},
have mgt1 : m > 1, from lt_of_le_of_ne (succ_le_of_lt mpos) (ne.symm mneq),
have mge2 : m ≥ 2, from succ_le_of_lt mgt1,
have hpd : ∃ p, prime p ∧ p ∣ m, from exists_prime_and_dvd mge2,
cases hpd with [p, H1],
cases H1 with [primep, pdvdm],
intro n,
cases (eq_zero_or_pos n) with [nz, npos],
{intros; rewrite nz; apply dvd_zero},
assume H : ∀ {p : ℕ}, prime p → mult p m ≤ mult p n,
obtain m' (meq : m = p * m'), from exists_eq_mul_right_of_dvd pdvdm,
have pgt1 : p > 1, from gt_one_of_prime primep,
have m'pos : m' > 0, from pos_of_ne_zero
(assume m'z, by revert mpos; rewrite [meq, m'z, mul_zero]; apply not_lt_zero),
have m'ltm : m' < m,
by rewrite [meq, -one_mul m' at {1}]; apply mul_lt_mul_of_lt_of_le m'pos pgt1 !le.refl,
have multpm : mult p m ≥ 1, from le_mult pgt1 mpos (by rewrite pow_one; apply pdvdm),
have multpn : mult p n ≥ 1, from le.trans multpm (H primep),
obtain n' (neq : n = p * n'),
from exists_eq_mul_right_of_dvd (dvd_of_mult_pos (lt_of_succ_le multpn)),
have n'pos : n' > 0, from pos_of_ne_zero
(assume n'z, by revert npos; rewrite [neq, n'z, mul_zero]; apply not_lt_zero),
have ∀q, prime q → mult q m' ≤ mult q n', from
(take q,
assume primeq : prime q,
have multqm : mult q m = mult q p + mult q m',
by rewrite [meq, mult_mul primeq (pos_of_prime primep) m'pos],
have multqn : mult q n = mult q p + mult q n',
by rewrite [neq, mult_mul primeq (pos_of_prime primep) n'pos],
show mult q m' ≤ mult q n', from le_of_add_le_add_left (multqm ▸ multqn ▸ H primeq)),
have m'dvdn' : m' ∣ n', from ih m' m'ltm m'pos n' this,
show m ∣ n, by rewrite [meq, neq]; apply mul_dvd_mul !dvd.refl m'dvdn'
end
theorem eq_of_forall_prime_mult_eq {m n : ℕ} (mpos : m > 0) (npos : n > 0)
(H : ∀ p, prime p → mult p m = mult p n) : m = n :=
dvd.antisymm
(dvd_of_forall_prime_mult_le mpos (take p, assume primep, H _ primep ▸ !le.refl))
(dvd_of_forall_prime_mult_le npos (take p, assume primep, H _ primep ▸ !le.refl))
/- prime factors -/
definition prime_factors (n : ℕ) : finset ℕ := { p ∈ upto (succ n) | prime p ∧ p ∣ n }
theorem prime_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : prime p :=
and.left (of_mem_sep H)
theorem dvd_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : p ∣ n :=
and.right (of_mem_sep H)
theorem mem_prime_factors {p n : ℕ} (npos : n > 0) (primep : prime p) (pdvdn : p ∣ n) :
p ∈ prime_factors n :=
have plen : p ≤ n, from le_of_dvd npos pdvdn,
mem_sep_of_mem (mem_upto_of_lt (lt_succ_of_le plen)) (and.intro primep pdvdn)
/- prime factorization -/
theorem mult_pow_eq_zero_of_prime_of_ne {p q : ℕ} (primep : prime p) (primeq : prime q)
(pneq : p ≠ q) (i : ℕ) : mult p (q^i) = 0 :=
begin
induction i with i ih,
{krewrite [pow_zero, mult_one_right]},
have qpos : q > 0, from pos_of_prime primeq,
have qipos : q^i > 0, from !pow_pos_of_pos qpos,
rewrite [pow_succ', mult_mul primep qipos qpos, ih, mult_eq_zero_of_prime_of_ne primep
primeq pneq]
end
theorem mult_prod_pow_of_not_mem {p : ℕ} (primep : prime p) {s : finset ℕ}
(sprimes : ∀ p, p ∈ s → prime p) (f : ℕ → ℕ) (pns : p ∉ s) :
mult p (∏ q ∈ s, q^(f q)) = 0 :=
begin
induction s with a s anins ih,
{rewrite [Prod_empty, mult_one_right]},
have pnea : p ≠ a, from assume peqa, by rewrite peqa at pns; exact pns !mem_insert,
have primea : prime a, from sprimes a !mem_insert,
have afapos : a ^ f a > 0, from !pow_pos_of_pos (pos_of_prime primea),
have prodpos : (∏ q ∈ s, q ^ f q) > 0,
from Prod_pos (take q, assume qs,
!pow_pos_of_pos (pos_of_prime (forall_of_forall_insert sprimes q qs))),
rewrite [!Prod_insert_of_not_mem anins, mult_mul primep afapos prodpos],
rewrite (mult_pow_eq_zero_of_prime_of_ne primep primea pnea),
rewrite (ih (forall_of_forall_insert sprimes) (λ H, pns (!mem_insert_of_mem H)))
end
theorem mult_prod_pow_of_mem {p : ℕ} (primep : prime p) {s : finset ℕ}
(sprimes : ∀ p, p ∈ s → prime p) (f : ℕ → ℕ) (ps : p ∈ s) :
mult p (∏ q ∈ s, q^(f q)) = f p :=
begin
induction s with a s anins ih,
{exact absurd ps !not_mem_empty},
have primea : prime a, from sprimes a !mem_insert,
have afapos : a ^ f a > 0, from !pow_pos_of_pos (pos_of_prime primea),
have prodpos : (∏ q ∈ s, q ^ f q) > 0,
from Prod_pos (take q, assume qs,
!pow_pos_of_pos (pos_of_prime (forall_of_forall_insert sprimes q qs))),
rewrite [!Prod_insert_of_not_mem anins, mult_mul primep afapos prodpos],
cases eq_or_mem_of_mem_insert ps with peqa pins,
{rewrite [peqa, !mult_pow_self (gt_one_of_prime primea)],
rewrite [mult_prod_pow_of_not_mem primea (forall_of_forall_insert sprimes) _ anins]},
have pnea : p ≠ a, from by intro peqa; rewrite peqa at pins; exact anins pins,
rewrite [mult_pow_eq_zero_of_prime_of_ne primep primea pnea, zero_add],
exact (ih (forall_of_forall_insert sprimes) pins)
end
theorem eq_prime_factorization {n : ℕ} (npos : n > 0) :
n = (∏ p ∈ prime_factors n, p^(mult p n)) :=
let nprod := ∏ p ∈ prime_factors n, p^(mult p n) in
have primefactors : ∀ p, p ∈ prime_factors n → prime p,
from take p, @prime_of_mem_prime_factors p n,
have prodpos : (∏ q ∈ prime_factors n, q^(mult q n)) > 0,
from Prod_pos (take q, assume qpf,
!pow_pos_of_pos (pos_of_prime (prime_of_mem_prime_factors qpf))),
eq_of_forall_prime_mult_eq npos prodpos
(take p,
assume primep,
decidable.by_cases
(assume pprimefactors : p ∈ prime_factors n,
eq.symm (mult_prod_pow_of_mem primep primefactors (λ p, mult p n) pprimefactors))
(assume pnprimefactors : p ∉ prime_factors n,
have ¬ p ∣ n, from assume H, pnprimefactors (mem_prime_factors npos primep H),
have mult p n = 0, from mult_eq_zero_of_not_dvd this,
by rewrite [this, mult_prod_pow_of_not_mem primep primefactors _ pnprimefactors]))
end nat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.