text
stringlengths 0
3.34M
|
---|
#' Compute empirical cumulative distribution
#'
#' The empirical cumulative distribution function (ECDF) provides an alternative
#' visualisation of distribution. Compared to other visualisations that rely on
#' density (like [geom_histogram()]), the ECDF doesn't require any
#' tuning parameters and handles both continuous and categorical variables.
#' The downside is that it requires more training to accurately interpret,
#' and the underlying visual tasks are somewhat more challenging.
#'
#' The statistic relies on the aesthetics assignment to guess which variable to
#' use as the input and which to use as the output. Either x or y must be provided
#' and one of them must be unused. The ECDF will be calculated on the given aesthetic
#' and will be output on the unused one.
#'
#' @inheritParams layer
#' @inheritParams geom_point
#' @param na.rm If `FALSE` (the default), removes missing values with
#' a warning. If `TRUE` silently removes missing values.
#' @param n if NULL, do not interpolate. If not NULL, this is the number
#' of points to interpolate with.
#' @param pad If `TRUE`, pad the ecdf with additional points (-Inf, 0)
#' and (Inf, 1)
#' @section Computed variables:
#' \describe{
#' \item{y}{cumulative density corresponding x}
#' }
#' @export
#' @examples
#' df <- data.frame(
#' x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),
#' g = gl(2, 100)
#' )
#' ggplot(df, aes(x)) +
#' stat_ecdf(geom = "step")
#'
#' # Don't go to positive/negative infinity
#' ggplot(df, aes(x)) +
#' stat_ecdf(geom = "step", pad = FALSE)
#'
#' # Multiple ECDFs
#' ggplot(df, aes(x, colour = g)) +
#' stat_ecdf()
stat_ecdf <- function(mapping = NULL, data = NULL,
geom = "step", position = "identity",
...,
n = NULL,
pad = TRUE,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = StatEcdf,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
n = n,
pad = pad,
na.rm = na.rm,
...
)
)
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
StatEcdf <- ggproto("StatEcdf", Stat,
required_aes = c("x|y"),
default_aes = aes(y = after_stat(y)),
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, main_is_orthogonal = FALSE, main_is_continuous = TRUE)
has_x <- !(is.null(data$x) && is.null(params$x))
has_y <- !(is.null(data$y) && is.null(params$y))
if (!has_x && !has_y) {
abort("stat_ecdf() requires an x or y aesthetic.")
}
params
},
compute_group = function(data, scales, n = NULL, pad = TRUE, flipped_aes = FALSE) {
data <- flip_data(data, flipped_aes)
# If n is NULL, use raw values; otherwise interpolate
if (is.null(n)) {
x <- unique(data$x)
} else {
x <- seq(min(data$x), max(data$x), length.out = n)
}
if (pad) {
x <- c(-Inf, x, Inf)
}
data_ecdf <- ecdf(data$x)(x)
df_ecdf <- new_data_frame(list(x = x, y = data_ecdf), n = length(x))
df_ecdf$flipped_aes <- flipped_aes
flip_data(df_ecdf, flipped_aes)
}
)
|
State Before: ss : List String
x✝ : List Char
⊢ List.foldl (fun x x_1 => x ++ x_1) { data := x✝ } [] = { data := x✝ ++ List.join (List.map data []) } State After: no goals Tactic: simp State Before: ss✝ : List String
s : List Char
ss : List String
x✝ : List Char
⊢ { data := x✝ ++ s ++ List.join (List.map data ss) } =
{ data := x✝ ++ List.join (List.map data ({ data := s } :: ss)) } State After: no goals Tactic: simp |
(*
File: AllLambda.thy
Time-stamp: <2016-01-06T17:58:00Z>
Author: JRF
Web: http://jrf.cocolog-nifty.com/software/2016/01/post.html
Logic Image: Logics_ZF (of Isabelle2020)
*)
theory AllLambda
imports dB dBeta SndLAlpha SndLBeta Length FNumber FinBndEx
begin
lemma LAlpha3_iff_LAlpha2:
assumes infv: "Infinite(LVariable)"
shows "LAlpha3(M, N) <-> <M, N>: LAlpha2"
apply (rule iff_trans [OF LAlpha3_iff_LAlpha
infv [THEN LAlpha2_iff_LAlpha, THEN iff_sym]])
done
end
|
Formal statement is: lemma coeffs_reflect_poly [code abstract]: "coeffs (reflect_poly p) = rev (dropWhile ((=) 0) (coeffs p))" Informal statement is: The coefficients of the polynomial $p$ are the same as the coefficients of the polynomial $p$ with the leading zeros removed. |
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
⊢ 𝓝ˢ (Ici a) = 𝓝 a ⊔ 𝓟 (Ioi a)
[PROOFSTEP]
rw [← Ioi_insert, nhdsSet_insert, nhdsSet_Ioi]
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : a < b
⊢ 𝓝ˢ (Ico a b) = 𝓝 a ⊔ 𝓟 (Ioo a b)
[PROOFSTEP]
rw [← Ioo_insert_left h, nhdsSet_insert, nhdsSet_Ioo]
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : a < b
⊢ 𝓝ˢ (Ioc a b) = 𝓝 b ⊔ 𝓟 (Ioo a b)
[PROOFSTEP]
rw [← Ioo_insert_right h, nhdsSet_insert, nhdsSet_Ioo]
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : a ≤ b
⊢ 𝓝ˢ (Icc a b) = 𝓝 a ⊔ 𝓝 b ⊔ 𝓟 (Ioo a b)
[PROOFSTEP]
rcases h.eq_or_lt with rfl | hlt
[GOAL]
case inl
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a c d : α
h : a ≤ a
⊢ 𝓝ˢ (Icc a a) = 𝓝 a ⊔ 𝓝 a ⊔ 𝓟 (Ioo a a)
[PROOFSTEP]
simp
[GOAL]
case inr
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : a ≤ b
hlt : a < b
⊢ 𝓝ˢ (Icc a b) = 𝓝 a ⊔ 𝓝 b ⊔ 𝓟 (Ioo a b)
[PROOFSTEP]
rw [← Ioc_insert_left h, nhdsSet_insert, nhdsSet_Ioc hlt, sup_assoc]
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
⊢ Ioi a ∈ 𝓝ˢ (Ici b) ↔ a < b
[PROOFSTEP]
rw [isOpen_Ioi.mem_nhdsSet, Ici_subset_Ioi]
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : b ≤ c
⊢ Iio c ∈ 𝓝ˢ (Iio b)
[PROOFSTEP]
simpa
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderClosedTopology α
a b c d : α
h : a ≤ b
⊢ Ioi a ∈ 𝓝ˢ (Ioi b)
[PROOFSTEP]
simpa
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderTopology α
a : α
h : Nonempty ↑(Ioi a)
⊢ HasBasis (𝓝ˢ (Iic a)) (fun x => a < x) Iio
[PROOFSTEP]
refine ⟨fun s ↦ ⟨fun hs ↦ ?_, fun ⟨b, hab, hb⟩ ↦ mem_of_superset (Iio_mem_nhdsSet_Iic hab) hb⟩⟩
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderTopology α
a : α
h : Nonempty ↑(Ioi a)
s : Set α
hs : s ∈ 𝓝ˢ (Iic a)
⊢ ∃ i, a < i ∧ Iio i ⊆ s
[PROOFSTEP]
rw [nhdsSet_Iic, mem_sup, mem_principal] at hs
[GOAL]
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderTopology α
a : α
h : Nonempty ↑(Ioi a)
s : Set α
hs : s ∈ 𝓝 a ∧ Iio a ⊆ s
⊢ ∃ i, a < i ∧ Iio i ⊆ s
[PROOFSTEP]
rcases exists_Ico_subset_of_mem_nhds hs.1 (Set.nonempty_coe_sort.1 h) with ⟨b, hab, hbs⟩
[GOAL]
case intro.intro
α : Type u_1
inst✝² : LinearOrder α
inst✝¹ : TopologicalSpace α
inst✝ : OrderTopology α
a : α
h : Nonempty ↑(Ioi a)
s : Set α
hs : s ∈ 𝓝 a ∧ Iio a ⊆ s
b : α
hab : a < b
hbs : Ico a b ⊆ s
⊢ ∃ i, a < i ∧ Iio i ⊆ s
[PROOFSTEP]
exact ⟨b, hab, Iio_subset_Iio_union_Ico.trans (union_subset hs.2 hbs)⟩
[GOAL]
α : Type u_1
inst✝³ : LinearOrder α
inst✝² : TopologicalSpace α
inst✝¹ : OrderTopology α
a : α
inst✝ : NeBot (𝓝[Ioi a] a)
⊢ HasBasis (𝓝ˢ (Iic a)) (fun x => a < x) Iic
[PROOFSTEP]
have : Nonempty (Ioi a) := (Filter.nonempty_of_mem (self_mem_nhdsWithin : Ioi a ∈ 𝓝[>] a)).to_subtype
[GOAL]
α : Type u_1
inst✝³ : LinearOrder α
inst✝² : TopologicalSpace α
inst✝¹ : OrderTopology α
a : α
inst✝ : NeBot (𝓝[Ioi a] a)
this : Nonempty ↑(Ioi a)
⊢ HasBasis (𝓝ˢ (Iic a)) (fun x => a < x) Iic
[PROOFSTEP]
refine (hasBasis_nhdsSet_Iic_Iio _).to_hasBasis (fun c hc ↦ ?_) (fun _ h ↦ ⟨_, h, Iio_subset_Iic_self⟩)
[GOAL]
α : Type u_1
inst✝³ : LinearOrder α
inst✝² : TopologicalSpace α
inst✝¹ : OrderTopology α
a : α
inst✝ : NeBot (𝓝[Ioi a] a)
this : Nonempty ↑(Ioi a)
c : α
hc : a < c
⊢ ∃ i', a < i' ∧ Iic i' ⊆ Iio c
[PROOFSTEP]
simpa only [Iic_subset_Iio] using (Filter.nonempty_of_mem <| Ioo_mem_nhdsWithin_Ioi' hc)
|
lemma to_fract_1 [simp]: "to_fract 1 = 1" |
open Classical
inductive Cnat where
| zero : Cnat
| succ : Cnat → Cnat
def add (a b : Cnat) : Cnat :=
match a with
| Cnat.zero => b
| Cnat.succ c => Cnat.succ (add c b)
theorem add_zero_right (x : Cnat) : add x Cnat.zero = x := by
induction x
case zero => rfl
case succ x' ih => simp [ih, add]
theorem add_suc_right (x y : Cnat) : add x (Cnat.succ y) = Cnat.succ (add x y) := by
induction x
case zero => rfl
case succ x' ih => simp [ih, add]
theorem add_comm (x y : Cnat) : add x y = add y x := by
induction x
case zero => simp [add, add_zero_right]
case succ x' ih => simp [ih, add, add_suc_right]
theorem add_assoc (x y z : Cnat) : add (add x y) z = add x (add y z) := by
induction x
case zero => simp [add]
case succ x' ih => simp [ih, add]
def mul (a b : Cnat) : Cnat :=
match a with
| Cnat.zero => Cnat.zero
| Cnat.succ c => add b (mul c b)
theorem mul_zero_right (x : Cnat) : mul x Cnat.zero = Cnat.zero := by
induction x
case zero => rfl
case succ x' ih => simp [ih, mul, add]
theorem mul_suc_right (x y : Cnat) : mul x (Cnat.succ y) = add x (mul x y) := by
induction x
case zero => simp [mul, add]
case succ x' ih => simp [mul, add, ih, <-add_assoc, add_comm]
theorem mul_comm (x y : Cnat) : mul x y = mul y x := by
induction x
case zero => simp [mul, mul_zero_right]
case succ x' ih => simp [mul, mul_suc_right, ih]
theorem distrib (x y z : Cnat) : mul x (add y z) = add (mul x y) (mul x z) := by
induction x
case zero => simp [mul, add]
case succ x' ih => rw [mul, mul, mul, add_assoc, ih, add_assoc,
<- add_assoc (mul x' y), <- add_assoc z, add_comm z]
theorem mul_assoc (x y z : Cnat) : mul (mul x y) z = mul x (mul y z) := by
induction x
case zero => simp [mul]
case succ x' ih => simp [mul, mul_comm, distrib, <- ih]
def lt (a b : Cnat) : Prop :=
match b with
| Cnat.zero => False
| Cnat.succ d => match a with
| Cnat.zero => True
| Cnat.succ c => lt c d
theorem lt_not_ref (x : Cnat) : ¬ lt x x := by
induction x
case zero => simp [lt]
case succ x' ih => simp [lt, ih]
theorem lt_not_symm (a b : Cnat) : lt a b → ¬ lt b a := by
induction a generalizing b
case zero => simp [lt]
case succ a' ih => match b with
| Cnat.zero => simp [lt]
| Cnat.succ b' => simp [lt]; apply ih
theorem lt_trans (a b c : Cnat) : lt a b ∧ lt b c → lt a c := by
induction c generalizing a b
case zero => simp [lt]
case succ c' ih => match a with
| Cnat.zero => simp [lt]
| Cnat.succ a' => match b with
| Cnat.zero => simp [lt]
| Cnat.succ b' => simp [lt]; apply ih
theorem lt_to_sub (a b : Cnat) : lt a b → ∃ c, b = add a c := by
induction a generalizing b
case zero => simp [add]; intro; apply Exists.intro b; rfl
case succ a ih =>
simp [add]
match b with
| Cnat.zero => simp [lt]
| Cnat.succ b' => simp [lt]; apply ih
theorem lt_add_suc (a b : Cnat) : lt a (add a b.succ) := by
induction a generalizing b
case zero => simp [add, lt]
case succ a ih => simp [add, lt]; apply ih
theorem add_cancels_left (a b c : Cnat) : add a b = add a c → b = c := by
induction a generalizing b
case zero => simp [add]; intro h; exact h
case succ a ih => simp [add]; apply ih
theorem add_cancels_right (a b c : Cnat) : add a c = add b c → a = b := by
induction c
case zero => simp [add_zero_right]; intro h; exact h
case succ c ih => simp [add_suc_right]; exact ih
theorem lt_suc (a b : Cnat) (h1: lt a b) : a.succ = b ∨ lt a.succ b := by
let ⟨c, h2⟩ := lt_to_sub a b h1
match c with
| Cnat.zero => {
simp [add_zero_right] at h2; rw [h2] at h1; simp [lt_not_ref] at h1
}
| Cnat.succ c' => match c' with
| Cnat.zero => {
simp [add_suc_right, add_zero_right] at h2
simp [h2]
}
| Cnat.succ c'' => {
apply Or.inr
rw [add_suc_right] at h2
rw [h2]
simp [lt]
exact lt_add_suc _ _
}
theorem division_theorem (m n : Cnat) (h1: lt Cnat.zero n) :
∃ q r, lt r n ∧ m = add (mul q n) r := by
induction m
case zero => {
apply Exists.intro Cnat.zero
apply Exists.intro Cnat.zero
simp [h1, mul, add]
}
case succ m ih => {
let ⟨q, r, h2, h3⟩ := ih
apply Or.elim (em (r.succ = n))
case left => {
intro h4
apply Exists.intro q.succ
apply Exists.intro Cnat.zero
simp [h1, add_zero_right, h3, mul]
rw [<- h4, add, add_comm]
}
case right => {
intro h5
apply Exists.intro q
apply Exists.intro r.succ
apply And.intro
case left => {
apply Or.elim (lt_suc r n h2)
case left => simp [h5]
case right => intro h6; exact h6
}
case right => {
rw [h3]
simp [add_suc_right]
}
}
}
def is_prime (p : Cnat) : Prop := sorry
|
-- Igualdad_de_bloques_de_una_particion_cuando_tienen_elementos_comunes.lean
-- Igualdad de bloques de una partición cuando tienen elementos comunes
-- José A. Alonso Jiménez
-- Sevilla, 30 de septiembre de 2021
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Este ejercicio es el primero de una serie cuyo objetivo es demostrar
-- que el tipo de las particiones de un conjunto `X` es isomorfo al tipo
-- de las relaciones de equivalencia sobre `X`. El desarrollo de dicha
-- serie está basado en la [cuarta parte](https://bit.ly/3AQWY7o) de la
-- primera sesión del curso de Kevin Buzzard
-- "Formalising mathematics: workshop 1 — logic, sets, functions,
-- relations" (https://bit.ly/3kJo231).
--
-- Una [partición](https://bit.ly/3uplABS) de un conjunto A es un conjunto
-- de subconjuntos no vacíos de A tal que todo elemento de A está
-- exactamente en uno de dichos subconjuntos. Es decir, una famila de
-- conjuntos C es una partición de A si se verifican las siguientes
-- condiciones:
-- + Los conjuntos de C son no vacíos; es decir,
-- ∀ X ∈ C, X ≠ ∅.
-- + Los conjuntos de C recubren A; es decir,
-- ∀ a ∈ A, ∃ X ∈ C, a ∈ X
-- + Los conjuntos de C son disjuntos entre sí; es decir,
-- ∀ X Y ∈ C, X ∩ Y ≠ ∅ → X = Y
--
-- En Lean, se puede definir el tipo de las particiones sobre un tipo A
-- mediante una estructura con 4 campos:
-- + Un conjunto de subconjuntos de A llamados los bloques de la partición.
-- + Una prueba de que los bloques son no vacíos.
-- + Una prueba de que cada término de tipo A está en uno de los bloques.
-- + Una prueba de que dos bloques con intersección no vacía son iguales.
-- Su definición es
-- @[ext] structure particion (A : Type) :=
-- (Bloques : set (set A))
-- (Hno_vacios : ∀ X ∈ Bloques, (X : set A).nonempty)
-- (Hrecubren : ∀ a, ∃ X ∈ Bloques, a ∈ X)
-- (Hdisjuntos : ∀ X Y ∈ Bloques, (X ∩ Y : set A).nonempty → X = Y)
--
-- Con la definición anterior,
-- + `P : particion A` expresa que `P` es una partición de `A`.
-- + `Bloques P` es el conjunto de los bloque de P.
-- + `Hno_vacios P` prueba que los bloques de `P` son no vacíos.
-- + `Hrecubren P` prueba que los bloque de `P` recubren a `A`.
-- + `Hdisjuntos p` prueba que los bloques de `P` son disjuntos entre sí
--
-- Demostrar que si dos bloques de una partición tienen un elemento en
-- común, entonces son iguales.
-- ---------------------------------------------------------------------
import tactic
@[ext] structure particion (A : Type) :=
(Bloques : set (set A))
(Hno_vacios : ∀ X ∈ Bloques, (X : set A).nonempty)
(Hrecubren : ∀ a, ∃ X ∈ Bloques, a ∈ X)
(Hdisjuntos : ∀ X Y ∈ Bloques, (X ∩ Y : set A).nonempty → X = Y)
namespace particion
variable {A : Type}
variable {P : particion A}
variables {X Y : set A}
-- 1ª demostración
example
(hX : X ∈ Bloques P)
(hY : Y ∈ Bloques P)
{a : A}
(haX : a ∈ X)
(haY : a ∈ Y)
: X = Y :=
begin
apply P.Hdisjuntos,
{ exact hX, },
{ exact hY, },
{ rw set.nonempty_def,
use a,
split,
{ exact haX, },
{ exact haY, }},
end
-- 2ª demostración
example
(hX : X ∈ Bloques P)
(hY : Y ∈ Bloques P)
{a : A}
(haX : a ∈ X)
(haY : a ∈ Y)
: X = Y :=
begin
apply P.Hdisjuntos,
{ exact hX, },
{ exact hY, },
{ use a,
exact ⟨haX, haY⟩, },
end
-- 3ª demostración
example
(hX : X ∈ Bloques P)
(hY : Y ∈ Bloques P)
{a : A}
(haX : a ∈ X)
(haY : a ∈ Y)
: X = Y :=
begin
apply P.Hdisjuntos,
{ exact hX, },
{ exact hY, },
{ exact ⟨a, haX, haY⟩, },
end
-- 4ª demostración
lemma iguales_si_comun
(hX : X ∈ Bloques P)
(hY : Y ∈ Bloques P)
{a : A}
(haX : a ∈ X)
(haY : a ∈ Y)
: X = Y :=
Hdisjuntos P X hX Y hY ⟨a, haX, haY⟩
end particion
|
theorem impNot {p q : Prop} : p → ¬ q ↔ ¬ (p ∧ q) :=
⟨ λ hpq h => hpq h.1 h.2, λ h hp hq => h <| And.intro hp hq ⟩
theorem Exists.impNot {p q : α → Prop} : (∃ x, p x → ¬ q x) ↔ ∃ x, ¬ (p x ∧ q x) := by
apply Iff.intro
intro h
cases h with | intro x hx =>
{ exact ⟨ x, λ hs => hx hs.1 hs.2 ⟩ }
intro h
cases h with | intro x hx =>
{ exact ⟨ x, λ hpx hqx => hx <| And.intro hpx hqx ⟩ }
namespace Classical
theorem contrapositive {p q : Prop} : (¬ q → ¬ p) → p → q :=
λ hqp hp => match em q with
| Or.inl h => h
| Or.inr h => False.elim <| hqp h hp
theorem notNot {p : Prop} : ¬ ¬ p ↔ p := by
apply Iff.intro
{ intro hp; cases em p with
| inl => assumption
| inr h => exact False.elim <| hp h }
{ exact λ hp hnp => False.elim <| hnp hp }
theorem notForall {p : α → Prop} : (¬ ∀ x, p x) → ∃ x, ¬ p x := by
{ apply contrapositive; intro hx; rw [notNot]; intro x;
cases em (p x); { assumption }
{ apply False.elim <| hx <| Exists.intro x _; assumption } }
theorem notAnd {p q : Prop} : p ∧ ¬ q ↔ ¬ (p → q) := by
apply Iff.intro
{ exact λ h himp => h.2 <| himp h.1 }
{ intro h; apply And.intro;
{ revert h; apply contrapositive; rw [notNot];
exact λ hnp hp => False.elim <| hnp hp }
{ exact λ hq => h <| λ _ => hq } }
theorem Exists.notAnd {p q : α → Prop} :
(∃ x, p x ∧ ¬ q x) ↔ ∃ x, ¬ (p x → q x) := by
apply Iff.intro
{ intro h;
let ⟨ x, ⟨ hp, hnq ⟩ ⟩ := h;
exact Exists.intro x λ h => hnq <| h hp }
{ intro h;
let ⟨ x, hx ⟩ := h;
apply Exists.intro x;
apply And.intro;
{ revert hx; apply contrapositive;
exact λ hpx hpq => hpq λ hp => False.elim <| hpx hp }
{ intro foo;
apply hx;
intro bar;
assumption; } }
end Classical |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Packed.Vector
-- Copyright : (c) Alberto Ruiz 2009
-- License : GPL
--
-- Maintainer : Alberto Ruiz <[email protected]>
-- Stability : provisional
--
-- Random vectors and matrices.
--
-----------------------------------------------------------------------------
module Data.Packed.Random (
Seed,
RandDist(..),
randomVector,
gaussianSample,
uniformSample
) where
import Numeric.GSL.Vector
import Data.Packed
import Numeric.ContainerBoot
import Numeric.LinearAlgebra.Algorithms
type Seed = Int
-- | Obtains a matrix whose rows are pseudorandom samples from a multivariate
-- Gaussian distribution.
gaussianSample :: Seed
-> Int -- ^ number of rows
-> Vector Double -- ^ mean vector
-> Matrix Double -- ^ covariance matrix
-> Matrix Double -- ^ result
gaussianSample seed n med cov = m where
c = dim med
meds = konst 1 n `outer` med
rs = reshape c $ randomVector seed Gaussian (c * n)
m = rs `mXm` cholSH cov `add` meds
-- | Obtains a matrix whose rows are pseudorandom samples from a multivariate
-- uniform distribution.
uniformSample :: Seed
-> Int -- ^ number of rows
-> [(Double,Double)] -- ^ ranges for each column
-> Matrix Double -- ^ result
uniformSample seed n rgs = m where
(as,bs) = unzip rgs
a = fromList as
cs = zipWith subtract as bs
d = dim a
dat = toRows $ reshape n $ randomVector seed Uniform (n*d)
am = konst 1 n `outer` a
m = fromColumns (zipWith scale cs dat) `add` am
|
(* Check typing of replaced objects in change - even though the failure
was already a proper error message (but with a helpless content) *)
Class foo {A} {a : A} := { bar := a; baz : bar = bar }.
Arguments bar {_} _ {_}.
Instance: forall A a, @foo A a.
intros; constructor.
abstract reflexivity.
Defined.
Goal @bar _ Set _ = (@bar _ (fun _ : Set => Set) _) nat.
Proof.
Fail change (bar (fun _ : Set => Set)) with (bar Set).
|
lemma csqrt_ii [simp]: "csqrt \<i> = (1 + \<i>) / sqrt 2" |
# Copyright (C) 2019-2020 Zilliz. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
from enum import Enum
import numpy as np
class FieldDecayFunction(Enum):
LINEAR = 'linear'
def decay_helper(decay_function_mode: FieldDecayFunction):
def linear(number, max, min):
return list(np.linspace(max, min, number))
helper = {FieldDecayFunction.LINEAR: linear}
return helper[decay_function_mode]
|
/*
* gsl_headers.h
* Pi4U
*
* Created by Panagiotis Hadjidoukas on 1/1/14.
* Copyright 2014 ETH Zurich. All rights reserved.
*
*/
#ifndef _GSL_HEADERS_
#define _GSL_HEADERS_ 1
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_roots.h>
/* NDL */
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sort_vector.h>
#endif
|
{-# OPTIONS --rewriting #-}
module GSeTT.GSeTT where
open import GSeTT.Syntax
open import GSeTT.Rules
import GSeTT.CwF-structure
import GSeTT.Dec-Type-Checking
import GSeTT.Uniqueness-Derivations
open import GSeTT.Typed-Syntax
|
function hfssSetSolveInside(fid, Object, solveInsideFlag)
fprintf(fid, 'oEditor.ChangeProperty _\n');
fprintf(fid, '\tArray("NAME:AllTabs", _\n');
fprintf(fid, '\t\tArray("NAME:Geometry3DAttributeTab", _\n');
fprintf(fid, '\t\t\tArray("NAME:PropServers", "%s"), _\n', Object);
fprintf(fid, '\t\t\tArray("NAME:ChangedProps", _\n');
if (solveInsideFlag)
fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", true) _\n');
else
fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", false) _\n');
end
fprintf(fid, '\t\t\t\t) _\n');
fprintf(fid, '\t\t\t) _\n');
fprintf(fid, '\t\t) \n'); |
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
! This file was ported from Lean 3 source module field_theory.is_alg_closed.basic
! leanprover-community/mathlib commit 3e00d81bdcbf77c8188bbd18f5524ddc3ed8cac6
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.FieldTheory.PerfectClosure
import Mathbin.FieldTheory.Separable
import Mathbin.RingTheory.Adjoin.Field
import Mathbin.RingTheory.Localization.Integral
/-!
# Algebraically Closed Field
In this file we define the typeclass for algebraically closed fields and algebraic closures,
and prove some of their properties.
## Main Definitions
- `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every
polynomial in `k` splits.
- `is_alg_closure R K` is the typeclass saying `K` is an algebraic closure of `R`, where `R` is a
commutative ring. This means that the map from `R` to `K` is injective, and `K` is
algebraically closed and algebraic over `R`
- `is_alg_closed.lift` is a map from an algebraic extension `L` of `R`, into any algebraically
closed extension of `R`.
- `is_alg_closure.equiv` is a proof that any two algebraic closures of the
same field are isomorphic.
## Tags
algebraic closure, algebraically closed
-/
universe u v w
open Classical BigOperators Polynomial
open Polynomial
variable (k : Type u) [Field k]
/-- Typeclass for algebraically closed fields.
To show `polynomial.splits p f` for an arbitrary ring homomorphism `f`,
see `is_alg_closed.splits_codomain` and `is_alg_closed.splits_domain`.
-/
class IsAlgClosed : Prop where
Splits : ∀ p : k[X], p.Splits <| RingHom.id k
#align is_alg_closed IsAlgClosed
/-- Every polynomial splits in the field extension `f : K →+* k` if `k` is algebraically closed.
See also `is_alg_closed.splits_domain` for the case where `K` is algebraically closed.
-/
theorem IsAlgClosed.splits_codomain {k K : Type _} [Field k] [IsAlgClosed k] [Field K] {f : K →+* k}
(p : K[X]) : p.Splits f := by
convert IsAlgClosed.splits (p.map f)
simp [splits_map_iff]
#align is_alg_closed.splits_codomain IsAlgClosed.splits_codomain
/-- Every polynomial splits in the field extension `f : K →+* k` if `K` is algebraically closed.
See also `is_alg_closed.splits_codomain` for the case where `k` is algebraically closed.
-/
theorem IsAlgClosed.splits_domain {k K : Type _} [Field k] [IsAlgClosed k] [Field K] {f : k →+* K}
(p : k[X]) : p.Splits f :=
Polynomial.splits_of_splits_id _ <| IsAlgClosed.splits _
#align is_alg_closed.splits_domain IsAlgClosed.splits_domain
namespace IsAlgClosed
variable {k}
theorem exists_root [IsAlgClosed k] (p : k[X]) (hp : p.degree ≠ 0) : ∃ x, IsRoot p x :=
exists_root_of_splits _ (IsAlgClosed.splits p) hp
#align is_alg_closed.exists_root IsAlgClosed.exists_root
theorem exists_pow_nat_eq [IsAlgClosed k] (x : k) {n : ℕ} (hn : 0 < n) : ∃ z, z ^ n = x :=
by
rcases exists_root (X ^ n - C x) _ with ⟨z, hz⟩; swap
· rw [degree_X_pow_sub_C hn x]
exact ne_of_gt (WithBot.coe_lt_coe.2 hn)
use z
simp only [eval_C, eval_X, eval_pow, eval_sub, is_root.def] at hz
exact sub_eq_zero.1 hz
#align is_alg_closed.exists_pow_nat_eq IsAlgClosed.exists_pow_nat_eq
theorem exists_eq_mul_self [IsAlgClosed k] (x : k) : ∃ z, x = z * z :=
by
rcases exists_pow_nat_eq x zero_lt_two with ⟨z, rfl⟩
exact ⟨z, sq z⟩
#align is_alg_closed.exists_eq_mul_self IsAlgClosed.exists_eq_mul_self
theorem roots_eq_zero_iff [IsAlgClosed k] {p : k[X]} : p.roots = 0 ↔ p = Polynomial.C (p.coeff 0) :=
by
refine' ⟨fun h => _, fun hp => by rw [hp, roots_C]⟩
cases' le_or_lt (degree p) 0 with hd hd
· exact eq_C_of_degree_le_zero hd
· obtain ⟨z, hz⟩ := IsAlgClosed.exists_root p hd.ne'
rw [← mem_roots (ne_zero_of_degree_gt hd), h] at hz
simpa using hz
#align is_alg_closed.roots_eq_zero_iff IsAlgClosed.roots_eq_zero_iff
theorem exists_eval₂_eq_zero_of_injective {R : Type _} [Ring R] [IsAlgClosed k] (f : R →+* k)
(hf : Function.Injective f) (p : R[X]) (hp : p.degree ≠ 0) : ∃ x, p.eval₂ f x = 0 :=
let ⟨x, hx⟩ := exists_root (p.map f) (by rwa [degree_map_eq_of_injective hf])
⟨x, by rwa [eval₂_eq_eval_map, ← is_root]⟩
#align is_alg_closed.exists_eval₂_eq_zero_of_injective IsAlgClosed.exists_eval₂_eq_zero_of_injective
theorem exists_eval₂_eq_zero {R : Type _} [Field R] [IsAlgClosed k] (f : R →+* k) (p : R[X])
(hp : p.degree ≠ 0) : ∃ x, p.eval₂ f x = 0 :=
exists_eval₂_eq_zero_of_injective f f.Injective p hp
#align is_alg_closed.exists_eval₂_eq_zero IsAlgClosed.exists_eval₂_eq_zero
variable (k)
theorem exists_aeval_eq_zero_of_injective {R : Type _} [CommRing R] [IsAlgClosed k] [Algebra R k]
(hinj : Function.Injective (algebraMap R k)) (p : R[X]) (hp : p.degree ≠ 0) :
∃ x : k, aeval x p = 0 :=
exists_eval₂_eq_zero_of_injective (algebraMap R k) hinj p hp
#align is_alg_closed.exists_aeval_eq_zero_of_injective IsAlgClosed.exists_aeval_eq_zero_of_injective
theorem exists_aeval_eq_zero {R : Type _} [Field R] [IsAlgClosed k] [Algebra R k] (p : R[X])
(hp : p.degree ≠ 0) : ∃ x : k, aeval x p = 0 :=
exists_eval₂_eq_zero (algebraMap R k) p hp
#align is_alg_closed.exists_aeval_eq_zero IsAlgClosed.exists_aeval_eq_zero
theorem of_exists_root (H : ∀ p : k[X], p.Monic → Irreducible p → ∃ x, p.eval x = 0) :
IsAlgClosed k :=
⟨fun p =>
Or.inr fun q hq hqp =>
have : Irreducible (q * C (leadingCoeff q)⁻¹) :=
by
rw [← coe_norm_unit_of_ne_zero hq.ne_zero]
exact (associated_normalize _).Irreducible hq
let ⟨x, hx⟩ := H (q * C (leadingCoeff q)⁻¹) (monic_mul_leadingCoeff_inv hq.NeZero) this
degree_mul_leadingCoeff_inv q hq.NeZero ▸ degree_eq_one_of_irreducible_of_root this hx⟩
#align is_alg_closed.of_exists_root IsAlgClosed.of_exists_root
theorem degree_eq_one_of_irreducible [IsAlgClosed k] {p : k[X]} (hp : Irreducible p) :
p.degree = 1 :=
degree_eq_one_of_irreducible_of_splits hp (IsAlgClosed.splits_codomain _)
#align is_alg_closed.degree_eq_one_of_irreducible IsAlgClosed.degree_eq_one_of_irreducible
theorem algebraMap_surjective_of_isIntegral {k K : Type _} [Field k] [Ring K] [IsDomain K]
[hk : IsAlgClosed k] [Algebra k K] (hf : Algebra.IsIntegral k K) :
Function.Surjective (algebraMap k K) :=
by
refine' fun x => ⟨-(minpoly k x).coeff 0, _⟩
have hq : (minpoly k x).leadingCoeff = 1 := minpoly.monic (hf x)
have h : (minpoly k x).degree = 1 := degree_eq_one_of_irreducible k (minpoly.irreducible (hf x))
have : aeval x (minpoly k x) = 0 := minpoly.aeval k x
rw [eq_X_add_C_of_degree_eq_one h, hq, C_1, one_mul, aeval_add, aeval_X, aeval_C,
add_eq_zero_iff_eq_neg] at this
exact (RingHom.map_neg (algebraMap k K) ((minpoly k x).coeff 0)).symm ▸ this.symm
#align is_alg_closed.algebra_map_surjective_of_is_integral IsAlgClosed.algebraMap_surjective_of_isIntegral
theorem algebra_map_surjective_of_is_integral' {k K : Type _} [Field k] [CommRing K] [IsDomain K]
[hk : IsAlgClosed k] (f : k →+* K) (hf : f.IsIntegral) : Function.Surjective f :=
@algebraMap_surjective_of_isIntegral k K _ _ _ _ f.toAlgebra hf
#align is_alg_closed.algebra_map_surjective_of_is_integral' IsAlgClosed.algebra_map_surjective_of_is_integral'
theorem algebraMap_surjective_of_isAlgebraic {k K : Type _} [Field k] [Ring K] [IsDomain K]
[hk : IsAlgClosed k] [Algebra k K] (hf : Algebra.IsAlgebraic k K) :
Function.Surjective (algebraMap k K) :=
algebraMap_surjective_of_isIntegral (Algebra.isAlgebraic_iff_isIntegral.mp hf)
#align is_alg_closed.algebra_map_surjective_of_is_algebraic IsAlgClosed.algebraMap_surjective_of_isAlgebraic
end IsAlgClosed
/-- Typeclass for an extension being an algebraic closure. -/
class IsAlgClosure (R : Type u) (K : Type v) [CommRing R] [Field K] [Algebra R K]
[NoZeroSMulDivisors R K] : Prop where
alg_closed : IsAlgClosed K
algebraic : Algebra.IsAlgebraic R K
#align is_alg_closure IsAlgClosure
theorem isAlgClosure_iff (K : Type v) [Field K] [Algebra k K] :
IsAlgClosure k K ↔ IsAlgClosed K ∧ Algebra.IsAlgebraic k K :=
⟨fun h => ⟨h.1, h.2⟩, fun h => ⟨h.1, h.2⟩⟩
#align is_alg_closure_iff isAlgClosure_iff
namespace lift
/- In this section, the homomorphism from any algebraic extension into an algebraically
closed extension is proven to exist. The assumption that M is algebraically closed could probably
easily be switched to an assumption that M contains all the roots of polynomials in K -/
variable {K : Type u} {L : Type v} {M : Type w} [Field K] [Field L] [Algebra K L] [Field M]
[Algebra K M] [IsAlgClosed M] (hL : Algebra.IsAlgebraic K L)
variable (K L M)
include hL
open Subalgebra AlgHom Function
/-- This structure is used to prove the existence of a homomorphism from any algebraic extension
into an algebraic closure -/
structure SubfieldWithHom where
carrier : Subalgebra K L
emb : carrier →ₐ[K] M
#align lift.subfield_with_hom lift.SubfieldWithHom
variable {K L M hL}
namespace SubfieldWithHom
variable {E₁ E₂ E₃ : SubfieldWithHom K L M hL}
instance : LE (SubfieldWithHom K L M hL)
where le E₁ E₂ := ∃ h : E₁.carrier ≤ E₂.carrier, ∀ x, E₂.emb (inclusion h x) = E₁.emb x
noncomputable instance : Inhabited (SubfieldWithHom K L M hL) :=
⟨{ carrier := ⊥
emb := (Algebra.ofId K M).comp (Algebra.botEquiv K L).toAlgHom }⟩
theorem le_def : E₁ ≤ E₂ ↔ ∃ h : E₁.carrier ≤ E₂.carrier, ∀ x, E₂.emb (inclusion h x) = E₁.emb x :=
Iff.rfl
#align lift.subfield_with_hom.le_def lift.SubfieldWithHom.le_def
theorem compat (h : E₁ ≤ E₂) : ∀ x, E₂.emb (inclusion h.fst x) = E₁.emb x :=
by
rw [le_def] at h
cases h
assumption
#align lift.subfield_with_hom.compat lift.SubfieldWithHom.compat
instance : Preorder (SubfieldWithHom K L M hL)
where
le := (· ≤ ·)
le_refl E := ⟨le_rfl, by simp⟩
le_trans E₁ E₂ E₃ h₁₂ h₂₃ :=
⟨le_trans h₁₂.fst h₂₃.fst, fun _ => by
erw [← inclusion_inclusion h₁₂.fst h₂₃.fst, compat, compat]⟩
open Lattice
theorem maximal_subfieldWithHom_chain_bounded (c : Set (SubfieldWithHom K L M hL))
(hc : IsChain (· ≤ ·) c) : ∃ ub : SubfieldWithHom K L M hL, ∀ N, N ∈ c → N ≤ ub :=
if hcn : c.Nonempty then
let ub : SubfieldWithHom K L M hL :=
haveI : Nonempty c := Set.Nonempty.to_subtype hcn
{ carrier := ⨆ i : c, (i : subfield_with_hom K L M hL).carrier
emb :=
Subalgebra.supᵢLift (fun i : c => (i : subfield_with_hom K L M hL).carrier)
(fun i j =>
let ⟨k, hik, hjk⟩ := directedOn_iff_directed.1 hc.directed_on i j
⟨k, hik.fst, hjk.fst⟩)
(fun i => (i : subfield_with_hom K L M hL).emb)
(by
intro i j h
ext x
cases' hc.total i.prop j.prop with hij hji
· simp [← hij.snd x]
·
erw [AlgHom.comp_apply, ← hji.snd (inclusion h x), inclusion_inclusion,
inclusion_self, AlgHom.id_apply x])
_ rfl }
⟨ub, fun N hN =>
⟨(le_supᵢ (fun i : c => (i : SubfieldWithHom K L M hL).carrier) ⟨N, hN⟩ : _),
by
intro x
simp [ub]
rfl⟩⟩
else by
rw [Set.not_nonempty_iff_eq_empty] at hcn
simp [hcn]
#align lift.subfield_with_hom.maximal_subfield_with_hom_chain_bounded lift.SubfieldWithHom.maximal_subfieldWithHom_chain_bounded
variable (hL M)
theorem exists_maximal_subfieldWithHom : ∃ E : SubfieldWithHom K L M hL, ∀ N, E ≤ N → N ≤ E :=
exists_maximal_of_chains_bounded maximal_subfieldWithHom_chain_bounded fun _ _ _ => le_trans
#align lift.subfield_with_hom.exists_maximal_subfield_with_hom lift.SubfieldWithHom.exists_maximal_subfieldWithHom
/-- The maximal `subfield_with_hom`. We later prove that this is equal to `⊤`. -/
noncomputable def maximalSubfieldWithHom : SubfieldWithHom K L M hL :=
Classical.choose (exists_maximal_subfieldWithHom M hL)
#align lift.subfield_with_hom.maximal_subfield_with_hom lift.SubfieldWithHom.maximalSubfieldWithHom
theorem maximalSubfieldWithHom_is_maximal :
∀ N : SubfieldWithHom K L M hL,
maximalSubfieldWithHom M hL ≤ N → N ≤ maximalSubfieldWithHom M hL :=
Classical.choose_spec (exists_maximal_subfieldWithHom M hL)
#align lift.subfield_with_hom.maximal_subfield_with_hom_is_maximal lift.SubfieldWithHom.maximalSubfieldWithHom_is_maximal
theorem maximalSubfieldWithHom_eq_top : (maximalSubfieldWithHom M hL).carrier = ⊤ :=
by
rw [eq_top_iff]
intro x _
let p := minpoly K x
let N : Subalgebra K L := (maximal_subfield_with_hom M hL).carrier
letI : Field N := (Subalgebra.isField_of_algebraic N hL).toField
letI : Algebra N M := (maximal_subfield_with_hom M hL).emb.toRingHom.toAlgebra
cases'
IsAlgClosed.exists_aeval_eq_zero M (minpoly N x)
(ne_of_gt
(minpoly.degree_pos
(isAlgebraic_iff_isIntegral.1 (Algebra.isAlgebraic_of_larger_base _ _ hL x)))) with
y hy
let O : Subalgebra N L := Algebra.adjoin N {(x : L)}
let larger_emb :=
(AdjoinRoot.liftHom (minpoly N x) y hy).comp
(AlgEquiv.adjoinSingletonEquivAdjoinRootMinpoly N x).toAlgHom
have hNO : N ≤ O.restrict_scalars K := by
intro z hz
show algebraMap N L ⟨z, hz⟩ ∈ O
exact O.algebra_map_mem _
let O' : subfield_with_hom K L M hL :=
{ carrier := O.restrict_scalars K
emb := larger_emb.restrict_scalars K }
have hO' : maximal_subfield_with_hom M hL ≤ O' :=
by
refine' ⟨hNO, _⟩
intro z
show O'.emb (algebraMap N O z) = algebraMap N M z
simp only [O', restrict_scalars_apply, AlgHom.commutes]
refine' (maximal_subfield_with_hom_is_maximal M hL O' hO').fst _
exact Algebra.subset_adjoin (Set.mem_singleton x)
#align lift.subfield_with_hom.maximal_subfield_with_hom_eq_top lift.SubfieldWithHom.maximalSubfieldWithHom_eq_top
end SubfieldWithHom
end lift
namespace IsAlgClosed
variable {K : Type u} [Field K] {L : Type v} {M : Type w} [Field L] [Algebra K L] [Field M]
[Algebra K M] [IsAlgClosed M] (hL : Algebra.IsAlgebraic K L)
variable (K L M)
include hL
/-- Less general version of `lift`. -/
private noncomputable irreducible_def lift_aux : L →ₐ[K] M :=
(lift.SubfieldWithHom.maximalSubfieldWithHom M hL).emb.comp <|
Eq.recOn (lift.SubfieldWithHom.maximalSubfieldWithHom_eq_top M hL).symm Algebra.toTop
#align is_alg_closed.lift_aux is_alg_closed.lift_aux
omit hL
variable {R : Type u} [CommRing R]
variable {S : Type v} [CommRing S] [IsDomain S] [Algebra R S] [Algebra R M] [NoZeroSMulDivisors R S]
[NoZeroSMulDivisors R M] (hS : Algebra.IsAlgebraic R S)
variable {M}
include hS
private theorem fraction_ring.is_algebraic :
letI : IsDomain R := (NoZeroSMulDivisors.algebraMap_injective R S).IsDomain _
Algebra.IsAlgebraic (FractionRing R) (FractionRing S) :=
by
intro inst x
exact
(IsFractionRing.isAlgebraic_iff R (FractionRing R) (FractionRing S)).1
((IsFractionRing.isAlgebraic_iff' R S (FractionRing S)).1 hS x)
#align is_alg_closed.fraction_ring.is_algebraic is_alg_closed.fraction_ring.is_algebraic
/-- A (random) homomorphism from an algebraic extension of R into an algebraically
closed extension of R. -/
noncomputable irreducible_def lift : S →ₐ[R] M :=
by
letI : IsDomain R := (NoZeroSMulDivisors.algebraMap_injective R S).IsDomain _
have hfRfS : Algebra.IsAlgebraic (FractionRing R) (FractionRing S) :=
fraction_ring.is_algebraic hS
let f : FractionRing S →ₐ[FractionRing R] M := lift_aux (FractionRing R) (FractionRing S) M hfRfS
exact (f.restrict_scalars R).comp ((Algebra.ofId S (FractionRing S)).restrictScalars R)
#align is_alg_closed.lift IsAlgClosed.lift
omit hS
noncomputable instance (priority := 100) perfectRing (p : ℕ) [Fact p.Prime] [CharP k p]
[IsAlgClosed k] : PerfectRing k p :=
PerfectRing.ofSurjective k p fun x => IsAlgClosed.exists_pow_nat_eq _ <| NeZero.pos p
#align is_alg_closed.perfect_ring IsAlgClosed.perfectRing
/-- Algebraically closed fields are infinite since `Xⁿ⁺¹ - 1` is separable when `#K = n` -/
instance (priority := 500) {K : Type _} [Field K] [IsAlgClosed K] : Infinite K :=
by
apply Infinite.of_not_fintype
intro hfin
set n := Fintype.card K with hn
set f := (X : K[X]) ^ (n + 1) - 1 with hf
have hfsep : separable f := separable_X_pow_sub_C 1 (by simp) one_ne_zero
apply Nat.not_succ_le_self (Fintype.card K)
have hroot : n.succ = Fintype.card (f.root_set K) := by
erw [card_root_set_eq_nat_degree hfsep (IsAlgClosed.splits_domain _), nat_degree_X_pow_sub_C]
rw [hroot]
exact Fintype.card_le_of_injective coe Subtype.coe_injective
end IsAlgClosed
namespace IsAlgClosure
variable (K : Type _) (J : Type _) (R : Type u) (S : Type _) [Field K] [Field J] [CommRing R]
(L : Type v) (M : Type w) [Field L] [Field M] [Algebra R M] [NoZeroSMulDivisors R M]
[IsAlgClosure R M] [Algebra K M] [IsAlgClosure K M] [CommRing S] [Algebra S L]
[NoZeroSMulDivisors S L] [IsAlgClosure S L]
attribute [local instance] IsAlgClosure.alg_closed
section
variable [Algebra R L] [NoZeroSMulDivisors R L] [IsAlgClosure R L]
/-- A (random) isomorphism between two algebraic closures of `R`. -/
noncomputable def equiv : L ≃ₐ[R] M :=
let f : L →ₐ[R] M := IsAlgClosed.lift IsAlgClosure.algebraic
AlgEquiv.ofBijective f
⟨RingHom.injective f.toRingHom,
by
letI : Algebra L M := RingHom.toAlgebra f
letI : IsScalarTower R L M :=
IsScalarTower.of_algebraMap_eq (by simp [RingHom.algebraMap_toAlgebra])
show Function.Surjective (algebraMap L M)
exact
IsAlgClosed.algebraMap_surjective_of_isAlgebraic
(Algebra.isAlgebraic_of_larger_base_of_injective
(NoZeroSMulDivisors.algebraMap_injective R _) IsAlgClosure.algebraic)⟩
#align is_alg_closure.equiv IsAlgClosure.equiv
end
section EquivOfAlgebraic
variable [Algebra R S] [Algebra R L] [IsScalarTower R S L]
variable [Algebra K J] [Algebra J L] [IsAlgClosure J L] [Algebra K L] [IsScalarTower K J L]
/-- A (random) isomorphism between an algebraic closure of `R` and an algebraic closure of
an algebraic extension of `R` -/
noncomputable def equivOfAlgebraic' [Nontrivial S] [NoZeroSMulDivisors R S]
(hRL : Algebra.IsAlgebraic R L) : L ≃ₐ[R] M :=
by
letI : NoZeroSMulDivisors R L :=
NoZeroSMulDivisors.of_algebraMap_injective
(by
rw [IsScalarTower.algebraMap_eq R S L]
exact
Function.Injective.comp (NoZeroSMulDivisors.algebraMap_injective _ _)
(NoZeroSMulDivisors.algebraMap_injective _ _))
letI : IsAlgClosure R L :=
{ alg_closed := by infer_instance
algebraic := hRL }
exact IsAlgClosure.equiv _ _ _
#align is_alg_closure.equiv_of_algebraic' IsAlgClosure.equivOfAlgebraic'
/-- A (random) isomorphism between an algebraic closure of `K` and an algebraic closure
of an algebraic extension of `K` -/
noncomputable def equivOfAlgebraic (hKJ : Algebra.IsAlgebraic K J) : L ≃ₐ[K] M :=
equivOfAlgebraic' K J _ _ (Algebra.isAlgebraic_trans hKJ IsAlgClosure.algebraic)
#align is_alg_closure.equiv_of_algebraic IsAlgClosure.equivOfAlgebraic
end EquivOfAlgebraic
section EquivOfEquiv
variable {R S}
/-- Used in the definition of `equiv_of_equiv` -/
noncomputable def equivOfEquivAux (hSR : S ≃+* R) :
{ e : L ≃+* M // e.toRingHom.comp (algebraMap S L) = (algebraMap R M).comp hSR.toRingHom } :=
by
letI : Algebra R S := RingHom.toAlgebra hSR.symm.to_ring_hom
letI : Algebra S R := RingHom.toAlgebra hSR.to_ring_hom
letI : IsDomain R := (NoZeroSMulDivisors.algebraMap_injective R M).IsDomain _
letI : IsDomain S := (NoZeroSMulDivisors.algebraMap_injective S L).IsDomain _
have : Algebra.IsAlgebraic R S := fun x =>
by
rw [← RingEquiv.symm_apply_apply hSR x]
exact isAlgebraic_algebraMap _
letI : Algebra R L := RingHom.toAlgebra ((algebraMap S L).comp (algebraMap R S))
haveI : IsScalarTower R S L := IsScalarTower.of_algebraMap_eq fun _ => rfl
haveI : IsScalarTower S R L :=
IsScalarTower.of_algebraMap_eq (by simp [RingHom.algebraMap_toAlgebra])
haveI : NoZeroSMulDivisors R S := NoZeroSMulDivisors.of_algebraMap_injective hSR.symm.injective
refine'
⟨equiv_of_algebraic' R S L M
(Algebra.isAlgebraic_of_larger_base_of_injective
(show Function.Injective (algebraMap S R) from hSR.injective) IsAlgClosure.algebraic),
_⟩
ext
simp only [RingEquiv.toRingHom_eq_coe, Function.comp_apply, RingHom.coe_comp,
AlgEquiv.coe_ringEquiv, RingEquiv.coe_toRingHom]
conv_lhs => rw [← hSR.symm_apply_apply x]
show equiv_of_algebraic' R S L M _ (algebraMap R L (hSR x)) = _
rw [AlgEquiv.commutes]
#align is_alg_closure.equiv_of_equiv_aux IsAlgClosure.equivOfEquivAux
/-- Algebraic closure of isomorphic fields are isomorphic -/
noncomputable def equivOfEquiv (hSR : S ≃+* R) : L ≃+* M :=
equivOfEquivAux L M hSR
#align is_alg_closure.equiv_of_equiv IsAlgClosure.equivOfEquiv
@[simp]
theorem equivOfEquiv_comp_algebraMap (hSR : S ≃+* R) :
(↑(equivOfEquiv L M hSR) : L →+* M).comp (algebraMap S L) = (algebraMap R M).comp hSR :=
(equivOfEquivAux L M hSR).2
#align is_alg_closure.equiv_of_equiv_comp_algebra_map IsAlgClosure.equivOfEquiv_comp_algebraMap
@[simp]
theorem equivOfEquiv_algebraMap (hSR : S ≃+* R) (s : S) :
equivOfEquiv L M hSR (algebraMap S L s) = algebraMap R M (hSR s) :=
RingHom.ext_iff.1 (equivOfEquiv_comp_algebraMap L M hSR) s
#align is_alg_closure.equiv_of_equiv_algebra_map IsAlgClosure.equivOfEquiv_algebraMap
@[simp]
theorem equivOfEquiv_symm_algebraMap (hSR : S ≃+* R) (r : R) :
(equivOfEquiv L M hSR).symm (algebraMap R M r) = algebraMap S L (hSR.symm r) :=
(equivOfEquiv L M hSR).Injective (by simp)
#align is_alg_closure.equiv_of_equiv_symm_algebra_map IsAlgClosure.equivOfEquiv_symm_algebraMap
@[simp]
theorem equivOfEquiv_symm_comp_algebraMap (hSR : S ≃+* R) :
((equivOfEquiv L M hSR).symm : M →+* L).comp (algebraMap R M) =
(algebraMap S L).comp hSR.symm :=
RingHom.ext_iff.2 (equivOfEquiv_symm_algebraMap L M hSR)
#align is_alg_closure.equiv_of_equiv_symm_comp_algebra_map IsAlgClosure.equivOfEquiv_symm_comp_algebraMap
end EquivOfEquiv
end IsAlgClosure
/-- Let `A` be an algebraically closed field and let `x ∈ K`, with `K/F` an algebraic extension
of fields. Then the images of `x` by the `F`-algebra morphisms from `K` to `A` are exactly
the roots in `A` of the minimal polynomial of `x` over `F`. -/
theorem Algebra.IsAlgebraic.range_eval_eq_rootSet_minpoly {F K} (A) [Field F] [Field K] [Field A]
[IsAlgClosed A] [Algebra F K] (hK : Algebra.IsAlgebraic F K) [Algebra F A] (x : K) :
(Set.range fun ψ : K →ₐ[F] A => ψ x) = (minpoly F x).rootSet A :=
by
have := Algebra.isAlgebraic_iff_isIntegral.1 hK
ext a; rw [mem_root_set_of_ne (minpoly.ne_zero (this x))] <;> [skip, infer_instance]
refine' ⟨_, fun ha => _⟩
· rintro ⟨ψ, rfl⟩
rw [aeval_alg_hom_apply ψ x, minpoly.aeval, map_zero]
let Fx := AdjoinRoot (minpoly F x)
have hx : aeval x (minpoly F x) = 0 := minpoly.aeval F x
letI : Algebra Fx A := (AdjoinRoot.lift (algebraMap F A) a ha).toAlgebra
letI : Algebra Fx K := (AdjoinRoot.lift (algebraMap F K) x hx).toAlgebra
haveI : IsScalarTower F Fx A := IsScalarTower.of_ring_hom (AdjoinRoot.liftHom _ a ha)
haveI : IsScalarTower F Fx K := IsScalarTower.of_ring_hom (AdjoinRoot.liftHom _ x hx)
haveI : Fact (Irreducible <| minpoly F x) := ⟨minpoly.irreducible <| this x⟩
let ψ₀ : K →ₐ[Fx] A := IsAlgClosed.lift (Algebra.isAlgebraic_of_larger_base F Fx hK)
exact
⟨ψ₀.restrict_scalars F,
(congr_arg ψ₀ (AdjoinRoot.lift_root hx).symm).trans <|
(ψ₀.commutes _).trans <| AdjoinRoot.lift_root ha⟩
#align algebra.is_algebraic.range_eval_eq_root_set_minpoly Algebra.IsAlgebraic.range_eval_eq_rootSet_minpoly
|
import analysis.real tactic.norm_num algebra.group_power
theorem Q4 (S : set ℝ) (x : ℝ) (H1 : x ∈ upper_bounds S) (H2 : x ∈ S) : is_lub S x := sorry
|
%% PRIME_SCRIPT is a script to call PRIME_FUN.
%
% Discussion:
%
% The BATCH command runs scripts, not functions. So we have to write
% this short script if we want to work with BATCH!
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 22 May 2012
%
% Author:
%
% John Burkardt
%
n = 10000000;
fprintf ( 1, '\n' );
fprintf ( 1, 'PRIME_SCRIPT\n' );
fprintf ( 1, ' Call PRIME_FUN to count prime numbers from 1 to %d\n', n );
tic
total = prime_fun ( n );
toc
|
lemma null_measure_idem [simp]: "null_measure (null_measure M) = null_measure M" |
lemma cball_trivial [simp]: "cball x 0 = {x}" |
{-# OPTIONS --without-K #-}
module algebra.monoid.morphism where
open import level
open import algebra.monoid.core
open import algebra.semigroup.morphism
open import equality.core
open import function.isomorphism
open import hott.level
open import sum
module _ {i}{j}
{X : Set i}⦃ sX : IsMonoid X ⦄
{Y : Set j}⦃ sY : IsMonoid Y ⦄ where
open IsMonoid ⦃ ... ⦄
record IsMonoidMorphism (f : X → Y) : Set (i ⊔ j) where
constructor mk-is-monoid-morphism
field
sgrp-mor : IsSemigroupMorphism f
id-pres : f e ≡ e
is-monoid-morphism-struct-iso : (f : X → Y)
→ IsMonoidMorphism f ≅ (IsSemigroupMorphism f × (f e ≡ e))
is-monoid-morphism-struct-iso f = record
{ to = λ mor → ( IsMonoidMorphism.sgrp-mor mor
, IsMonoidMorphism.id-pres mor )
; from = λ { (s , i) → mk-is-monoid-morphism s i }
; iso₁ = λ _ → refl
; iso₂ = λ _ → refl }
is-monoid-morphism-level : (f : X → Y) → h 1 (IsMonoidMorphism f)
is-monoid-morphism-level f =
iso-level (sym≅ (is-monoid-morphism-struct-iso f))
(×-level (is-semigroup-morphism-level f)
(is-set _ _))
|
Require Import Util SizeInduction Get MapDefined Coq.Classes.RelationClasses.
Require Import IL Var Val OptionR AllInRel.
Require Import CMap CMapDomain CMapPartialOrder CMapJoinSemiLattice.
Require Import Analysis AnalysisForwardSSA Subterm CSet MapAgreement RenamedApart.
Require Import Infra.PartialOrder Infra.Lattice Infra.WithTop.
Require Import LabelsDefined Annotation.
Require Import Reachability ReachabilityAnalysisCorrectSSA.
Require Import ConstantPropagation ConstantPropagationSound ConstantPropagationAnalysis.
Require Import DomainSSA FiniteFixpointIteration.
Local Arguments proj1_sig {A} {P} e.
Local Arguments length {A} e.
Local Arguments forward {sT} {D} {H} {H0} exp_transf reach_transf ZL ZLIncl st ST d anr.
Notation "'getAE' X" := (proj1_sig (fst (fst X))) (at level 10, X at level 0).
Local Arguments exist {A} {P} x _.
Lemma domenv_map_proper D `{PartialOrder D} Z
: Proper (poEq ==> poEq) (fun AE => domenv AE ⊝ Z).
Proof.
unfold Proper, respectful; intros.
general induction Z; simpl; eauto using poEq_list_struct.
Qed.
Lemma domjoin_list_domenv D `{JoinSemiLattice D} Z (Y:list (option D)) AE
(ND : NoDupA eq Z)
(LEN : ❬Z❭ = ❬Y❭)
: Y ⊑ domenv (domjoin_list AE Z Y) ⊝ Z.
Proof.
general induction LEN; simpl; eauto.
eapply poLe_list_struct.
- unfold domenv at 1.
rewrite domupd_var_eq; eauto.
- eapply PIR2_get; eauto with len.
intros; inv_get.
unfold domenv. rewrite domupd_var_ne; eauto.
exploit IHLEN; eauto.
+ eapply PIR2_nth in H3; eauto; dcr; inv_get.
eapply H6.
+ intro EQ; invc EQ. inv ND. eapply H5.
eapply get_InA in H2. eauto.
Qed.
Lemma cp_sound sT AE ZL s (ST:subTerm s sT) ZLIncl ra anr
: let X := @forward sT _ _ _ (@cp_trans) (@cp_reach) ZL ZLIncl s ST AE anr in
renamedApart s ra
-> annotation s anr
-> labelsDefined s (length ZL)
-> poEq (fst X) (AE,anr)
-> disj (list_union (of_list ⊝ ZL)) (snd (getAnn ra))
-> paramsMatch s (length ⊝ ZL)
-> (forall n Z, get ZL n Z -> NoDupA eq Z)
-> cp_sound (domenv (proj1_sig AE))
(zip pair ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL)) s anr.
Proof.
intros LET RA ANN LD EQ1 DISJ PM NODUP. subst LET.
general induction LD; invt @renamedApart;
try invt @annotation; simpl in *; simpl; invt @paramsMatch;
simpl in *; dcr;
repeat let_pair_case_eq; repeat let_case_eq; repeat simpl_pair_eqs; subst;
simpl in *; try invtc @ann_R; subst.
- set_simpl. clear_trivial_eqs.
+ pose proof EQ1 as EQ3.
eapply forward_domupdd_eq in EQ3; eauto.
* econstructor; eauto.
eapply IHLD; eauto.
split; simpl. rewrite <- EQ1 at 2.
eapply forward_ext; eauto using cp_trans_ext, cp_reach_ext.
rewrite <- EQ3. symmetry; eauto.
rewrite <- H10 at 2.
eapply forward_ext; eauto using cp_trans_ext, cp_reach_ext.
rewrite <- EQ3. symmetry; eauto.
pe_rewrite. eapply disj_2_incl; eauto with cset.
intros.
rewrite EQ1 in EQ3.
specialize (EQ3 x). unfold domenv.
eapply option_R_inv in EQ3.
rewrite EQ3. simpl. rewrite domupd_var_eq; try reflexivity.
* rewrite renamedApart_occurVars; eauto. pe_rewrite.
eapply renamedApart_disj in H4; eauto.
pe_rewrite. revert DISJ H4; clear_all; cset_tac.
- clear_trivial_eqs.
set_simpl.
exploit (forward_if_inv _ _ _ _ _ _ EQ1); eauto.
repeat rewrite renamedApart_occurVars; eauto;
pe_rewrite; eauto.
repeat rewrite renamedApart_occurVars; eauto;
pe_rewrite; eauto with cset.
rewrite forward_ext in EQ1; try eapply H; try reflexivity; eauto using cp_reach_ext, cp_trans_ext; try reflexivity.
econstructor; eauto.
+ eapply IHLD1; eauto.
split; eauto. pe_rewrite. eapply disj_2_incl; eauto.
+ eapply IHLD2; eauto.
split; eauto.
rewrite forward_ext; eauto using cp_reach_ext, cp_trans_ext. symmetry; eauto.
pe_rewrite. symmetry. eapply disj_2_incl; eauto with cset.
- econstructor; eauto.
- inv_get.
econstructor; eauto using zip_get_eq.
intros. cases in EQ1. inv_get.
set_simpl.
unfold domjoin_listd in EQ1.
destruct AE as [AE pf]; simpl in *; clear_trivial_eqs.
unfold poEq in EQ1. simpl in EQ1.
rewrite (get_nth nil H3) in *.
exploit NODUP; eauto.
rewrite lookup_list_map.
symmetry in EQ1.
rewrite domenv_map_proper; eauto.
eapply domjoin_list_domenv; eauto with len.
- clear_trivial_eqs.
eapply PIR2_get in H21; try eassumption. clear H20.
exploit (snd_forwardF_inv _ _ _ _ _ _ _ H21); eauto with len.
exploit (snd_forwardF_inv' _ _ _ _ _ _ _ H21); eauto with len.
Transparent poEq. simpl poEq in H21.
repeat PIR2_eq_simpl. repeat ST_pat.
Opaque poEq.
set (FWt:=(forward cp_trans cp_reach (fst ⊝ F ++ ZL) ZLIncl0 t ST0 AE ta)) in *.
set (FWF:=forwardF (snd FWt) (forward cp_trans cp_reach (fst ⊝ F ++ ZL) ZLIncl0)
F sa (fst (fst FWt)) STF) in *.
assert (fst (fst (FWt)) ≣ AE /\
forall (n : nat) (Zs : params * stmt) (r : ann bool) (ST0 : subTerm (snd Zs) sT),
get F n Zs ->
get sa n r ->
fst
(fst
(forward cp_trans cp_reach (fst ⊝ F ++ ZL) (ZLIncl_ext ZL eq_refl ST ZLIncl) (snd Zs) ST0 AE r))
≣ AE). {
pe_rewrite. set_simpl.
eapply forwardF_agree_get; try eassumption.
- eauto with len.
- rewrite <- EQ1. unfold FWF. reflexivity.
- unfold FWt. reflexivity.
- pe_rewrite. eauto with ren.
- pe_rewrite.
eapply disj_Dt_getAnn; eauto.
- eapply funConstr_disj_ZL_getAnn; eauto.
- eapply disj_1_incl.
eapply funConstr_disj_ZL_getAnn; eauto.
rewrite List.map_app. rewrite list_union_app.
clear_all. cset_tac.
- eapply cp_trans_ext.
- eapply cp_reach_ext.
} dcr.
assert (forall (n : nat) (r : ann bool) (Zs : params * stmt),
get sa n r ->
get F n Zs ->
forall STZs : subTerm (snd Zs) sT,
(snd
(fst
(forward cp_trans cp_reach (fst ⊝ F ++ ZL)
ZLIncl0 (snd Zs) STZs AE r))) ≣ r). {
eapply (@snd_forwardF_inv_get) with (BL:=(snd FWt)); eauto.
subst FWt; eauto with len.
subst FWt; eauto with len.
rewrite <- H2 at 2. unfold FWF.
rewrite forwardF_ext'; try reflexivity; eauto.
eapply cp_trans_ext; eauto.
eapply cp_reach_ext; eauto.
symmetry; eauto.
eapply cp_trans_ext; eauto.
eapply cp_reach_ext; eauto.
}
econstructor; eauto.
+ intros. inv_get. exploit H7; eauto.
assert (EQ:
((fun Zs0 : params * stmt =>
(fst Zs0, lookup_list (domenv (proj1_sig AE)) (fst Zs0))) ⊝ F ++
pair ⊜ ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL))
= zip pair (fst ⊝ F ++ ZL) (lookup_list (domenv (proj1_sig AE)) ⊝ (fst ⊝ F ++ ZL))). {
rewrite !List.map_app. rewrite !zip_app; eauto with len.
rewrite !zip_map_l. rewrite !zip_map_r.
f_equal; eauto.
clear_all. general induction F; simpl; f_equal; eauto.
}
rewrite EQ.
eapply H0; try eassumption.
-- eauto.
-- eauto.
-- eauto with len.
-- split; simpl; eauto.
-- set_simpl.
eapply disj_2_incl.
eapply funConstr_disj_ZL_getAnn; eauto with ren.
eapply incl_list_union; eauto using zip_get.
-- eauto.
-- intros ? ? GET2. eapply get_app_cases in GET2. destruct GET2.
inv_get. edestruct H5; eauto.
dcr. inv_get. eapply NODUP; eauto.
+ assert (EQ:
(fun Zs : params * stmt => (fst Zs, lookup_list (domenv (proj1_sig AE)) (fst Zs)))
⊝ F ++ pair ⊜ ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL)
= zip pair (fst ⊝ F ++ ZL) (lookup_list (domenv (proj1_sig AE)) ⊝ (fst ⊝ F ++ ZL))). {
rewrite !List.map_app. rewrite !zip_app; eauto with len.
rewrite !zip_map_l. rewrite !zip_map_r.
f_equal; eauto.
clear_all. general induction F; simpl; f_equal; eauto.
}
rewrite EQ.
eapply IHLD; eauto with len.
* split; simpl; eauto.
* pe_rewrite. set_simpl.
rewrite List.map_app. rewrite list_union_app.
eapply disj_union_left.
-- symmetry.
eapply funConstr_disj_Dt; eauto.
-- symmetry. eapply disj_incl; eauto.
* intros ? ? GET2. eapply get_app_cases in GET2. destruct GET2.
inv_get. edestruct H5; eauto.
dcr. inv_get. eapply NODUP; eauto.
Grab Existential Variables.
eauto.
Qed.
Definition cp_reachability_sound (sT:stmt)
ZL BL s (d:VDom (occurVars sT) _) r (ST:subTerm s sT) ZLIncl
(EQ:(fst (forward cp_trans cp_reach ZL ZLIncl s ST d r)) ≣ (d,r)) ra
(Ann: annotation s r) (RA:renamedApart s ra)
(DefZL: labelsDefined s (length ZL))
(DefBL: labelsDefined s (length BL))
(BL_le: poLe (snd (forward cp_trans cp_reach ZL ZLIncl s ST d r)) BL)
(Disj:disj (list_union (of_list ⊝ ZL)) (snd (getAnn ra)))
: reachability (cop2bool (domenv (proj1_sig d))) Sound BL s r.
Proof.
eapply reachability_sound with (pr:=fun d => cop2bool (domenv (proj1_sig d)));
eauto using cp_trans_ext, cp_reach_ext.
- unfold cp_reach, cop2bool, Dom; intros;
repeat cases; simpl in *; unfold Dom in *; clear_trivial_eqs; eauto.
+ exfalso. eapply H. rewrite COND; simpl. eauto.
+ exfalso. eapply H. rewrite COND; simpl. eauto.
+ exfalso. eapply H. rewrite COND; simpl. eauto.
- unfold cp_reach, cop2bool, Dom; intros;
repeat cases; simpl in *; unfold Dom in *; clear_trivial_eqs; eauto.
+ exfalso. eapply H. rewrite COND; simpl. eauto.
+ exfalso. eapply H. rewrite COND0; simpl. eauto.
+ exfalso. eapply H. rewrite COND; simpl. eauto.
Qed.
Lemma cp_sound_reorga s (a:ann bool) ra (RA:renamedApart s ra)
(AE : VDom (occurVars s) (withTop val)) an
(EQ : @step _ (constant_propagation_analysis RA) (AE, @exist _ _ a an)
≣ (AE, @exist _ _ a an))
: fst
(forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s (subTerm_refl s) AE a)
≣ (AE, a).
Proof.
rewrite pair_eta at 1.
eapply poEq_struct.
- eapply poEq_fst in EQ. simpl fst at 2 in EQ.
etransitivity; eauto.
- eapply poEq_snd in EQ. simpl snd at 2 in EQ.
revert EQ.
case_eq (snd (@step _ (constant_propagation_analysis RA) (AE, exist a an))); intros.
etransitivity; eauto; swap 1 2.
+ eapply poEq_sig_struct'. eauto.
+ unfold step in H. simpl in H.
eapply poEq_sig_struct'. rewrite H. rewrite EQ. reflexivity.
Qed.
Lemma cp_sound_nil s (AEanr:VDom (occurVars s) (withTop val) * {a : ann bool | annotation s a})
ra
(RA:renamedApart s ra)
: poEq (@step _ (constant_propagation_analysis RA) (AEanr)) (AEanr)
-> paramsMatch s nil
-> ConstantPropagationSound.cp_sound (domenv (proj1_sig (fst AEanr)))
nil s (proj1_sig (snd AEanr)).
Proof.
intros. destruct AEanr as [AE [anr an]].
eapply cp_sound with (ZL:=nil) (ST:=@subTerm_refl _); eauto.
- eapply cp_sound_reorga. eauto.
- simpl. cset_tac.
- isabsurd.
Qed.
Definition cp_reachability_sound_nil s
(AEanr:VDom (occurVars s) (withTop val) * {a : ann bool | annotation s a})
ra
(RA:renamedApart s ra)
: poEq (@step _ (constant_propagation_analysis RA) (AEanr)) (AEanr)
-> paramsMatch s nil
-> reachability (cop2bool (domenv (proj1_sig (fst AEanr))))
Sound nil s (proj1_sig (snd AEanr)).
Proof.
intros. destruct AEanr as [AE [anr an]].
eapply cp_reachability_sound with (BL:=nil) (ZL:=nil); eauto.
- eapply cp_sound_reorga. eapply H.
- assert (❬snd
(forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s
(subTerm_refl s) (fst (AE, exist anr an)) (proj1_sig (snd (AE, exist anr an))))❭ = 0).
eauto with len.
destruct (snd
(forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s
(subTerm_refl s) (fst (AE, exist anr an)) (proj1_sig (snd (AE, exist anr an)))));
eauto. isabsurd.
- simpl. cset_tac.
Qed.
Lemma constantPropagationAnalysis_getAnn s ra
(RA:renamedApart s ra)
: getAnn
(proj1_sig (snd (constantPropagationAnalysis RA))) = true.
Proof.
unfold constantPropagationAnalysis.
eapply safeFixpoint_induction.
- simpl. rewrite getAnn_setTopAnn. reflexivity.
- intros. simpl.
rewrite forward_fst_snd_getAnn. eauto.
Qed.
Lemma constantPropagation_init_inv s ra (RA:renamedApart s ra)
: forall x : var,
x \In freeVars s ->
(DomainSSA.domenv
(proj1_sig (fst (constantPropagationAnalysis RA)))) x === ⎣Top⎦.
Proof.
intros. unfold constantPropagationAnalysis, domenv, constant_propagation_analysis.
eapply makeForwardAnalysisSSA_init_env. eauto.
Qed.
|
section "Formalization of Promela semantics"
theory Promela
imports
PromelaDatastructures
PromelaInvariants
PromelaStatistics
begin
text \<open>Auxiliary\<close>
lemma mod_integer_le:
\<open>x mod (a + 1) \<le> b\<close> if \<open>a \<le> b\<close> \<open>0 < a\<close> for a b x :: integer
using that including integer.lifting proof transfer
fix a b x :: int
assume \<open>0 < a\<close> \<open>a \<le> b\<close>
have \<open>x mod (a + 1) < a + 1\<close>
by (rule pos_mod_bound) (use \<open>0 < a\<close> in simp)
with \<open>a \<le> b\<close> show \<open>x mod (a + 1) \<le> b\<close>
by simp
qed
lemma mod_integer_ge:
\<open>b \<le> x mod (a + 1)\<close> if \<open>b \<le> 0\<close> \<open>0 < a\<close> for a b x :: integer
using that including integer.lifting proof transfer
fix a b x :: int
assume \<open>b \<le> 0\<close> \<open>0 < a\<close>
then have \<open>0 \<le> x mod (a + 1)\<close>
by simp
with \<open>b \<le> 0\<close> show \<open>b \<le> x mod (a + 1)\<close>
by simp
qed
text \<open>
After having defined the datastructures, we present in this theory how to construct the transition system and how to generate the successors of a state, \ie the real semantics of a Promela program.
For the first task, we take the enriched AST as input, the second one operates on the transition system.
\<close>
subsection \<open>Misc Helpers\<close>
definition add_label :: "String.literal \<Rightarrow> labels \<Rightarrow> nat \<Rightarrow> labels" where
"add_label l lbls pos = (
case lm.lookup l lbls of
None \<Rightarrow> lm.update l pos lbls
| Some _ \<Rightarrow> abortv STR ''Label given twice: '' l (\<lambda>_. lbls))"
definition min_prio :: "edge list \<Rightarrow> integer \<Rightarrow> integer" where
"min_prio es start = Min ((prio ` set es) \<union> {start})"
lemma min_prio_code [code]:
"min_prio es start = fold (\<lambda>e pri. if prio e < pri then prio e else pri) es start"
proof -
from Min.set_eq_fold have "Min (set (start # map prio es)) = fold min (map prio es) start" by metis
also have "... = fold (min \<circ> prio) es start" by (simp add: fold_map)
also have "... = fold (\<lambda>e pri. if prio e < pri then prio e else pri) es start" by (auto intro!: fold_cong)
finally show ?thesis by (simp add: min_prio_def)
qed
definition for_all :: "('a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> bool" where
"for_all f xs \<longleftrightarrow> (\<forall>x \<in> set xs. f x)"
lemma for_all_code[code]:
"for_all f xs \<longleftrightarrow> foldli xs id (\<lambda>kv \<sigma>. f kv) True"
by (simp add: for_all_def foldli_conj)
definition find_remove :: "('a \<Rightarrow> bool) \<Rightarrow> 'a list \<Rightarrow> 'a option \<times> 'a list" where
"find_remove P xs = (case List.find P xs of None \<Rightarrow> (None, xs)
| Some x \<Rightarrow> (Some x, List.remove1 x xs))"
lemma find_remove_code [code]:
"find_remove P [] = (None, [])"
"find_remove P (x#xs) = (if P x then (Some x, xs)
else apsnd (Cons x) (find_remove P xs))"
by (induct xs) (auto simp add: find_remove_def dest: find_SomeD split: option.split)
lemma find_remove_subset:
"find_remove P xs = (res, xs') \<Longrightarrow> set xs' \<subseteq> set xs"
unfolding find_remove_def
using set_remove1_subset
by (force split: option.splits)
lemma find_remove_length:
"find_remove P xs = (res, xs') \<Longrightarrow> length xs' \<le> length xs"
unfolding find_remove_def
by (induct xs arbitrary: res xs') (auto split: if_splits option.splits)
subsection \<open>Variable handling\<close>
text \<open>
Handling variables, with their different scopes (global vs. local),
and their different types (array vs channel vs bounded) is one of the main challenges
of the implementation.
\<close>
fun lookupVar :: "variable \<Rightarrow> integer option \<Rightarrow> integer" where
"lookupVar (Var _ val) None = val"
| "lookupVar (Var _ _) (Some _) = abort STR ''Array used on var'' (\<lambda>_.0)"
| "lookupVar (VArray _ _ vals) None = vals !! 0" (* sic! *)
| "lookupVar (VArray _ siz vals) (Some idx) = vals !! nat_of_integer idx"
primrec checkVarValue :: "varType \<Rightarrow> integer \<Rightarrow> integer" where
"checkVarValue (VTBounded lRange hRange) val = (
if val \<le> hRange \<and> val \<ge> lRange then val
else \<comment> \<open>overflowing is well-defined and may actually be used (e.g. bool)\<close>
if lRange = 0 \<and> val > 0
then val mod (hRange + 1)
else \<comment> \<open>we do not want to implement C-semantics (ie type casts)\<close>
abort STR ''Value overflow'' (\<lambda>_. lRange))"
| "checkVarValue VTChan val = (
if val < min_var_value \<or> val > max_var_value
then abort STR ''Value overflow'' (\<lambda>_. 0)
else val)"
context
fixes type :: varType
assumes "varType_inv type"
begin
lemma checkVarValue_bounded:
"checkVarValue type val \<in> {min_var_value..max_var_value}"
using \<open>varType_inv type\<close>
by (cases type) (auto intro: mod_integer_le mod_integer_ge)
lemma checkVarValue_bounds:
"min_var_value \<le> checkVarValue type val"
"checkVarValue type val \<le> max_var_value"
using checkVarValue_bounded [of val] by simp_all
lemma checkVarValue_Var:
"variable_inv (Var type (checkVarValue type val))"
using \<open>varType_inv type\<close> by (simp add: checkVarValue_bounds)
end
fun editVar :: "variable \<Rightarrow> integer option \<Rightarrow> integer \<Rightarrow> variable" where
"editVar (Var type _ ) None val = Var type (checkVarValue type val)"
| "editVar (Var _ _) (Some _) _ = abort STR ''Array used on var'' (\<lambda>_. Var VTChan 0)"
| "editVar (VArray type siz vals) None val = (
let lv = IArray.list_of vals in
let v' = lv[0:=checkVarValue type val] in
VArray type siz (IArray v'))"
| "editVar (VArray type siz vals) (Some idx) val = (
let lv = IArray.list_of vals in
let v' = lv[(nat_of_integer idx):=checkVarValue type val] in
VArray type siz (IArray v'))"
lemma editVar_variable_inv:
assumes "variable_inv v"
shows "variable_inv (editVar v idx val)"
proof (cases v)
case (Var type val) with assms have "varType_inv type" by simp
with Var show ?thesis
by (cases idx)
(auto intro!: checkVarValue_Var
simp del: checkVarValue.simps variable_inv.simps)
next
case (VArray type siz vals)
with assms have [simp, intro!]: "varType_inv type" by simp
show ?thesis
proof (cases idx)
case None with assms VArray show ?thesis
by (cases "IArray.list_of vals") (auto intro!: checkVarValue_bounds)
next
case (Some i)
note upd_cases = in_set_upd_cases[where l="IArray.list_of vals" and i="nat_of_integer i"]
from Some VArray assms show ?thesis
by (cases type)
(auto elim!: upd_cases intro!: mod_integer_le mod_integer_ge simp add: min_var_value_def)
qed
qed
definition getVar'
:: "bool \<Rightarrow> String.literal \<Rightarrow> integer option
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> integer option"
where
"getVar' gl v idx g p = (
let vars = if gl then gState.vars g else pState.vars p in
map_option (\<lambda>x. lookupVar x idx) (lm.lookup v vars))"
definition setVar'
:: "bool \<Rightarrow> String.literal \<Rightarrow> integer option
\<Rightarrow> integer
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> 'a gState_scheme * pState"
where
"setVar' gl v idx val g p = (
if gl then
if v = STR ''_'' then (g,p) \<comment> \<open>\<open>''_''\<close> is a write-only scratch variable\<close>
else case lm.lookup v (gState.vars g) of
None \<Rightarrow> abortv STR ''Unknown global variable: '' v (\<lambda>_. (g,p))
| Some x \<Rightarrow> (g\<lparr>gState.vars := lm.update v (editVar x idx val)
(gState.vars g)\<rparr>
, p)
else
case lm.lookup v (pState.vars p) of
None \<Rightarrow> abortv STR ''Unknown proc variable: '' v (\<lambda>_. (g,p))
| Some x \<Rightarrow> (g, p\<lparr>pState.vars := lm.update v (editVar x idx val)
(pState.vars p)\<rparr>))"
lemma setVar'_gState_inv:
assumes "gState_inv prog g"
shows "gState_inv prog (fst (setVar' gl v idx val g p))"
unfolding setVar'_def using assms
by (auto simp add: gState_inv_def lm.correct
intro: editVar_variable_inv
split: option.splits)
lemma setVar'_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, fst (setVar' gl v idx val g p)) \<in> gState_progress_rel prog"
apply (intro gState_progress_relI)
apply (fact assms)
apply (fact setVar'_gState_inv[OF assms])
apply (auto simp: setVar'_def lm.correct split: option.splits)
done
lemma vardict_inv_process_names:
assumes "vardict_inv ss proc v"
and "lm.lookup k v = Some x"
shows "k \<in> process_names ss proc"
using assms
by (auto simp add: lm.correct vardict_inv_def)
lemma vardict_inv_variable_inv:
assumes "vardict_inv ss proc v"
and "lm.lookup k v = Some x"
shows "variable_inv x"
using assms
by (auto simp add: lm.correct vardict_inv_def)
lemma vardict_inv_updateI:
assumes "vardict_inv ss proc vs"
and "x \<in> process_names ss proc"
and "variable_inv v"
shows "vardict_inv ss proc (lm.update x v vs)"
using assms
by (auto simp add: lm.correct vardict_inv_def)
lemma update_vardict_inv:
assumes "vardict_inv ss proc v"
and "lm.lookup k v = Some x"
and "variable_inv x'"
shows "vardict_inv ss proc (lm.update k x' v)"
using assms
by (auto intro!: vardict_inv_updateI vardict_inv_process_names)
lemma setVar'_pState_inv:
assumes "pState_inv prog p"
shows "pState_inv prog (snd (setVar' gl v idx val g p))"
unfolding setVar'_def using assms
by (auto split: if_splits option.splits
simp add: pState_inv_def
intro: update_vardict_inv editVar_variable_inv vardict_inv_variable_inv)
lemma setVar'_cl_inv:
assumes "cl_inv (g,p)"
shows "cl_inv (setVar' gl v idx val g p)"
unfolding setVar'_def using assms
by (auto split: if_splits option.splits)
definition withVar'
:: "bool \<Rightarrow> String.literal \<Rightarrow> integer option
\<Rightarrow> (integer \<Rightarrow> 'x)
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> 'x"
where
"withVar' gl v idx f g p = f (the (getVar' gl v idx g p))"
definition withChannel'
:: "bool \<Rightarrow> String.literal \<Rightarrow> integer option
\<Rightarrow> (nat \<Rightarrow> channel \<Rightarrow> 'x)
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> 'x"
where
"withChannel' gl v idx f g p = (
let error = \<lambda>_. abortv STR ''Variable is not a channel: '' v
(\<lambda>_. f 0 InvChannel) in
let abort = \<lambda>_. abortv STR ''Channel already closed / invalid: '' v
(\<lambda>_. f 0 InvChannel)
in withVar' gl v idx (\<lambda>i. let i = nat_of_integer i in
if i \<ge> length (channels g) then error ()
else let c = channels g ! i in
case c of
InvChannel \<Rightarrow> abort ()
| _ \<Rightarrow> f i c) g p)"
subsection \<open>Expressions\<close>
text \<open>Expressions are free of side-effects.
This is in difference to SPIN, where @{term run} is an expression with side-effect. We treat @{term run} as a statement.\<close>
abbreviation "trivCond x \<equiv> if x then 1 else 0"
fun exprArith :: "'a gState_scheme \<Rightarrow> pState \<Rightarrow> expr \<Rightarrow> integer"
and pollCheck :: "'a gState_scheme \<Rightarrow> pState \<Rightarrow> channel \<Rightarrow> recvArg list \<Rightarrow> bool
\<Rightarrow> bool"
and recvArgsCheck :: "'a gState_scheme \<Rightarrow> pState \<Rightarrow> recvArg list \<Rightarrow> integer list
\<Rightarrow> bool"
where
"exprArith g p (ExprConst x) = x"
| "exprArith g p (ExprMConst x _) = x"
| "exprArith g p ExprTimeOut = trivCond (timeout g)"
| "exprArith g p (ExprLen (ChanRef (VarRef gl name None))) =
withChannel' gl name None (
\<lambda>_ c. case c of
Channel _ _ q \<Rightarrow> integer_of_nat (length q)
| HSChannel _ \<Rightarrow> 0) g p"
| "exprArith g p (ExprLen (ChanRef (VarRef gl name (Some idx)))) =
withChannel' gl name (Some (exprArith g p idx)) (
\<lambda>_ c. case c of
Channel _ _ q \<Rightarrow> integer_of_nat (length q)
| HSChannel _ \<Rightarrow> 0) g p"
| "exprArith g p (ExprEmpty (ChanRef (VarRef gl name None))) =
trivCond (withChannel' gl name None (
\<lambda>_ c. case c of Channel _ _ q \<Rightarrow> (q = [])
| HSChannel _ \<Rightarrow> True) g p)"
| "exprArith g p (ExprEmpty (ChanRef (VarRef gl name (Some idx)))) =
trivCond (withChannel' gl name (Some (exprArith g p idx)) (
\<lambda>_ c. case c of Channel _ _ q \<Rightarrow> (q = [])
| HSChannel _ \<Rightarrow> True) g p)"
| "exprArith g p (ExprFull (ChanRef(VarRef gl name None))) =
trivCond (withChannel' gl name None (
\<lambda>_ c. case c of
Channel cap _ q \<Rightarrow> integer_of_nat (length q) \<ge> cap
| HSChannel _ \<Rightarrow> False) g p)"
| "exprArith g p (ExprFull (ChanRef(VarRef gl name (Some idx)))) =
trivCond (withChannel' gl name (Some (exprArith g p idx)) (
\<lambda>_ c. case c of
Channel cap _ q \<Rightarrow> integer_of_nat (length q) \<ge> cap
| HSChannel _ \<Rightarrow> False) g p)"
| "exprArith g p (ExprVarRef (VarRef gl name None)) =
withVar' gl name None id g p"
| "exprArith g p (ExprVarRef (VarRef gl name (Some idx))) =
withVar' gl name (Some (exprArith g p idx)) id g p"
| "exprArith g p (ExprUnOp UnOpMinus expr) = 0 - exprArith g p expr"
| "exprArith g p (ExprUnOp UnOpNeg expr) = ((exprArith g p expr) + 1) mod 2"
| "exprArith g p (ExprBinOp BinOpAdd lexpr rexpr) =
(exprArith g p lexpr) + (exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpSub lexpr rexpr) =
(exprArith g p lexpr) - (exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpMul lexpr rexpr) =
(exprArith g p lexpr) * (exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpDiv lexpr rexpr) =
(exprArith g p lexpr) div (exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpMod lexpr rexpr) =
(exprArith g p lexpr) mod (exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpGr lexpr rexpr) =
trivCond (exprArith g p lexpr > exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpLe lexpr rexpr) =
trivCond (exprArith g p lexpr < exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpGEq lexpr rexpr) =
trivCond (exprArith g p lexpr \<ge> exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpLEq lexpr rexpr) =
trivCond (exprArith g p lexpr \<le> exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpEq lexpr rexpr) =
trivCond (exprArith g p lexpr = exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpNEq lexpr rexpr) =
trivCond (exprArith g p lexpr \<noteq> exprArith g p rexpr)"
| "exprArith g p (ExprBinOp BinOpAnd lexpr rexpr) =
trivCond (exprArith g p lexpr \<noteq> 0 \<and> exprArith g p rexpr \<noteq> 0)"
| "exprArith g p (ExprBinOp BinOpOr lexpr rexpr) =
trivCond (exprArith g p lexpr \<noteq> 0 \<or> exprArith g p rexpr \<noteq> 0)"
| "exprArith g p (ExprCond cexpr texpr fexpr) =
(if exprArith g p cexpr \<noteq> 0 then exprArith g p texpr
else exprArith g p fexpr)"
| "exprArith g p (ExprPoll (ChanRef (VarRef gl name None)) rs srt) =
trivCond (withChannel' gl name None (
\<lambda>_ c. pollCheck g p c rs srt) g p)"
| "exprArith g p (ExprPoll (ChanRef (VarRef gl name (Some idx))) rs srt) =
trivCond (withChannel' gl name (Some (exprArith g p idx)) (
\<lambda>_ c. pollCheck g p c rs srt) g p)"
| "pollCheck g p InvChannel _ _ =
abort STR ''Channel already closed / invalid.'' (\<lambda>_. False)"
| "pollCheck g p (HSChannel _) _ _ = False"
| "pollCheck g p (Channel _ _ q) rs srt = (
if q = [] then False
else if \<not> srt then recvArgsCheck g p rs (hd q)
else List.find (recvArgsCheck g p rs) q \<noteq> None)"
| "recvArgsCheck _ _ [] [] = True"
| "recvArgsCheck _ _ _ [] =
abort STR ''Length mismatch on receiving.'' (\<lambda>_. False)"
| "recvArgsCheck _ _ [] _ =
abort STR ''Length mismatch on receiving.'' (\<lambda>_. False)"
| "recvArgsCheck g p (r#rs) (v#vs) = ((
case r of
RecvArgConst c \<Rightarrow> c = v
| RecvArgMConst c _ \<Rightarrow> c = v
| RecvArgVar var \<Rightarrow> True
| RecvArgEval e \<Rightarrow> exprArith g p e = v ) \<and> recvArgsCheck g p rs vs)"
text \<open>@{const getVar'} etc.\ do operate on name, index, \ldots directly. Lift them to use @{const VarRef} instead.\<close>
fun liftVar where
"liftVar f (VarRef gl v idx) argm g p =
f gl v (map_option (exprArith g p) idx) argm g p"
definition "getVar v = liftVar (\<lambda>gl v idx arg. getVar' gl v idx) v ()"
definition "setVar = liftVar setVar'"
definition "withVar = liftVar withVar'"
primrec withChannel
where "withChannel (ChanRef v) = liftVar withChannel' v"
lemma setVar_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, fst (setVar v val g p)) \<in> gState_progress_rel prog"
unfolding setVar_def
by (cases v) (simp add: setVar'_gState_progress_rel[OF assms])
lemmas setVar_gState_inv =
setVar_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma setVar_pState_inv:
assumes "pState_inv prog p"
shows "pState_inv prog (snd (setVar v val g p))"
unfolding setVar_def
by (cases v) (auto simp add: setVar'_pState_inv assms)
lemma setVar_cl_inv:
assumes "cl_inv (g,p)"
shows "cl_inv (setVar v val g p)"
unfolding setVar_def
by (cases v) (auto simp add: setVar'_cl_inv assms)
subsection \<open>Variable declaration\<close>
lemma channel_inv_code [code]:
"channel_inv (Channel cap ts q)
\<longleftrightarrow> cap \<le> max_array_size
\<and> 0 \<le> cap
\<and> for_all varType_inv ts
\<and> length ts \<le> max_array_size
\<and> length q \<le> max_array_size
\<and> for_all (\<lambda>x. length x = length ts
\<and> for_all (\<lambda>y. y \<ge> min_var_value
\<and> y \<le> max_var_value) x) q"
"channel_inv (HSChannel ts)
\<longleftrightarrow> for_all varType_inv ts \<and> length ts \<le> max_array_size"
by (auto simp add: for_all_def) force+
primrec toVariable
:: "'a gState_scheme \<Rightarrow> pState \<Rightarrow> varDecl \<Rightarrow> String.literal * variable * channels"
where
"toVariable g p (VarDeclNum lb hb name siz init) = (
let type = VTBounded lb hb in
if \<not> varType_inv type then abortv STR ''Invalid var def (varType_inv failed): '' name
(\<lambda>_. (name, Var VTChan 0, []))
else
let
init = checkVarValue type (case init of
None \<Rightarrow> 0
| Some e \<Rightarrow> exprArith g p e);
v = (case siz of
None \<Rightarrow> Var type init
| Some s \<Rightarrow> if nat_of_integer s \<le> max_array_size
then VArray type (nat_of_integer s)
(IArray.tabulate (s, \<lambda>_. init))
else abortv STR ''Invalid var def (array too large): '' name
(\<lambda>_. Var VTChan 0))
in
(name, v, []))"
| "toVariable g p (VarDeclChan name siz types) = (
let
size = (case siz of None \<Rightarrow> 1 | Some s \<Rightarrow> nat_of_integer s);
chans = (case types of
None \<Rightarrow> []
| Some (cap, tys) \<Rightarrow>
let C = (if cap = 0 then HSChannel tys
else Channel cap tys []) in
if \<not> channel_inv C
then abortv STR ''Invalid var def (channel_inv failed): ''
name (\<lambda>_. [])
else replicate size C);
cidx = (case types of
None \<Rightarrow> 0
| Some _ \<Rightarrow> integer_of_nat (length (channels g)));
v = (case siz of
None \<Rightarrow> Var VTChan cidx
| Some s \<Rightarrow> if nat_of_integer s \<le> max_array_size
then VArray VTChan (nat_of_integer s)
(IArray.tabulate (s,
\<lambda>i. if cidx = 0 then 0
else i + cidx))
else abortv STR ''Invalid var def (array too large): ''
name (\<lambda>_. Var VTChan 0))
in
(name, v, chans))"
lemma toVariable_variable_inv:
assumes "gState_inv prog g"
shows "variable_inv (fst (snd (toVariable g p v)))"
using assms
apply (cases v)
apply (auto intro!: checkVarValue_Var
simp del: variable_inv.simps checkVarValue.simps varType_inv.simps
split: if_splits option.splits)
apply (auto intro!: mod_integer_ge mod_integer_le simp add: min_var_value_def)
apply (simp_all add: assms gState_inv_def
max_channels_def max_var_value_def min_var_value_def max_array_size_def)
including integer.lifting
apply (transfer', simp)+
done
lemma toVariable_channels_inv:
shows "\<forall>x \<in> set (snd (snd (toVariable g p v))). channel_inv x"
by (cases v) auto
lemma toVariable_channels_inv':
shows "toVariable g p v = (a,b,c) \<Longrightarrow> \<forall>x \<in> set c. channel_inv x"
using toVariable_channels_inv
by (metis snd_conv)
lemma toVariable_variable_inv':
shows "gState_inv prog g \<Longrightarrow> toVariable g p v = (a,b,c) \<Longrightarrow> variable_inv b"
by (metis snd_conv fst_conv toVariable_variable_inv)
definition mkChannels
:: "'a gState_scheme \<Rightarrow> pState \<Rightarrow> channels \<Rightarrow> 'a gState_scheme * pState"
where
"mkChannels g p cs = (
if cs = [] then (g,p) else
let l = length (channels g) in
if l + length cs > max_channels
then abort STR ''Too much channels'' (\<lambda>_. (g,p))
else let
cs\<^sub>p = map integer_of_nat [l..<l + length cs];
g' = g\<lparr>channels := channels g @ cs\<rparr>;
p' = p\<lparr>pState.channels := pState.channels p @ cs\<^sub>p\<rparr>
in
(g', p'))"
lemma mkChannels_gState_progress_rel:
"gState_inv prog g
\<Longrightarrow> set cs \<subseteq> Collect channel_inv
\<Longrightarrow> (g, fst (mkChannels g p cs)) \<in> gState_progress_rel prog"
unfolding mkChannels_def
by (intro gState_progress_relI)
(auto simp add: gState_inv_def gState.defs cl_inv_def)
lemmas mkChannels_gState_inv =
mkChannels_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma mkChannels_pState_inv:
"pState_inv prog p
\<Longrightarrow> cl_inv (g,p)
\<Longrightarrow> pState_inv prog (snd (mkChannels g p cs))"
unfolding mkChannels_def
including integer.lifting
apply (auto simp add: pState_inv_def pState.defs gState_inv_def dest!: cl_inv_lengthD)
apply (transfer', simp)+
done
lemma mkChannels_cl_inv:
"cl_inv (g,p) \<Longrightarrow> cl_inv (mkChannels g p cs)"
unfolding mkChannels_def
by (auto simp add: pState.defs dest: cl_inv_lengthD intro!: cl_invI)
definition mkVarChannel
:: "varDecl
\<Rightarrow> ((var_dict \<Rightarrow> var_dict) \<Rightarrow> 'a gState_scheme * pState
\<Rightarrow> 'a gState_scheme * pState)
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> 'a gState_scheme * pState"
where
"mkVarChannel v upd g p = (
let
(k,v,cs) = toVariable g p v;
(g',p') = upd (lm.update k v) (g,p)
in
mkChannels g' p' cs)"
lemma mkVarChannel_gState_inv:
assumes "gState_inv prog g"
and "\<And>k v' cs. toVariable g p v = (k,v',cs)
\<Longrightarrow> gState_inv prog (fst (upd (lm.update k v') (g,p)))"
shows "gState_inv prog (fst (mkVarChannel v upd g p))"
using assms unfolding mkVarChannel_def
by (force split: varDecl.split prod.split
intro!: mkChannels_gState_inv
dest: toVariable_channels_inv')
lemma mkVarChannel_gState_progress_rel:
assumes "gState_inv prog g"
and "\<And>k v' cs. toVariable g p v = (k,v',cs)
\<Longrightarrow> (g, fst (upd (lm.update k v') (g,p))) \<in> gState_progress_rel prog"
shows "(g, fst (mkVarChannel v upd g p)) \<in> gState_progress_rel prog"
proof -
obtain k v' cs where 1: "toVariable g p v = (k,v',cs)" by (metis prod.exhaust)
obtain g' p' where 2: "(g',p') = upd (lm.update k v') (g,p)" by (metis prod.exhaust)
with 1 assms have *: "(g, g') \<in> gState_progress_rel prog" by (metis fst_conv)
also from 1 2 have "(g', fst (mkChannels g' p' cs)) \<in> gState_progress_rel prog"
by (force intro!: mkChannels_gState_progress_rel gState_progress_rel_gState_invI2[OF *]
dest: toVariable_channels_inv')
finally have "(g, fst (mkChannels g' p' cs)) \<in> gState_progress_rel prog" .
thus ?thesis using 1 2 by (auto simp add: mkVarChannel_def split: prod.split)
qed
lemma mkVarChannel_pState_inv:
assumes "pState_inv prog p"
and "cl_inv (g,p)"
and "\<And>k v' cs. toVariable g p v = (k,v',cs)
\<Longrightarrow> cl_inv (upd (lm.update k v') (g,p))"
and "\<And>k v' cs. toVariable g p v = (k,v',cs)
\<Longrightarrow> pState_inv prog (snd (upd (lm.update k v') (g,p)))"
shows "pState_inv prog (snd (mkVarChannel v upd g p))"
using assms unfolding mkVarChannel_def
by (force split: varDecl.split prod.split
intro!: mkChannels_pState_inv)
lemma mkVarChannel_cl_inv:
assumes "cl_inv (g,p)"
and "\<And>k v' cs. toVariable g p v = (k,v',cs)
\<Longrightarrow> cl_inv (upd (lm.update k v') (g,p))"
shows "cl_inv (mkVarChannel v upd g p)"
using assms unfolding mkVarChannel_def
by (force split: varDecl.split prod.splits
intro!: mkChannels_cl_inv)
definition mkVarChannelProc
:: "procVarDecl \<Rightarrow> 'a gState_scheme \<Rightarrow> pState \<Rightarrow> 'a gState_scheme * pState"
where
"mkVarChannelProc v g p = (
let
v' = case v of
ProcVarDeclNum lb hb name siz init \<Rightarrow>
VarDeclNum lb hb name siz init
| ProcVarDeclChan name siz \<Rightarrow>
VarDeclChan name siz None;
(k,v,cs) = toVariable g p v'
in
mkVarChannel v' (apsnd \<circ> pState.vars_update) g p)"
lemma mkVarChannelProc_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, fst (mkVarChannelProc v g p)) \<in> gState_progress_rel prog"
unfolding mkVarChannelProc_def
using assms
by (auto intro!: mkVarChannel_gState_progress_rel)
lemmas mkVarChannelProc_gState_inv =
mkVarChannelProc_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma toVariable_name:
"toVariable g p (VarDeclNum lb hb name sz init) = (x,a,b) \<Longrightarrow> x = name"
"toVariable g p (VarDeclChan name sz t) = (x, a, b) \<Longrightarrow> x = name"
by (auto split: if_splits)
declare toVariable.simps[simp del]
lemma statesDecls_process_names:
assumes "v \<in> statesDecls (states prog !! (pState.idx p))"
shows "procVarDeclName v \<in> process_names (states prog !! (pState.idx p))
(processes prog !! (pState.idx p))"
using assms
by (cases "processes prog !! (pState.idx p)") (auto simp add: statesNames_def)
lemma mkVarChannelProc_pState_inv:
assumes "pState_inv prog p"
and "gState_inv prog g"
and "cl_inv (g, p)"
and decl: "v \<in> statesDecls (states prog !! (pState.idx p))"
shows "pState_inv prog (snd (mkVarChannelProc v g p))"
unfolding mkVarChannelProc_def
using assms statesDecls_process_names[OF decl]
by (auto intro!: mkVarChannel_pState_inv)
(auto dest: toVariable_name
split: procVarDecl.splits
intro: toVariable_variable_inv' vardict_inv_updateI
simp add: pState_inv_def)
lemma mkVarChannelProc_cl_inv:
assumes "cl_inv (g,p)"
shows "cl_inv (mkVarChannelProc v g p)"
unfolding mkVarChannelProc_def using assms
by (auto intro!: mkVarChannel_cl_inv)
subsection \<open>Folding\<close>
text \<open>
Fold over lists (and lists of lists) of @{typ step}/@{typ stmnt}. The folding functions are
doing a bit more than that, e.g.\ ensuring the offset into the program array is correct.
\<close>
definition step_fold' where
"step_fold' g steps (lbls :: labels) pri pos
(nxt :: edgeIndex) (onxt :: edgeIndex option) iB =
foldr (\<lambda>step (pos, nxt, lbls, es).
let (e,enxt,lbls) = g step (lbls, pri, pos, nxt, onxt, iB)
in (pos + length e, enxt, lbls, es@e)
) steps (pos, nxt, lbls, [])"
definition step_fold where
"step_fold g steps lbls pri pos nxt onxt iB = (
let (_,nxt,lbls,s) = step_fold' g steps lbls pri pos nxt onxt iB
in (s,nxt,lbls))"
lemma step_fold'_cong:
assumes "lbls = lbls'"
and "pri = pri'"
and "pos = pos'"
and "steps = steps'"
and "nxt = nxt'"
and "onxt = onxt'"
and "iB = iB'"
and "\<And>x d. x \<in> set steps \<Longrightarrow> g x d = g' x d"
shows "step_fold' g steps lbls pri pos nxt onxt iB =
step_fold' g' steps' lbls' pri' pos' nxt' onxt' iB'"
unfolding step_fold'_def
by (auto intro: foldr_cong simp add: assms)
lemma step_fold_cong[fundef_cong]:
assumes "lbls = lbls'"
and "pri = pri'"
and "pos = pos'"
and "steps = steps'"
and "nxt = nxt'"
and "onxt = onxt'"
and "iB = iB'"
and "\<And>x d. x \<in> set steps \<Longrightarrow> g x d = g' x d"
shows "step_fold g steps lbls pri pos nxt onxt iB =
step_fold g' steps' lbls' pri' pos' nxt' onxt' iB'"
unfolding step_fold_def
by (auto simp: assms cong: step_fold'_cong)
fun step_foldL_step where
"step_foldL_step _ _ _ [] (pos, nxt, lbls, es, is) = (pos, nxt, lbls, es, is)"
| "step_foldL_step g pri onxt (s#steps) (pos, nxt, lbls, es, is) = (
let (pos', nxt', lbls', ss') = step_fold' g steps lbls pri pos nxt onxt False in
let (s', nxt'', lbls'') = g s (lbls',pri,pos',nxt',onxt,True) in
let rs = butlast s'; s'' = last s' in
(pos' + length rs, nxt, lbls'', es@ss'@rs, s''#is))"
definition step_foldL where
"step_foldL g stepss lbls pri pos nxt onxt =
foldr (step_foldL_step g pri onxt) stepss (pos,nxt,lbls,[],[])"
lemma step_foldL_step_cong:
assumes "pri = pri'"
and "onxt = onxt'"
and "s = s'"
and "d = d'"
and "\<And>x d. x \<in> set s \<Longrightarrow> g x d = g' x d"
shows "step_foldL_step g pri onxt s d = step_foldL_step g' pri' onxt' s' d'"
using assms
by (cases d', cases s') (simp_all cong: step_fold'_cong)
lemma step_foldL_cong[fundef_cong]:
assumes "lbls = lbls'"
and "pri = pri'"
and "pos = pos'"
and "stepss = stepss'"
and "nxt = nxt'"
and "onxt = onxt'"
and "\<And>x x' d. x \<in> set stepss \<Longrightarrow> x' \<in> set x \<Longrightarrow> g x' d = g' x' d"
shows "step_foldL g stepss lbls pri pos nxt onxt =
step_foldL g' stepss' lbls' pri' pos' nxt' onxt'"
unfolding step_foldL_def
using assms
apply (cases stepss')
apply simp
apply (force intro!: foldr_cong step_foldL_step_cong)
done
subsection \<open>Starting processes\<close>
definition modProcArg
:: "(procArg * integer) \<Rightarrow> String.literal * variable"
where
"modProcArg x = (
case x of
(ProcArg ty name, val) \<Rightarrow> if varType_inv ty
then let init = checkVarValue ty val
in (name, Var ty init)
else abortv STR ''Invalid proc arg (varType_inv failed)''
name (\<lambda>_. (name, Var VTChan 0)))"
definition emptyProc :: "pState"
\<comment> \<open>The empty process.\<close>
where
"emptyProc = \<lparr>pid = 0, vars = lm.empty (), pc = 0, channels = [], idx = 0 \<rparr>"
lemma vardict_inv_empty:
"vardict_inv ss proc (lm.empty())"
unfolding vardict_inv_def
by (simp add: lm.correct)
lemma emptyProc_cl_inv[simp]:
"cl_inv (g, emptyProc)"
by (simp add: cl_inv_def emptyProc_def)
lemma emptyProc_pState_inv:
assumes "program_inv prog"
shows "pState_inv prog emptyProc"
proof -
from assms have "IArray.length (states prog !! 0) > 0"
by (intro program_inv_length_states) (auto simp add: program_inv_def)
with assms show ?thesis
unfolding pState_inv_def program_inv_def emptyProc_def
by (auto simp add: vardict_inv_empty)
qed
fun mkProc
:: "'a gState_scheme \<Rightarrow> pState
\<Rightarrow> String.literal \<Rightarrow> expr list \<Rightarrow> process \<Rightarrow> nat
\<Rightarrow> 'a gState_scheme * pState"
where
"mkProc g p name args (sidx, start, argDecls, decls) pidN = (
let start = case start of
Index x \<Rightarrow> x
| _ \<Rightarrow> abortv STR ''Process start is not index: '' name (\<lambda>_. 0)
in
\<comment> \<open>sanity check\<close>
if length args \<noteq> length argDecls
then abortv STR ''Signature mismatch: '' name (\<lambda>_. (g,emptyProc))
else
let
\<comment> \<open>evaluate args (in the context of the calling process)\<close>
eArgs = map (exprArith g p) args;
\<comment> \<open>replace the init part of \<open>argDecls\<close>\<close>
argVars = map modProcArg (zip argDecls eArgs);
\<comment> \<open>add \<open>_pid\<close> to vars\<close>
pidI = integer_of_nat pidN;
argVars = (STR ''_pid'', Var (VTBounded 0 pidI) pidI)#argVars;
argVars = lm.to_map argVars;
\<comment> \<open>our new process\<close>
p = \<lparr> pid = pidN, vars = argVars, pc = start, channels = [], idx = sidx \<rparr>
in
\<comment> \<open>apply the declarations\<close>
foldl (\<lambda>(g,p) d. mkVarChannel d (apsnd \<circ> pState.vars_update) g p)
(g,p)
decls)"
lemma mkProc_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, fst (mkProc g p name args (processes prog !! sidx) pidN)) \<in>
gState_progress_rel prog"
proof -
obtain sidx' start argDecls decls where
p: "processes prog !! sidx = (sidx', start, argDecls, decls)"
by (metis prod.exhaust)
from assms have
"\<And>p. (g, fst (foldl (\<lambda>(g,p) d. mkVarChannel d (apsnd \<circ> pState.vars_update) g p)
(g,p) decls))
\<in> gState_progress_rel prog"
proof (induction decls arbitrary: g p)
case (Cons d decls)
obtain g' p' where
new: "(g',p') = (mkVarChannel d (apsnd \<circ> pState.vars_update) g p)"
by (metis prod.exhaust)
hence "g' = fst ..." by (metis fst_conv)
with Cons.prems have g_g': "(g,g') \<in> gState_progress_rel prog"
by (auto intro: mkVarChannel_gState_progress_rel)
also note Cons.IH[OF g_g'[THEN gState_progress_rel_gState_invI2], of p']
finally show ?case by (auto simp add: o_def new)
qed simp
thus ?thesis using assms p by auto
qed
lemmas mkProc_gState_inv =
mkProc_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma mkProc_pState_inv:
assumes "program_inv prog"
and "gState_inv prog g"
and "pidN \<le> max_procs" and "pidN > 0"
and "sidx < IArray.length (processes prog)"
and "fst (processes prog !! sidx) = sidx"
shows "pState_inv prog (snd (mkProc g p name args (processes prog !! sidx) pidN))"
proof -
obtain sidx' start argDecls decls where
"processes prog !! sidx = (sidx', start, argDecls, decls)"
by (metis prod.exhaust)
with assms have
p_def: "processes prog !! sidx = (sidx, start, argDecls, decls)"
"IArray.list_of (processes prog) ! sidx = (sidx, start, argDecls, decls)"
by simp_all
with assms have "(sidx,start,argDecls,decls) \<in> set (IArray.list_of (processes prog))"
by (force dest: nth_mem)
with assms obtain s where s: "start = Index s" "s < IArray.length (states prog !! sidx)"
unfolding program_inv_def by auto
hence P_inv: "pState_inv prog \<lparr>
pid = pidN,
vars = lm.to_map
((STR ''_pid'', Var (VTBounded 0 (integer_of_nat pidN))
(integer_of_nat pidN))
# map modProcArg (zip argDecls (map (exprArith g p) args))),
pc = s, channels = [], idx = sidx\<rparr>"
unfolding pState_inv_def
using assms[unfolded program_inv_def]
including integer.lifting
apply (simp add: p_def)
apply (intro lm_to_map_vardict_inv)
apply auto
apply (simp add: max_procs_def max_var_value_def)
apply transfer'
apply simp
apply transfer'
apply simp
apply (simp add: min_var_value_def)
apply transfer'
apply simp
apply (simp add: max_var_value_def max_procs_def)
apply transfer'
apply simp
apply (drule set_zip_leftD)
apply (force simp add: modProcArg_def
split: procArg.splits if_splits
intro!: image_eqI)
apply (clarsimp simp add: modProcArg_def
split: procArg.splits if_splits
simp del: variable_inv.simps)
apply (intro checkVarValue_Var)
apply assumption
done
from p_def have
"varDeclName ` set decls \<subseteq>
process_names (states prog !! sidx) (processes prog !! sidx)"
by auto
with \<open>gState_inv prog g\<close> have
F_inv: "\<And>p. \<lbrakk> pState_inv prog p; sidx = pState.idx p; cl_inv (g,p) \<rbrakk>
\<Longrightarrow> pState_inv prog
(snd (foldl (\<lambda>(g,p) d. mkVarChannel d (apsnd \<circ> pState.vars_update) g p)
(g,p) decls))"
proof (induction decls arbitrary: g p)
case (Cons d ds) hence
decl: "varDeclName d \<in> process_names (states prog !! pState.idx p)
(processes prog !! pState.idx p)"
by simp
obtain g' p' where
new: "(g',p') = (mkVarChannel d (apsnd \<circ> pState.vars_update) g p)"
by (metis prod.exhaust)
hence p': "p' = snd ..." and g': "g' = fst ..."
by (metis snd_conv fst_conv)+
with Cons.prems have "pState_inv prog p'"
apply (auto intro!: mkVarChannel_pState_inv)
apply (simp add: pState_inv_def)
apply (intro vardict_inv_updateI)
apply simp
apply (cases d)
apply (force dest!: toVariable_name)
apply (force dest!: toVariable_name)
apply (intro toVariable_variable_inv')
apply assumption+
done
moreover
from p' Cons.prems have "pState.idx p' = sidx"
by (auto simp add: mkVarChannel_def mkChannels_def split: prod.split)
moreover
from new Cons.prems have "cl_inv (g',p')"
by (auto intro!: mkVarChannel_cl_inv)
moreover
from g' Cons.prems have "gState_inv prog g'"
by (auto intro!: mkVarChannel_gState_inv)
moreover
from Cons.prems have
"varDeclName ` set ds \<subseteq>
process_names (states prog !! sidx) (processes prog !! sidx)"
by simp
ultimately
have
"pState_inv prog
(snd (foldl (\<lambda>(g,p) d. mkVarChannel d (apsnd \<circ> pState.vars_update) g p)
(g',p') ds))"
using Cons.IH[of p' g'] by (simp add: o_def)
with new show ?case by (simp add: o_def)
qed simp
show ?thesis
by (auto simp add: p_def s cl_inv_def
intro: F_inv[OF P_inv])
(blast intro: emptyProc_pState_inv assms)
qed
lemma mkProc_cl_inv:
assumes "cl_inv (g,p)"
shows "cl_inv (mkProc g p name args (processes prog !! sidx) pidN)"
proof -
note IArray.sub_def [simp del]
obtain sidx' start argDecls decls
where [simp]: "processes prog !! sidx = (sidx', start, argDecls, decls)"
by (metis prod.exhaust)
have
P_inv: "\<And>s v. cl_inv (g, \<lparr>pid = pidN, vars = v, pc = s, channels = [], idx = sidx' \<rparr>)"
by (simp add: cl_inv_def)
have
"\<And>p. cl_inv(g,p) \<Longrightarrow>
cl_inv (foldl (\<lambda>(g,p) d. mkVarChannel d (apsnd \<circ> pState.vars_update) g p)
(g,p) decls)"
proof (induction decls arbitrary: g p)
case (Cons d ds)
obtain g' p' where
new: "(g',p') = (mkVarChannel d (apsnd \<circ> pState.vars_update) g p)"
by (metis prod.exhaust)
with Cons.prems have "cl_inv (g',p')"
by (auto intro!: mkVarChannel_cl_inv)
from Cons.IH[OF this] new show ?case by (simp add: o_def)
qed simp
from this[OF P_inv] show ?thesis by auto
qed
declare mkProc.simps[simp del]
definition runProc
:: "String.literal \<Rightarrow> expr list \<Rightarrow> program
\<Rightarrow> 'a gState_scheme \<Rightarrow> pState
\<Rightarrow> 'a gState_scheme * pState"
where
"runProc name args prog g p = (
if length (procs g) \<ge> max_procs
then abort STR ''Too many processes'' (\<lambda>_. (g,p))
else let pid = length (procs g) + 1 in
case lm.lookup name (proc_data prog) of
None \<Rightarrow> abortv STR ''No such process: '' name
(\<lambda>_. (g,p))
| Some proc_idx \<Rightarrow>
let (g', proc) = mkProc g p name args (processes prog !! proc_idx) pid
in (g'\<lparr>procs := procs g @ [proc]\<rparr>, p))"
lemma runProc_gState_progress_rel:
assumes "program_inv prog"
and "gState_inv prog g"
and "pState_inv prog p"
and "cl_inv (g,p)"
shows "(g, fst (runProc name args prog g p)) \<in> gState_progress_rel prog"
proof (cases "length (procs g) < max_procs")
note IArray.sub_def [simp del]
case True thus ?thesis
proof (cases "lm.lookup name (proc_data prog)")
case (Some proc_idx)
hence *: "proc_idx < IArray.length (processes prog)"
"fst (processes prog !! proc_idx) = proc_idx"
using assms
by (simp_all add: lm.correct program_inv_def)
obtain g' p' where
new: "(g',p') = mkProc g p name args (processes prog !! proc_idx) (length (procs g) + 1)"
by (metis prod.exhaust)
hence g': "g' = fst ..." and p': "p' = snd ..."
by (metis snd_conv fst_conv)+
from assms g' have "(g, g') \<in> gState_progress_rel prog "
by (auto intro!: mkProc_gState_progress_rel)
moreover
from * assms True p' have "pState_inv prog p'"
by (auto intro!: mkProc_pState_inv)
moreover
from assms new have "cl_inv (g',p')"
by (auto intro!: mkProc_cl_inv)
ultimately show ?thesis
using True Some new assms
unfolding runProc_def gState_progress_rel_def
by (clarsimp split: prod.split)
(auto simp add: gState_inv_def cl_inv_def)
next
case None with assms show ?thesis by (auto simp add: runProc_def)
qed
next
case False with assms show ?thesis by (auto simp add: runProc_def)
qed
lemmas runProc_gState_inv =
runProc_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma runProc_pState_id:
"snd (runProc name args prog g p) = p"
unfolding runProc_def
by (auto split: if_splits split: option.split prod.split)
lemma runProc_pState_inv:
assumes "pState_inv prog p"
shows "pState_inv prog (snd (runProc name args prog g p))"
by (simp add: assms runProc_pState_id)
lemma runProc_cl_inv:
assumes "program_inv prog"
and "gState_inv prog g"
and "pState_inv prog p"
and "cl_inv (g,p)"
shows "cl_inv (runProc name args prog g p)"
proof -
obtain g' p' where *: "runProc name args prog g p = (g',p')"
by (metis prod.exhaust)
with runProc_gState_progress_rel[OF assms, of name args] have
"length (channels g) \<le> length (channels g')"
by (simp add: gState_progress_rel_def)
moreover from * runProc_pState_id have "p' = p" by (metis snd_conv)
ultimately show ?thesis by (metis \<open>cl_inv (g,p)\<close> * cl_inv_trans)
qed
subsection \<open>AST to edges\<close>
type_synonym ast = "AST.module list"
text \<open>In this section, the AST is translated into the transition system.\<close>
text \<open>
Handling atomic blocks is non-trivial. Therefore, we do this in an extra pass:
@{term lp} and @{term hp} are the positions of the start and the end of
the atomic block. Every edge pointing into this range is therefore marked as
@{term Atomic}. If they are pointing somewhere else, they are set to @{term InAtomic},
meaning: they start \emph{in} an atomic block, but leave it afterwards.
\<close>
definition atomize :: "nat \<Rightarrow> nat \<Rightarrow> edge list \<Rightarrow> edge list" where
"atomize lp hp es = fold (\<lambda>e es.
let e' = case target e of
LabelJump _ None \<Rightarrow>
\<comment> \<open>Labels are checked again later on, when they\<close>
\<comment> \<open>are going to be resolved. Hence it is safe to say\<close>
\<comment> \<open>\<open>atomic\<close> here, especially as the later algorithm\<close>
\<comment> \<open>relies on targets in atomic blocks to be marked as such.\<close>
e\<lparr> atomic := InAtomic \<rparr>
| LabelJump _ (Some via) \<Rightarrow>
if lp \<le> via \<and> hp \<ge> via then e\<lparr> atomic := Atomic \<rparr>
else e\<lparr> atomic := InAtomic \<rparr>
| Index p' \<Rightarrow>
if lp \<le> p' \<and> hp \<ge> p' then e\<lparr> atomic := Atomic \<rparr>
else e\<lparr> atomic := InAtomic \<rparr>
in e'#es) es []"
fun skip \<comment> \<open>No-(edge)\<close>
where
"skip (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECExpr (ExprConst 1),
effect = EEId, target = nxt, prio = pri,
atomic = NonAtomic\<rparr>]], Index pos, lbls)"
text \<open>
The AST is walked backwards. This allows to know the next state directly.
Parameters used:
\begin{description}
\item[lbls] Map of Labels
\item[pri] Current priority
\item[pos] Current position in the array
\item[nxt] Next state
\item[onxt] Previous 'next state' (where to jump after a 'do')
\item[inBlock] Needed for certain constructs to calculate the layout of the array
\end{description}
\<close>
fun stepToState
:: "step
\<Rightarrow> (labels * integer * nat * edgeIndex * edgeIndex option * bool)
\<Rightarrow> edge list list * edgeIndex * labels"
and stmntToState
:: "stmnt
\<Rightarrow> (labels * integer * nat * edgeIndex * edgeIndex option * bool)
\<Rightarrow> edge list list * edgeIndex * labels"
where
"stepToState (StepStmnt s None) data = stmntToState s data"
| "stepToState (StepStmnt s (Some u)) (lbls, pri, pos, nxt, onxt, _) = (
let
\<comment> \<open>the \<open>unless\<close> part\<close>
(ues,_,lbls') = stmntToState u (lbls, pri, pos, nxt, onxt, True);
u = last ues; ues = butlast ues;
pos' = pos + length ues;
\<comment> \<open>find minimal current priority\<close>
pri = min_prio u pri;
\<comment> \<open>the guarded part --\<close>
\<comment> \<open>priority is decreased, because there is now a new unless part with\<close>
\<comment> \<open>higher prio\<close>
(ses,spos,lbls'') = stmntToState s (lbls', pri - 1, pos', nxt, onxt, False);
\<comment> \<open>add an edge to the unless part for each generated state\<close>
ses = map (List.append u) ses
in
(ues@ses,spos,lbls''))"
| "stepToState (StepDecl decls) (lbls, pri, pos, nxt, onxt, _) = (
let edgeF = \<lambda>d (lbls,pri,pos,nxt,_).
([[\<lparr>cond = ECTrue, effect = EEDecl d, target = nxt,
prio = pri, atomic = NonAtomic\<rparr>]], Index pos, lbls)
in
step_fold edgeF decls lbls pri pos nxt onxt False)"
| "stepToState StepSkip (lbls,_,_,nxt,_) = ([],nxt,lbls)"
| "stmntToState (StmntAtomic steps) (lbls, pri, pos, nxt, onxt, inBlock) = (
let (es,pos',lbls') = step_fold stepToState steps lbls pri pos nxt onxt inBlock in
let es' = map (atomize pos (pos + length es)) es in
(es', pos', lbls'))"
| "stmntToState (StmntLabeled l s) (lbls, pri, pos, d) = (
let
(es, pos', lbls) = stmntToState s (lbls, pri, pos, d);
\<comment> \<open>We don't resolve goto-chains. If the labeled stmnt returns only a jump,\<close>
\<comment> \<open>use this goto state.\<close>
lpos = case pos' of Index p \<Rightarrow> p | _ \<Rightarrow> pos;
lbls' = add_label l lbls lpos
in
(es, pos', lbls'))"
| "stmntToState (StmntDo stepss) (lbls, pri, pos, nxt, onxt, inBlock) = (
let
\<comment> \<open>construct the different branches\<close>
\<comment> \<open>\<open>nxt\<close> in those branches points current pos (it is a loop after all)\<close>
\<comment> \<open>\<open>onxt\<close> then is the current \<open>nxt\<close> (needed for break, f.ex.)\<close>
(_,_,lbls,es,is) = step_foldL stepToState stepss lbls pri
(pos+1) (Index pos) (Some nxt);
\<comment> \<open>put the branch starting points (\<open>is\<close>) into the array\<close>
es' = concat is # es
in
if inBlock then
\<comment> \<open>inside another DO or IF or UNLESS\<close>
\<comment> \<open>\<open>\<longrightarrow>\<close> append branches again, so they can be consumed\<close>
(es' @ [concat is], Index pos, lbls)
else
(es', Index pos, lbls)
)"
| "stmntToState (StmntIf stepss) (lbls, pri, pos, nxt, onxt, _) = (
let (pos,_,lbls,es,is) = step_foldL stepToState stepss lbls pri pos nxt onxt
in (es @ [concat is], Index pos, lbls))"
| "stmntToState (StmntSeq steps) (lbls, pri, pos, nxt, onxt, inBlock) =
step_fold stepToState steps lbls pri pos nxt onxt inBlock"
| "stmntToState (StmntAssign v e) (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECTrue, effect = EEAssign v e, target = nxt, prio = pri,
atomic = NonAtomic\<rparr>]], Index pos, lbls)"
| "stmntToState (StmntAssert e) (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECTrue, effect = EEAssert e, target = nxt, prio = pri,
atomic = NonAtomic\<rparr>]], Index pos, lbls)"
| "stmntToState (StmntCond e) (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECExpr e, effect = EEId, target = nxt, prio = pri,
atomic = NonAtomic\<rparr>]], Index pos, lbls)"
| "stmntToState StmntElse (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECElse, effect = EEId, target = nxt, prio = pri,
atomic = NonAtomic \<rparr>]], Index pos, lbls)"
| "stmntToState StmntBreak (lbls,pri,_,_,Some onxt,_) =
([[\<lparr>cond = ECTrue, effect = EEGoto, target = onxt, prio = pri,
atomic = NonAtomic \<rparr>]], onxt, lbls)"
| "stmntToState StmntBreak (_,_,_,_,None,_) =
abort STR ''Misplaced break'' (\<lambda>_. ([],Index 0,lm.empty()))"
| "stmntToState (StmntRun n args) (lbls, pri, pos, nxt, onxt, _) =
([[\<lparr>cond = ECRun n, effect = EERun n args, target = nxt, prio = pri,
atomic = NonAtomic \<rparr>]], Index pos,lbls)"
| "stmntToState (StmntGoTo l) (lbls, pri, pos, _) =
([[\<lparr>cond = ECTrue, effect = EEGoto, target = LabelJump l None, prio = pri,
atomic = NonAtomic \<rparr>]], LabelJump l (Some pos), lbls)"
| "stmntToState (StmntSend v e srt) (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECSend v, effect = EESend v e srt, target = nxt, prio = pri,
atomic = NonAtomic \<rparr>]], Index pos, lbls)"
| "stmntToState (StmntRecv v r srt rem) (lbls, pri, pos, nxt, _) =
([[\<lparr>cond = ECRecv v r srt, effect = EERecv v r srt rem, target = nxt, prio = pri,
atomic = NonAtomic \<rparr>]], Index pos, lbls)"
| "stmntToState StmntSkip d = skip d"
subsubsection \<open>Setup\<close>
definition endState :: "edge list" where
\<comment> \<open>An extra state added to each process marking its end.\<close>
"endState = [\<lparr> cond = ECFalse, effect = EEEnd, target = Index 0, prio = 0,
atomic = NonAtomic\<rparr>]"
definition resolveLabel :: "String.literal \<Rightarrow> labels \<Rightarrow> nat" where
"resolveLabel l lbls = (
case lm.lookup l lbls of
None \<Rightarrow> abortv STR ''Unresolved label: '' l (\<lambda>_. 0)
| Some pos \<Rightarrow> pos)"
primrec resolveLabels :: "edge list list \<Rightarrow> labels \<Rightarrow> edge list \<Rightarrow> edge list" where
"resolveLabels _ _ [] = []"
| "resolveLabels edges lbls (e#es) = (
let check_atomic = \<lambda>pos. fold (\<lambda>e a. a \<and> inAtomic e) (edges ! pos) True in
case target e of
Index _ \<Rightarrow> e
| LabelJump l None \<Rightarrow>
let pos = resolveLabel l lbls in
e\<lparr>target := Index pos,
atomic := if inAtomic e then
if check_atomic pos then Atomic
else InAtomic
else NonAtomic \<rparr>
| LabelJump l (Some via) \<Rightarrow>
let pos = resolveLabel l lbls in
e\<lparr>target := Index pos,
\<comment> \<open>NB: \<open>isAtomic\<close> instead of \<open>inAtomic\<close>, cf \<open>atomize()\<close>\<close>
atomic := if isAtomic e then
if check_atomic pos \<and> check_atomic via then Atomic
else InAtomic
else atomic e \<rparr>
) # (resolveLabels edges lbls es)"
definition calculatePrios :: "edge list list \<Rightarrow> (integer * edge list) list" where
"calculatePrios ess = map (\<lambda>es. (min_prio es 0, es)) ess"
definition toStates :: "step list \<Rightarrow> states * edgeIndex * labels" where
"toStates steps = (
let
(states,pos,lbls) = step_fold stepToState steps (lm.empty())
0 1 (Index 0) None False;
pos = (case pos of
Index _ \<Rightarrow> pos
| LabelJump l _ \<Rightarrow> Index (resolveLabel l lbls));
states = endState # states;
states = map (resolveLabels states lbls) states;
states = calculatePrios states
in
case pos of Index s \<Rightarrow>
if s < length states then (IArray states, pos, lbls)
else abort STR ''Start index out of bounds'' (\<lambda>_. (IArray states, Index 0, lbls)))"
lemma toStates_inv:
assumes "toStates steps = (ss,start,lbls)"
shows "\<exists>s. start = Index s \<and> s < IArray.length ss"
and "IArray.length ss > 0"
using assms
unfolding toStates_def calculatePrios_def
by (auto split: prod.splits edgeIndex.splits if_splits)
(* returns: states * is_active * name * labels * process *)
primrec toProcess
:: "nat \<Rightarrow> proc \<Rightarrow> states * nat * String.literal * (labels * process)"
where
"toProcess sidx (ProcType act name args decls steps) = (
let
(states, start, lbls) = toStates steps;
act = (case act of
None \<Rightarrow> 0
| Some None \<Rightarrow> 1
| Some (Some x) \<Rightarrow> nat_of_integer x)
in
(states, act, name, lbls, sidx, start, args, decls))"
| "toProcess sidx (Init decls steps) = (
let (states, start, lbls) = toStates steps in
(states, 1, STR '':init:'', lbls, sidx, start, [], decls))"
lemma toProcess_sidx:
"toProcess sidx p = (ss,a,n,l,idx,r) \<Longrightarrow> idx = sidx"
by (cases p) (simp_all split: prod.splits)
lemma toProcess_states_nonempty:
"toProcess sidx p = (ss,a,n,l,idx,r) \<Longrightarrow> IArray.length ss > 0"
by (cases p) (force split: prod.splits dest: toStates_inv(2))+
lemma toProcess_start:
"toProcess sidx p = (ss,a,n,l,idx,start,r)
\<Longrightarrow> \<exists>s. start = Index s \<and> s < IArray.length ss"
by (cases p) (force split: prod.splits dest: toStates_inv(1))+
lemma toProcess_startE:
assumes "toProcess sidx p = (ss,a,n,l,idx,start,r)"
obtains s where "start = Index s" "s < IArray.length ss"
using toProcess_start[OF assms]
by blast
text \<open>
The main construction function. Takes an AST
and returns an initial state,
and the program (= transition system).
\<close>
definition setUp :: "ast \<Rightarrow> program \<times> gState" where
"setUp ast = (
let
(decls, procs, _) = preprocess ast;
assertVar = Var (VTBounded 0 1) 0;
pre_procs = map (case_prod toProcess) (List.enumerate 1 procs);
procs = IArray ((0, Index 0, [], []) # map (\<lambda>(_,_,_,_,p). p) pre_procs);
labels = IArray (lm.empty() # map (\<lambda>(_,_,_,l,_). l) pre_procs);
states = IArray (IArray [(0,[])] # map (\<lambda>(s,_). s) pre_procs);
names = IArray (STR ''invalid'' # map (\<lambda>(_,_,n,_). n) pre_procs);
proc_data = lm.to_map (map (\<lambda>(_,_,n,_,idx,_). (n,idx)) pre_procs);
prog = \<lparr> processes = procs, labels = labels, states = states,
proc_names = names, proc_data = proc_data \<rparr>;
g = \<lparr> vars = lm.sng (STR ''__assert__'') assertVar,
channels = [InvChannel], timeout = False, procs = [] \<rparr>;
g' = foldl (\<lambda>g d.
fst (mkVarChannel d (apfst \<circ> gState.vars_update) g emptyProc)
) g decls;
g'' = foldl (\<lambda>g (_,a,name,_).
foldl (\<lambda>g name.
fst (runProc name [] prog g emptyProc)
) g (replicate a name)
) g' pre_procs
in
(prog, g''))"
lemma setUp_program_inv':
"program_inv (fst (setUp ast))"
proof (rule program_invI, goal_cases)
case 1 show ?case by (simp add: setUp_def split: prod.split)
next
case 2 show ?case by (simp add: setUp_def split: prod.split)
next
case 3 thus ?case
by (auto simp add: setUp_def o_def
split: prod.splits
dest!: toProcess_states_nonempty)
next
case 4 thus ?case
unfolding setUp_def
by (auto simp add: lm.correct o_def in_set_enumerate_eq nth_enumerate_eq
dest!: subsetD[OF Misc.ran_map_of] toProcess_sidx
split: prod.splits)
(* TODO: Change name Misc.ran_map_of \<longrightarrow> ran_map_of_ss, as it collides
with AList.ran_map_of *)
next
case 5 thus ?case
apply (auto simp add: setUp_def o_def split: prod.splits)
apply (frule toProcess_sidx)
apply (frule toProcess_start)
apply (auto simp: in_set_enumerate_eq nth_enumerate_eq)
done
qed
lemma setUp_program_inv:
assumes "setUp ast = (prog,g)"
shows "program_inv prog"
using assms setUp_program_inv'
by (metis fst_conv)
lemma setUp_gState_inv:
assumes "setUp ast = (prog, g)"
shows "gState_inv prog g"
proof -
from assms have p_INV: "program_inv prog" by (fact setUp_program_inv)
{
fix prog :: program
assume *: "program_inv prog"
let ?g = "\<lparr> vars = lm.sng (STR ''__assert__'') (Var (VTBounded 0 1) 0),
channels = [InvChannel], timeout = False, procs = [] \<rparr>"
have g1: "gState_inv prog ?g"
by (simp add: gState_inv_def max_channels_def lm_correct max_var_value_def)
{
fix g decls
assume "gState_inv prog g"
hence "gState_inv prog (foldl (\<lambda>g d.
fst (mkVarChannel d (apfst \<circ> gState.vars_update) g emptyProc)
) g decls)"
apply (rule foldl_rule)
apply (intro mkVarChannel_gState_inv)
apply simp
apply (frule_tac g=\<sigma> in toVariable_variable_inv')
apply assumption
apply (auto simp add: gState_inv_def lm.correct)
done
}
note g2 = this[OF g1]
{
fix g :: "'a gState_scheme" and pre_procs
assume "gState_inv prog g"
hence "gState_inv prog (foldl (\<lambda>g (_,a,name,_).
foldl (\<lambda>g name.
fst (runProc name [] prog g emptyProc)
) g (replicate a name)
) g pre_procs)"
apply (rule foldl_rule)
apply (clarsimp split: prod.splits)
apply (rule foldl_rule)
apply (auto intro!: runProc_gState_inv emptyProc_pState_inv *)
done
}
note this[OF g2]
} note g_INV = this
from assms p_INV show ?thesis
unfolding setUp_def
by (auto split: prod.splits intro!: g_INV)
qed
subsection \<open>Semantic Engine\<close>
text \<open>
After constructing the transition system, we are missing the final part:
The successor function on this system. We use SPIN-nomenclature and call it
\emph{semantic engine}.
\<close>
definition "assertVar \<equiv> VarRef True (STR ''__assert__'') None"
subsubsection \<open>Evaluation of Edges\<close>
fun evalRecvArgs
:: "recvArg list \<Rightarrow> integer list \<Rightarrow> gState\<^sub>I \<Rightarrow> pState \<Rightarrow> gState\<^sub>I * pState"
where
"evalRecvArgs [] [] g l = (g,l)"
| "evalRecvArgs _ [] g l =
abort STR ''Length mismatch on receiving.'' (\<lambda>_. (g,l))"
| "evalRecvArgs [] _ g l =
abort STR ''Length mismatch on receiving.'' (\<lambda>_. (g,l))"
| "evalRecvArgs (r#rs) (v#vs) g l = (
let (g,l) =
case r of
RecvArgVar var \<Rightarrow> setVar var v g l
| _ \<Rightarrow> (g,l)
in evalRecvArgs rs vs g l)"
primrec evalCond
:: "edgeCond \<Rightarrow> gState\<^sub>I \<Rightarrow> pState \<Rightarrow> bool"
where
"evalCond ECTrue _ _ \<longleftrightarrow> True"
| "evalCond ECFalse _ _ \<longleftrightarrow> False"
| "evalCond (ECExpr e) g l \<longleftrightarrow> exprArith g l e \<noteq> 0"
| "evalCond (ECRun _) g l \<longleftrightarrow> length (procs g) < 255"
| "evalCond ECElse g l \<longleftrightarrow> gState\<^sub>I.else g"
| "evalCond (ECSend v) g l \<longleftrightarrow>
withChannel v (\<lambda>_ c.
case c of
Channel cap _ q \<Rightarrow> integer_of_nat (length q) < cap
| HSChannel _ \<Rightarrow> True) g l"
| "evalCond (ECRecv v rs srt) g l \<longleftrightarrow>
withChannel v (\<lambda>i c.
case c of
HSChannel _ \<Rightarrow> handshake g \<noteq> 0 \<and> recvArgsCheck g l rs (hsdata g)
| _ \<Rightarrow> pollCheck g l c rs srt) g l"
fun evalHandshake
:: "edgeCond \<Rightarrow> nat \<Rightarrow> gState\<^sub>I \<Rightarrow> pState \<Rightarrow> bool"
where
"evalHandshake (ECRecv v _ _) h g l
\<longleftrightarrow> h = 0
\<or> withChannel v (\<lambda>i c. case c of
HSChannel _ \<Rightarrow> i = h
| Channel _ _ _ \<Rightarrow> False) g l"
| "evalHandshake _ h _ _ \<longleftrightarrow> h = 0"
primrec evalEffect
:: "edgeEffect \<Rightarrow> program \<Rightarrow> gState\<^sub>I \<Rightarrow> pState \<Rightarrow> gState\<^sub>I * pState"
where
"evalEffect EEEnd _ g l = (g,l)"
| "evalEffect EEId _ g l = (g,l)"
| "evalEffect EEGoto _ g l = (g,l)"
| "evalEffect (EEAssign v e) _ g l = setVar v (exprArith g l e) g l"
| "evalEffect (EEDecl d) _ g l = mkVarChannelProc d g l"
| "evalEffect (EERun name args) prog g l = runProc name args prog g l"
| "evalEffect (EEAssert e) _ g l = (
if exprArith g l e = 0
then setVar assertVar 1 g l
else (g,l))"
| "evalEffect (EESend v es srt) _ g l = withChannel v (\<lambda>i c.
let
ab = \<lambda>_. abort STR ''Length mismatch on sending.'' (\<lambda>_. (g,l));
es = map (exprArith g l) es
in
if \<not> for_all (\<lambda>x. x \<ge> min_var_value \<and> x \<le> max_var_value) es
then abort STR ''Invalid Channel'' (\<lambda>_. (g,l))
else
case c of
Channel cap ts q \<Rightarrow>
if length ts \<noteq> length es \<or> \<not> (length q < max_array_size)
then ab()
else let
q' = if \<not> srt then q@[es]
else let
q = map lexlist q;
q' = insort (lexlist es) q
in map unlex q';
g = gState.channels_update (\<lambda>cs.
cs[ i := Channel cap ts q' ]) g
in (g,l)
| HSChannel ts \<Rightarrow>
if length ts \<noteq> length es then ab()
else (g\<lparr>hsdata := es, handshake := i\<rparr>, l)
| InvChannel \<Rightarrow> abort STR ''Trying to send on invalid channel'' (\<lambda>_. (g,l))
) g l"
| "evalEffect (EERecv v rs srt rem) _ g l = withChannel v (\<lambda>i c.
case c of
Channel cap ts qs \<Rightarrow>
if qs = [] then abort STR ''Recv from empty channel'' (\<lambda>_. (g,l))
else
let
(q', qs') = if \<not> srt then (hd qs, tl qs)
else apfst the (find_remove (recvArgsCheck g l rs) qs);
(g,l) = evalRecvArgs rs q' g l;
g = if rem
then gState.channels_update (\<lambda>cs. cs[ i := Channel cap ts qs']) g
else g
\<comment> \<open>messages are not removed -- so no need to update anything\<close>
in (g,l)
| HSChannel _ \<Rightarrow>
let (g,l) = evalRecvArgs rs (hsdata g) g l in
let g = g\<lparr> handshake := 0, hsdata := [] \<rparr>
in (g,l)
| InvChannel \<Rightarrow> abort STR ''Receiving on invalid channel'' (\<lambda>_. (g,l))
) g l"
lemma statesDecls_effect:
assumes "ef \<in> effect ` edgeSet ss"
and "ef = EEDecl d"
shows "d \<in> statesDecls ss"
proof -
from assms obtain e where "e \<in> edgeSet ss" "ef = effect e" by auto
thus ?thesis using assms
unfolding statesDecls_def
by (auto simp add: edgeDecls_def
intro!: bexI[where x = e]
split: edgeEffect.split)
qed
lemma evalRecvArgs_pState_inv:
assumes "pState_inv prog p"
shows "pState_inv prog (snd (evalRecvArgs rargs xs g p))"
using assms
proof (induction rargs xs arbitrary: p g rule: list_induct2')
case (4 r rs x xs) thus ?case
proof (cases r)
case (RecvArgVar v)
obtain g' p' where new: "setVar v x g p = (g',p')" by (metis prod.exhaust)
hence "p' = snd (setVar v x g p)" by simp
with "4" have "pState_inv prog p'" by (auto intro!: setVar_pState_inv)
from "4.IH"[OF this] RecvArgVar new show ?thesis by simp
qed simp_all
qed simp_all
lemma evalRecvArgs_pState_inv':
assumes "evalRecvArgs rargs xs g p = (g', p')"
and "pState_inv prog p"
shows "pState_inv prog p'"
using assms evalRecvArgs_pState_inv
by (metis snd_conv)
lemma evalRecvArgs_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, fst (evalRecvArgs rargs xs g p)) \<in> gState_progress_rel prog"
using assms
proof (induction rargs xs arbitrary: p g rule: list_induct2')
case (4 r rs x xs) thus ?case
proof (cases r)
case (RecvArgVar v)
obtain g' p' where new: "setVar v x g p = (g',p')" by (metis prod.exhaust)
hence "g' = fst (setVar v x g p)" by simp
with "4" have "(g, g') \<in> gState_progress_rel prog"
by (auto intro!: setVar_gState_progress_rel)
also hence "gState_inv prog g'"
by (rule gState_progress_rel_gState_invI2)
note "4.IH"[OF this, of p']
finally show ?thesis using RecvArgVar new by simp
qed simp_all
qed simp_all
lemmas evalRecvArgs_gState_inv =
evalRecvArgs_gState_progress_rel[THEN gState_progress_rel_gState_invI2]
lemma evalRecvArgs_cl_inv:
assumes "cl_inv (g,p)"
shows "cl_inv (evalRecvArgs rargs xs g p)"
using assms
proof (induction rargs xs arbitrary: p g rule: list_induct2')
case (4 r rs x xs) thus ?case
proof (cases r)
case (RecvArgVar v)
with 4 have "cl_inv (setVar v x g p)"
by (auto intro!: setVar_cl_inv)
with "4.IH" RecvArgVar show ?thesis
by (auto split: prod.splits)
qed simp_all
qed simp_all
lemma evalEffect_pState_inv:
assumes "pState_inv prog p"
and "gState_inv prog g"
and "cl_inv (g,p)"
and "e \<in> effect ` edgeSet (states prog !! pState.idx p)"
shows "pState_inv prog (snd (evalEffect e prog g p))"
using assms
proof (cases e)
case (EEDecl d)
with assms have "d \<in> statesDecls (states prog !! pState.idx p)"
using statesDecls_effect
by simp
with assms EEDecl show ?thesis
by (auto simp del: IArray.sub_def
intro!: mkVarChannelProc_pState_inv)
next
case (EESend c es srt)
then obtain v where "ChanRef v = c" by (cases c) simp
with EESend assms show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def split: channel.split)
next
case (EERecv c es srt)
then obtain v where "ChanRef v = c" by (cases c) simp
with EERecv assms show ?thesis
by (cases v)
(auto simp: withChannel'_def withVar'_def
split: prod.splits channel.split
dest: evalRecvArgs_pState_inv')
qed (clarsimp_all intro!: setVar_pState_inv runProc_pState_inv)
lemma evalEffect_gState_progress_rel:
assumes "program_inv prog"
and "gState_inv prog g"
and "pState_inv prog p"
and "cl_inv (g,p)"
shows "(g, fst (evalEffect e prog g p)) \<in> gState_progress_rel prog"
using assms
proof (cases e)
case EEAssert
with assms show ?thesis
by (auto intro: setVar_gState_progress_rel)
next
case EEAssign
with assms show ?thesis
by (auto intro: setVar_gState_progress_rel)
next
case EEDecl
with assms show ?thesis
by (auto intro: mkVarChannelProc_gState_progress_rel)
next
case EERun
with assms show ?thesis
by (auto intro: runProc_gState_progress_rel)
next
case (EESend c es srt)
then obtain v where v: "c = ChanRef v" by (metis chanRef.exhaust)
obtain idx where idx: "nat_of_integer (the (getVar v g p)) = idx" by blast
note idx' = idx[symmetric, unfolded getVar_def]
show ?thesis
proof (cases "idx < length (gState.channels g)")
case True
note DEF = True EESend v idx' assms
show ?thesis
proof (cases "gState.channels g ! idx")
case (Channel cap ts q)
with True have "Channel cap ts q \<in> set (gState.channels g)"
by (metis nth_mem)
with assms have "channel_inv (Channel cap ts q)"
by (auto simp add: gState_inv_def simp del: channel_inv.simps)
with Channel DEF show ?thesis
by (cases v)
(auto simp add: withChannel'_def withVar'_def for_all_def
split: channel.split
intro!: gState_progress_rel_channels_update)
next
case HSChannel with DEF show ?thesis
by (cases v)
(auto simp: withChannel'_def withVar'_def gState_progress_rel_def
gState_inv_def
split: channel.split)
next
case InvChannel with DEF show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def)
qed
next
case False with EESend idx' v assms show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def)
qed
next
case (EERecv c rs srt rem)
then obtain v where v: "c = ChanRef v" by (metis chanRef.exhaust)
obtain idx where idx: "nat_of_integer (the (getVar v g p)) = idx" by blast
note idx' = idx[symmetric, unfolded getVar_def]
show ?thesis
proof (cases "idx < length (gState.channels g)")
case True
note DEF = True EERecv v idx' assms
show ?thesis
proof (cases "gState.channels g ! idx")
note channel_inv.simps[simp del]
case (Channel cap ts q)
with True have "Channel cap ts q \<in> set (gState.channels g)"
by (metis nth_mem)
with assms have c_inv: "channel_inv (Channel cap ts q)"
by (auto simp add: gState_inv_def simp del: channel_inv.simps)
moreover obtain res q' where
"apfst the (find_remove (recvArgsCheck g p rs) q) = (res, q')"
by (metis prod.exhaust)
moreover hence "q' = snd (find_remove (recvArgsCheck g p rs) q)"
by (simp add: apfst_def map_prod_def split: prod.splits)
with find_remove_subset find_remove_length have
"set q' \<subseteq> set q" "length q' \<le> length q"
by (metis surjective_pairing)+
with c_inv have "channel_inv (Channel cap ts q')"
by (auto simp add: channel_inv.simps)
moreover {
assume "q \<noteq> []"
hence "set (tl q) \<subseteq> set q" using tl_subset by auto
with c_inv have "channel_inv (Channel cap ts (tl q))"
by (auto simp add: channel_inv.simps)
}
moreover {
fix res g' p'
assume "evalRecvArgs rs res g p = (g',p')"
with evalRecvArgs_gState_progress_rel assms have
"(g,g') \<in> gState_progress_rel prog"
by (metis fst_conv)
hence "length (channels g) \<le> length (channels g')"
by (simp add: gState_progress_rel_def)
}
ultimately show ?thesis using Channel DEF
apply (cases v)
apply (auto simp add: withChannel'_def withVar'_def for_all_def
split: channel.split prod.split
elim: fstE
intro!: evalRecvArgs_gState_progress_rel
gState_progress_rel_channels_update_step)
apply force+
done
next
case HSChannel
obtain g' p' where *: "evalRecvArgs rs (hsdata g) g p = (g',p')"
by (metis prod.exhaust)
with assms have "(g,g') \<in> gState_progress_rel prog"
by (auto elim!: fstE intro!: evalRecvArgs_gState_progress_rel)
also hence "gState_inv prog g'" by blast
hence "(g',g'\<lparr>handshake := 0, hsdata := []\<rparr>) \<in> gState_progress_rel prog"
by (auto simp add: gState_progress_rel_def gState_inv_def)
finally
have "(g,g'\<lparr>handshake := 0, hsdata := []\<rparr>) \<in> gState_progress_rel prog" .
with DEF HSChannel * show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def for_all_def
split: channel.split prod.split)
next
case InvChannel with DEF show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def)
qed
next
case False with EERecv idx' v assms show ?thesis
by (cases v) (auto simp add: withChannel'_def withVar'_def)
qed
qed simp_all
lemma evalEffect_cl_inv:
assumes "cl_inv (g,p)"
and "program_inv prog"
and "gState_inv prog g"
and "pState_inv prog p"
shows "cl_inv (evalEffect e prog g p)"
using assms
proof (cases e)
case EERun with assms show ?thesis by (force intro!: runProc_cl_inv)
next
case (EESend c es srt) then obtain v where "ChanRef v = c" by (cases c) simp
with EESend assms show ?thesis
by (cases v)
(auto simp add: withChannel'_def withVar'_def split: channel.split
intro!: cl_inv_channels_update)
next
case (EERecv c es srt) then obtain v where "ChanRef v = c" by (cases c) simp
with EERecv assms show ?thesis
apply (cases v)
apply (auto simp add: withChannel'_def withVar'_def split: channel.split prod.split
intro!: cl_inv_channels_update)
apply (metis evalRecvArgs_cl_inv)+
done
qed (simp_all add: setVar_cl_inv mkVarChannelProc_cl_inv)
subsubsection \<open>Executable edges\<close>
text \<open>
To find a successor global state, we first need to find all those edges which are executable
(\ie the condition evaluates to true).
\<close>
type_synonym choices = "(edge * pState) list"
\<comment> \<open>A choice is an executable edge and the process it belongs to.\<close>
definition getChoices :: "gState\<^sub>I \<Rightarrow> pState \<Rightarrow> edge list \<Rightarrow> choices" where
"getChoices g p = foldl (\<lambda>E e.
if evalHandshake (cond e) (handshake g) g p \<and> evalCond (cond e) g p
then (e,p)#E
else E) []"
lemma getChoices_sub_edges_fst:
"fst ` set (getChoices g p es) \<subseteq> set es"
unfolding getChoices_def
by (rule foldl_rule_aux) auto
lemma getChoices_sub_edges:
"(a,b) \<in> set (getChoices g p es) \<Longrightarrow> a \<in> set es"
using getChoices_sub_edges_fst
by force
lemma getChoices_p_snd:
"snd ` set (getChoices g p es) \<subseteq> {p}"
unfolding getChoices_def
by (rule foldl_rule_aux) auto
lemma getChoices_p:
"(a,b) \<in> set (getChoices g p es) \<Longrightarrow> b = p"
using getChoices_p_snd
by force
definition sort_by_pri where
"sort_by_pri min_pri edges = foldl (\<lambda>es e.
let idx = nat_of_integer (abs (prio e))
in if idx > min_pri
then abort STR ''Invalid priority'' (\<lambda>_. es)
else let ep = e # (es ! idx) in es[idx := ep]
) (replicate (min_pri + 1) []) edges"
lemma sort_by_pri_edges':
assumes "set edges \<subseteq> A"
shows "set (sort_by_pri min_pri edges) \<subseteq> {xs. set xs \<subseteq> A}"
using assms
unfolding sort_by_pri_def
apply (rule_tac I="\<lambda>\<sigma> _. (\<forall>x \<in> set \<sigma>. set x \<subseteq> A) \<and> length \<sigma> = min_pri + 1" in foldl_rule_aux_P)
apply simp
apply (force dest!: subsetD[OF set_update_subset_insert]
split: if_splits)
apply force
done
lemma sort_by_pri_edges:
assumes "set edges \<subseteq> A"
and "es \<in> set (sort_by_pri min_pri edges)"
shows "set es \<subseteq> A"
using sort_by_pri_edges'[OF assms(1)] assms
by auto
lemma sort_by_pri_length:
"length (sort_by_pri min_pri edges) = min_pri + 1"
unfolding sort_by_pri_def
by (rule foldl_rule_aux_P [where I="\<lambda>\<sigma> _. length \<sigma> = min_pri + 1"])
simp_all
definition executable
:: "states iarray \<Rightarrow> gState\<^sub>I \<Rightarrow> choices nres"
\<comment> \<open>Find all executable edges\<close>
where
"executable ss g = (
let procs = procs g in
nfoldli procs (\<lambda>_. True) (\<lambda>p E.
if (exclusive g = 0 \<or> exclusive g = pid p) then do {
let (min_pri, edges) = (ss !! pState.idx p) !! pc p;
ASSERT(set edges \<subseteq> edgeSet (ss !! pState.idx p));
(E',_,_) \<leftarrow>
if min_pri = 0 then do {
WHILE\<^sub>T (\<lambda>(E,brk,_). E = [] \<and> brk = 0) (\<lambda> (_, _, ELSE). do {
let g = g\<lparr>gState\<^sub>I.else := ELSE\<rparr>;
E = getChoices g p edges
in
if E = [] then (
if \<not> ELSE then RETURN (E, 0::nat, True)
else RETURN (E, 1, False))
else RETURN (E, 1, ELSE) }) ([], 0::nat, False)
} else do {
let min_pri = nat_of_integer (abs min_pri);
let pri_edges = sort_by_pri min_pri edges;
ASSERT (\<forall>es \<in> set pri_edges.
set es \<subseteq> edgeSet (ss !! pState.idx p));
let pri_edges = IArray pri_edges;
WHILE\<^sub>T (\<lambda>(E,pri,_). E = [] \<and> pri \<le> min_pri) (\<lambda>(_, pri, ELSE). do {
let es = pri_edges !! pri;
let g = g\<lparr>gState\<^sub>I.else := ELSE\<rparr>;
let E = getChoices g p es;
if E = [] then (
if \<not> ELSE then RETURN (E,pri,True)
else RETURN (E, pri + 1, False))
else RETURN (E, pri, ELSE) }) ([], 0, False)
};
RETURN (E'@E)
} else RETURN E
) []
)"
definition
"while_rel1 =
measure (\<lambda>x. if x = [] then 1 else 0)
<*lex*> measure (\<lambda>x. if x = 0 then 1 else 0)
<*lex*> measure (\<lambda>x. if \<not> x then 1 else 0)"
lemma wf_while_rel1:
"wf while_rel1"
unfolding while_rel1_def
by auto
definition
"while_rel2 mp =
measure (\<lambda>x. if x = [] then 1 else 0)
<*lex*> measure (\<lambda>x. (mp + 1) - x)
<*lex*> measure (\<lambda>x. if \<not> x then 1 else 0)"
lemma wf_while_rel2:
"wf (while_rel2 mp)"
unfolding while_rel2_def
by auto
lemma executable_edgeSet:
assumes "gState_inv prog g"
and "program_inv prog"
and "ss = states prog"
shows "executable ss g
\<le> SPEC (\<lambda>cs. \<forall>(e,p) \<in> set cs.
e \<in> edgeSet (ss !! pState.idx p)
\<and> pState_inv prog p
\<and> cl_inv (g,p))"
unfolding executable_def
using assms
apply (refine_rcg refine_vcg nfoldli_rule[where
I="\<lambda>_ _ cs. \<forall>(e,p) \<in> set cs.
e \<in> edgeSet (ss !! pState.idx p)
\<and> pState_inv prog p
\<and> cl_inv (g,p)"])
apply simp
apply (rename_tac p l1 l2 \<sigma> e p')
apply (subgoal_tac "pState_inv prog p")
apply (clarsimp simp add: edgeSet_def pState_inv_def)[]
apply (rule_tac x="IArray.list_of
(IArray.list_of (states prog) ! pState.idx p) ! pc p" in bexI)
apply simp
apply (force intro!: nth_mem)
apply (force simp add: gState_inv_def)
apply (refine_rcg refine_vcg wf_while_rel1 WHILET_rule[where
I="\<lambda>(cs,_,_). \<forall>(e,p) \<in> set cs.
e \<in> edgeSet (ss !! pState.idx p)
\<and> pState_inv prog p
\<and> cl_inv (g,p)"
and R=while_rel1])
apply (vc_solve solve: asm_rl simp add: while_rel1_def)
apply (frule getChoices_p)
using getChoices_sub_edges apply (force simp add: gState_inv_def)
using sort_by_pri_edges apply fastforce
apply (rename_tac min_pri pri_edges)
apply (rule_tac I="\<lambda>(cs,_,_). \<forall>(e,p) \<in> set cs.
e \<in> edgeSet (ss !! pState.idx p)
\<and> pState_inv prog p
\<and> cl_inv (g,p)"
and R="while_rel2 (nat_of_integer (abs min_pri))"
in WHILET_rule)
apply (simp add: wf_while_rel2)
apply simp
apply (refine_rcg refine_vcg)
apply (clarsimp_all split: prod.split simp add: while_rel2_def)
apply (metis diff_less_mono lessI)
apply (rename_tac idx' else e p')
apply (frule getChoices_p)
apply (frule getChoices_sub_edges)
apply (subgoal_tac
"sort_by_pri (nat_of_integer \<bar>min_pri\<bar>) pri_edges ! idx'
\<in> set (sort_by_pri (nat_of_integer \<bar>min_pri\<bar>) pri_edges)")
apply (auto simp add: assms gState_inv_def)[]
apply (force simp add: sort_by_pri_length)
apply (auto simp add: assms)
done
lemma executable_edgeSet':
assumes "gState_inv prog g"
and "program_inv prog"
shows "executable (states prog) g
\<le> SPEC (\<lambda>cs. \<forall>(e,p) \<in> set cs.
e \<in> edgeSet ((states prog) !! pState.idx p)
\<and> pState_inv prog p
\<and> cl_inv(g,p))"
using executable_edgeSet[where ss = "states prog"] assms
by simp
schematic_goal executable_refine:
"RETURN (?ex s g) \<le> executable s g"
unfolding executable_def
by (refine_transfer)
concrete_definition executable_impl for s g uses executable_refine
subsubsection \<open>Successor calculation\<close>
function to\<^sub>I where
"to\<^sub>I \<lparr> gState.vars = v, channels = ch, timeout = t, procs = p \<rparr>
= \<lparr> gState.vars = v, channels = ch, timeout = False, procs = p,
handshake = 0, hsdata = [], exclusive = 0, gState\<^sub>I.else = False \<rparr>"
by (metis gState.cases) (metis gState.ext_inject)
termination by lexicographic_order
function "from\<^sub>I" where
"from\<^sub>I \<lparr> gState.vars = v, channels = ch, timeout = t, procs = p, \<dots> = m \<rparr>
= \<lparr> gState.vars = v, channels = ch, timeout = t, procs = p \<rparr>"
by (metis gState.surjective) (metis gState.ext_inject)
termination by lexicographic_order
function reset\<^sub>I where
"reset\<^sub>I \<lparr> gState.vars = v, channels = ch, timeout = t, procs = p,
handshake = hs, hsdata = hsd, exclusive = _, gState\<^sub>I.else = _ \<rparr>
= \<lparr> gState.vars = v, channels = ch, timeout = False, procs = p,
handshake = 0, hsdata = if hs \<noteq> 0 then hsd else [], exclusive = 0,
gState\<^sub>I.else = False \<rparr>"
by (metis (full_types) gState\<^sub>I.surjective unit.exhaust)
(metis gState.select_convs gState\<^sub>I.select_convs)
termination by lexicographic_order
lemma gState_inv_to\<^sub>I:
"gState_inv prog g = gState_inv prog (to\<^sub>I g)"
by (cases g, simp add: gState_inv_def cl_inv_def)
lemma gState_inv_from\<^sub>I:
"gState_inv prog g = gState_inv prog (from\<^sub>I g)"
by (cases g, simp add: gState_inv_def cl_inv_def)
lemma gState_inv_reset\<^sub>I:
"gState_inv prog g = gState_inv prog (reset\<^sub>I g)"
by (cases g, simp add: gState_inv_def cl_inv_def)
lemmas gState_inv_I_simps =
gState_inv_to\<^sub>I gState_inv_from\<^sub>I gState_inv_reset\<^sub>I
definition removeProcs
\<comment> \<open>Remove ended processes, if there is no running one with a higher pid.\<close>
where
"removeProcs ps = foldr (\<lambda>p (dead,sd,ps,dcs).
if dead \<and> pc p = 0 then (True, True, ps, pState.channels p @ dcs)
else (False, sd, p#ps, dcs)) ps (True, False, [], [])"
lemma removeProcs_subset':
"set (fst (snd (snd (removeProcs ps)))) \<subseteq> set ps"
unfolding removeProcs_def
apply (subst foldr_conv_foldl)
apply (rule foldl_rule_aux_P[where I="\<lambda>(_,_,ps',_) _. set ps' \<subseteq> set ps"])
apply simp
apply (clarsimp split: if_splits)
apply force
apply (rename_tac p)
apply (case_tac "p = x")
apply (subst set_rev[symmetric])
apply simp
apply force
apply force
done
lemma removeProcs_length':
"length (fst (snd (snd (removeProcs ps)))) \<le> length ps"
unfolding removeProcs_def
apply (subst foldr_conv_foldl)
apply (rule foldl_rule_aux_P[where
I="\<lambda>(_,_,ps',_) ps''. length ps' + length ps'' \<le> length ps"])
apply (auto split: if_splits)
done
lemma removeProcs_subset:
"removeProcs ps = (dead,sd,ps',dcs) \<Longrightarrow> set ps' \<subseteq> set ps"
using removeProcs_subset'
by (metis fst_conv snd_conv)
lemma removeProcs_length:
"removeProcs ps = (dead,sd,ps',dcs) \<Longrightarrow> length ps' \<le> length ps"
using removeProcs_length'
by (metis fst_conv snd_conv)
definition cleanChans :: "integer list \<Rightarrow> channels \<Rightarrow> channels"
\<comment> \<open>Mark channels of closed processes as invalid.\<close>
where
"cleanChans dchans cs = snd (foldl (\<lambda>(i,cs) c.
if List.member dchans i then (i + 1, cs@[InvChannel])
else (i + 1, cs@[c])) (0, []) cs)"
lemma cleanChans_channel_inv:
assumes "set cs \<subseteq> Collect channel_inv"
shows "set (cleanChans dchans cs) \<subseteq> Collect channel_inv"
using assms
unfolding cleanChans_def
apply (rule_tac foldl_rule_aux)
apply (force split: if_splits)+
done
lemma cleanChans_length:
"length (cleanChans dchans cs) = length cs"
unfolding cleanChans_def
by (rule foldl_rule_aux_P[where
I="\<lambda>(_,cs') cs''. length cs' + length cs'' = length cs"])
(force split: if_splits)+
definition checkDeadProcs :: "'a gState_scheme \<Rightarrow> 'a gState_scheme" where
"checkDeadProcs g = (
let (_, soDied, procs, dchans) = removeProcs (procs g) in
if soDied then
g\<lparr> procs := procs, channels := cleanChans dchans (channels g)\<rparr>
else g)"
lemma checkDeadProcs_gState_progress_rel:
assumes "gState_inv prog g"
shows "(g, checkDeadProcs g) \<in> gState_progress_rel prog"
using assms cleanChans_length[where cs="channels g"]
cleanChans_channel_inv[where cs="channels g"]
unfolding checkDeadProcs_def
apply (intro gState_progress_relI)
apply assumption
apply (clarsimp split: if_splits prod.splits)
apply (frule removeProcs_length)
apply (frule removeProcs_subset)
apply (auto simp add: gState_inv_def cl_inv_def)[]
apply (clarsimp split: if_splits prod.splits)+
done
lemma gState_progress_rel_exclusive:
"(g, g') \<in> gState_progress_rel prog
\<Longrightarrow> (g, g'\<lparr>exclusive := p\<rparr>) \<in> gState_progress_rel prog"
by (simp add: gState_progress_rel_def gState_inv_def cl_inv_def)
definition applyEdge
:: "program \<Rightarrow> edge \<Rightarrow> pState \<Rightarrow> gState\<^sub>I \<Rightarrow> gState\<^sub>I nres"
where
"applyEdge prog e p g = do {
let (g',p') = evalEffect (effect e) prog g p;
ASSERT ((g,g') \<in> gState_progress_rel prog);
ASSERT (pState_inv prog p');
ASSERT (cl_inv (g',p'));
let p'' = (case target e of Index t \<Rightarrow>
if t < IArray.length (states prog !! pState.idx p') then p'\<lparr>pc := t\<rparr>
else abort STR ''Edge target out of bounds'' (\<lambda>_. p')
| _ \<Rightarrow> abort STR ''Edge target not Index'' (\<lambda>_. p'));
ASSERT (pState_inv prog p'');
let g'' = g'\<lparr>procs := list_update (procs g') (pid p'' - 1) p''\<rparr>;
ASSERT ((g',g'') \<in> gState_progress_rel prog);
let g''' = (if isAtomic e \<and> handshake g'' = 0
then g''\<lparr> exclusive := pid p'' \<rparr>
else g'');
ASSERT ((g',g''') \<in> gState_progress_rel prog);
let g\<^sub>f = (if pc p'' = 0 then checkDeadProcs g''' else g''');
ASSERT ((g''',g\<^sub>f) \<in> gState_progress_rel prog);
RETURN g\<^sub>f }"
lemma applyEdge_gState_progress_rel:
assumes "program_inv prog"
and "gState_inv prog g"
and "pState_inv prog p"
and "cl_inv (g,p)"
and "e \<in> edgeSet (states prog !! pState.idx p)"
shows "applyEdge prog e p g \<le> SPEC (\<lambda>g'. (g,g') \<in> gState_progress_rel prog)"
using assms
unfolding applyEdge_def
apply (intro refine_vcg)
apply (force elim: fstE intro!: evalEffect_gState_progress_rel)
apply (force elim: sndE intro!: evalEffect_pState_inv)
apply (drule subst)
apply (rule evalEffect_cl_inv)
apply assumption+
apply (cases "target e")
apply (clarsimp simp add: pState_inv_def)
apply simp
apply (frule gState_progress_rel_gState_invI2)
apply (cases "target e")
apply (clarsimp split: if_splits)
apply (intro gState_progress_relI)
apply assumption
apply (auto simp add: gState_inv_def cl_inv_def
dest!: subsetD[OF set_update_subset_insert])[]
apply (simp add: cl_inv_def)
apply simp
apply (intro gState_progress_relI)
apply assumption
apply (auto simp add: gState_inv_def cl_inv_def
dest!: subsetD[OF set_update_subset_insert])[]
apply (simp add: cl_inv_def)
apply simp
apply (clarsimp split: if_splits)
apply (intro gState_progress_relI)
apply assumption
apply (auto simp add: gState_inv_def cl_inv_def
dest!: subsetD[OF set_update_subset_insert])[]
apply (simp add: cl_inv_def)
apply simp
apply (auto split: if_splits intro!: gState_progress_rel_exclusive)[]
apply (force intro!: checkDeadProcs_gState_progress_rel)
apply (blast intro!: gState_progress_rel_trans)
done
schematic_goal applyEdge_refine:
"RETURN (?ae prog e p g) \<le> applyEdge prog e p g"
unfolding applyEdge_def
by (refine_transfer)
concrete_definition applyEdge_impl for e p g uses applyEdge_refine
definition nexts
:: "program \<Rightarrow> gState \<Rightarrow> gState ls nres"
\<comment> \<open>The successor function\<close>
where
"nexts prog g = (
let
f = from\<^sub>I;
g = to\<^sub>I g
in
REC (\<lambda>D g. do {
E \<leftarrow> executable (states prog) g;
if E = [] then
if handshake g \<noteq> 0 then
\<comment> \<open>HS not possible -- remove current step\<close>
RETURN (ls.empty())
else if exclusive g \<noteq> 0 then
\<comment> \<open>Atomic blocks -- just return current state\<close>
RETURN (ls.sng (f g))
else if \<not> timeout g then
\<comment> \<open>Set timeout\<close>
D (g\<lparr>timeout := True\<rparr>)
else
\<comment> \<open>If all else fails: stutter\<close>
RETURN (ls.sng (f (reset\<^sub>I g)))
else
\<comment> \<open>Setting the internal variables (exclusive, handshake, ...) to 0\<close>
\<comment> \<open>is safe -- they are either set by the edges, or not thought\<close>
\<comment> \<open>to be used outside executable.\<close>
let g = reset\<^sub>I g in
nfoldli E (\<lambda>_. True) (\<lambda>(e,p) G.
applyEdge prog e p g \<bind> (\<lambda> g'.
if handshake g' \<noteq> 0 \<or> isAtomic e then do {
G\<^sub>R \<leftarrow> D g';
if ls.isEmpty G\<^sub>R \<and> handshake g' = 0 then
\<comment> \<open>this only happens if the next step is a handshake, which fails\<close>
\<comment> \<open>hence we stay at the current state\<close>
RETURN (ls.ins (f g') G)
else
RETURN (ls.union G\<^sub>R G)
} else RETURN (ls.ins (f g') G))) (ls.empty())
}) g
\<bind> (\<lambda>G. if ls.isEmpty G then RETURN (ls.sng (f g)) else RETURN G)
)"
lemma gState_progress_rel_intros:
"(to\<^sub>I g, gI') \<in> gState_progress_rel prog
\<Longrightarrow> (g, from\<^sub>I gI') \<in> gState_progress_rel prog"
"(gI, gI') \<in> gState_progress_rel prog
\<Longrightarrow> (gI, reset\<^sub>I gI') \<in> gState_progress_rel prog"
"(to\<^sub>I g, gI') \<in> gState_progress_rel prog
\<Longrightarrow> (to\<^sub>I g, gI'\<lparr>timeout := t\<rparr>) \<in> gState_progress_rel prog"
unfolding gState_progress_rel_def
by (cases g, cases gI', cases gI, force simp add: gState_inv_def cl_inv_def)+
lemma gState_progress_rel_step_intros:
"(to\<^sub>I g, g') \<in> gState_progress_rel prog
\<Longrightarrow> (reset\<^sub>I g', g'') \<in> gState_progress_rel prog
\<Longrightarrow> (g, from\<^sub>I g'') \<in> gState_progress_rel prog"
"(to\<^sub>I g, g') \<in> gState_progress_rel prog
\<Longrightarrow> (reset\<^sub>I g', g'') \<in> gState_progress_rel prog
\<Longrightarrow> (to\<^sub>I g, g'') \<in> gState_progress_rel prog"
unfolding gState_progress_rel_def
by (cases g, cases g', cases g'', force simp add: gState_inv_def cl_inv_def)+
lemma cl_inv_reset\<^sub>I:
"cl_inv(g,p) \<Longrightarrow> cl_inv(reset\<^sub>I g, p)"
by (cases g) (simp add: cl_inv_def)
lemmas refine_helpers =
gState_progress_rel_intros gState_progress_rel_step_intros cl_inv_reset\<^sub>I
lemma nexts_SPEC:
assumes "gState_inv prog g"
and "program_inv prog"
shows "nexts prog g \<le> SPEC (\<lambda>gs. \<forall>g' \<in> ls.\<alpha> gs. (g,g') \<in> gState_progress_rel prog)"
using assms
unfolding nexts_def
apply (refine_rcg refine_vcg REC_rule[where
pre="\<lambda>g'. (to\<^sub>I g,g') \<in> gState_progress_rel prog"])
apply (simp add: gState_inv_to\<^sub>I)
apply (rule order_trans[OF executable_edgeSet'])
apply (drule gState_progress_rel_gState_invI2)
apply assumption
apply assumption
apply (refine_rcg refine_vcg nfoldli_rule[where
I="\<lambda>_ _ \<sigma>. \<forall>g' \<in> ls.\<alpha> \<sigma>. (g,g') \<in> gState_progress_rel prog"]
order_trans[OF applyEdge_gState_progress_rel])
apply (vc_solve intro: refine_helpers solve: asm_rl simp add: ls.correct)
apply (rule order_trans)
apply (rprems)
apply (vc_solve intro: refine_helpers solve: asm_rl simp add: ls.correct)
apply (rule order_trans)
apply rprems
apply (vc_solve intro: refine_helpers solve: asm_rl simp add: ls.correct)
done
lemma RETURN_dRETURN:
"RETURN f \<le> f' \<Longrightarrow> nres_of (dRETURN f) \<le> f'"
unfolding nres_of_def
by simp
lemma executable_dRETURN:
"nres_of (dRETURN (executable_impl prog g)) \<le> executable prog g"
using executable_impl.refine
by (simp add: RETURN_dRETURN)
lemma applyEdge_dRETURN:
"nres_of (dRETURN (applyEdge_impl prog e p g)) \<le> applyEdge prog e p g"
using applyEdge_impl.refine
by (simp add: RETURN_dRETURN)
schematic_goal nexts_code_aux:
"nres_of (?nexts prog g) \<le> nexts prog g"
unfolding nexts_def
by (refine_transfer the_resI executable_dRETURN applyEdge_dRETURN)
concrete_definition nexts_code_aux for prog g uses nexts_code_aux
prepare_code_thms nexts_code_aux_def
subsubsection \<open>Handle non-termination\<close>
text \<open>
A Promela model may include non-terminating parts. Therefore we cannot guarantee, that @{const nexts} will actually terminate.
To avoid having to deal with this in the model checker, we fail in case of non-termination.
\<close>
(* TODO: Integrate such a concept into refine_transfer! *)
definition SUCCEED_abort where
"SUCCEED_abort msg dm m = (
case m of
RES X \<Rightarrow> if X={} then Code.abort msg (\<lambda>_. dm) else RES X
| _ \<Rightarrow> m)"
definition dSUCCEED_abort where
"dSUCCEED_abort msg dm m = (
case m of
dSUCCEEDi \<Rightarrow> Code.abort msg (\<lambda>_. dm)
| _ \<Rightarrow> m)"
definition ref_succeed where
"ref_succeed m m' \<longleftrightarrow> m \<le> m' \<and> (m=SUCCEED \<longrightarrow> m'=SUCCEED)"
lemma dSUCCEED_abort_SUCCEED_abort:
"\<lbrakk> RETURN dm' \<le> dm; ref_succeed (nres_of m') m \<rbrakk>
\<Longrightarrow> nres_of (dSUCCEED_abort msg (dRETURN dm') (m'))
\<le> SUCCEED_abort msg dm m"
unfolding dSUCCEED_abort_def SUCCEED_abort_def ref_succeed_def
by (auto split: dres.splits nres.splits)
text \<open>The final successor function now incorporates:
\begin{enumerate}
\item @{const Promela.nexts}
\item handling of non-termination
\end{enumerate}\<close>
definition nexts_code where
"nexts_code prog g =
the_res (dSUCCEED_abort (STR ''The Universe is broken!'')
(dRETURN (ls.sng g))
(nexts_code_aux prog g))"
lemma nexts_code_SPEC:
assumes "gState_inv prog g"
and "program_inv prog"
shows "g' \<in> ls.\<alpha> (nexts_code prog g)
\<Longrightarrow> (g,g') \<in> gState_progress_rel prog"
unfolding nexts_code_def
unfolding dSUCCEED_abort_def
using assms
using order_trans[OF nexts_code_aux.refine nexts_SPEC[OF assms(1,2)]]
by (auto split: dres.splits simp: ls.correct)
subsection \<open>Finiteness of the state space\<close>
inductive_set reachable_states
for P :: program
and g\<^sub>s :: gState \<comment> \<open>start state\<close>
where
"g\<^sub>s \<in> reachable_states P g\<^sub>s" |
"g \<in> reachable_states P g\<^sub>s \<Longrightarrow> x \<in> ls.\<alpha> (nexts_code P g)
\<Longrightarrow> x \<in> reachable_states P g\<^sub>s"
lemmas reachable_states_induct[case_names init step] =
reachable_states.induct[split_format (complete)]
lemma reachable_states_finite:
assumes "program_inv prog"
and "gState_inv prog g"
shows "finite (reachable_states prog g)"
proof (rule finite_subset[OF _ gStates_finite[of _ g]])
define INV where "INV g' \<longleftrightarrow> g' \<in> (gState_progress_rel prog)\<^sup>* `` {g} \<and> gState_inv prog g'" for g'
{
fix g'
have "g' \<in> reachable_states prog g \<Longrightarrow> INV g'"
proof (induct rule: reachable_states_induct)
case init with assms show ?case by (simp add: INV_def)
next
case (step g g')
from step(2,3) have
"(g, g') \<in> gState_progress_rel prog"
using nexts_code_SPEC[OF _ \<open>program_inv prog\<close>]
unfolding INV_def by auto
thus ?case using step(2) unfolding INV_def by auto
qed
}
thus "reachable_states prog g \<subseteq>
(gState_progress_rel prog)\<^sup>* `` {g}"
unfolding INV_def by auto
qed
subsection \<open>Traces\<close>
text \<open>When trying to generate a lasso, we have a problem: We only have a list of global
states. But what are the transitions to come from one to the other?
This problem shall be tackled by @{term replay}: Given two states, it generates a list of
transitions that was taken.\<close>
(* Give a list of edges that lead from g\<^sub>1 to g\<^sub>2 *)
definition replay :: "program \<Rightarrow> gState \<Rightarrow> gState \<Rightarrow> choices nres" where
"replay prog g\<^sub>1 g\<^sub>2 = (
let
g\<^sub>1 = to\<^sub>I g\<^sub>1;
check = \<lambda>g. from\<^sub>I g = g\<^sub>2
in
REC\<^sub>T (\<lambda>D g. do {
E \<leftarrow> executable (states prog) g;
if E = [] then
if check g then RETURN []
else if \<not> timeout g then D (g\<lparr>timeout := True\<rparr>)
else abort STR ''Stuttering should not occur on replay''
(\<lambda>_. RETURN [])
else
let g = reset\<^sub>I g in
nfoldli E (\<lambda>E. E = []) (\<lambda>(e,p) _.
applyEdge prog e p g \<bind> (\<lambda>g'.
if handshake g' \<noteq> 0 \<or> isAtomic e then do {
E\<^sub>R \<leftarrow> D g';
if E\<^sub>R = [] then
if check g' then RETURN [(e,p)] else RETURN []
else
RETURN ((e,p) # E\<^sub>R)
} else if check g' then RETURN [(e,p)] else RETURN [])
) []
}) g\<^sub>1
)"
lemma abort_refine[refine_transfer]:
"nres_of (f ()) \<le> F () \<Longrightarrow> nres_of (abort s f) \<le> abort s F"
"f() \<noteq> dSUCCEED \<Longrightarrow> abort s f \<noteq> dSUCCEED"
by auto
schematic_goal replay_code_aux:
"RETURN (?replay prog g\<^sub>1 g\<^sub>2) \<le> replay prog g\<^sub>1 g\<^sub>2"
unfolding replay_def applyEdge_def
by (refine_transfer the_resI executable_dRETURN)
concrete_definition replay_code for prog g\<^sub>1 g\<^sub>2 uses replay_code_aux
prepare_code_thms replay_code_def
subsubsection \<open>Printing of traces\<close>
(* Might go to another theory *)
definition procDescr
:: "(integer \<Rightarrow> string) \<Rightarrow> program \<Rightarrow> pState \<Rightarrow> string"
where
"procDescr f prog p = (
let
name = String.explode (proc_names prog !! pState.idx p);
id = f (integer_of_nat (pid p))
in
name @ '' ('' @ id @ '')'')"
definition printInitial
:: "(integer \<Rightarrow> string) \<Rightarrow> program \<Rightarrow> gState \<Rightarrow> string"
where
"printInitial f prog g\<^sub>0 = (
let psS = printList (procDescr f prog) (procs g\<^sub>0) [] [] '' '' in
''Initially running: '' @ psS)"
abbreviation "lf \<equiv> CHR 0x0A"
fun printConfig
:: "(integer \<Rightarrow> string) \<Rightarrow> program \<Rightarrow> gState option \<Rightarrow> gState \<Rightarrow> string"
where
"printConfig f prog None g\<^sub>0 = printInitial f prog g\<^sub>0"
| "printConfig f prog (Some g\<^sub>0) g\<^sub>1 = (
let eps = replay_code prog g\<^sub>0 g\<^sub>1 in
let print = (\<lambda>(e,p). procDescr f prog p @ '': '' @ printEdge f (pc p) e)
in if eps = [] \<and> g\<^sub>1 = g\<^sub>0 then '' -- stutter --''
else printList print eps [] [] (lf#'' ''))"
definition "printConfigFromAST f \<equiv> printConfig f o fst o setUp"
subsection \<open>Code export\<close>
code_identifier
code_module "PromelaInvariants" \<rightharpoonup> (SML) Promela
| code_module "PromelaDatastructures" \<rightharpoonup> (SML) Promela
definition "executable_triv prog g = executable_impl (snd prog) g"
definition "apply_triv prog g ep = applyEdge_impl prog (fst ep) (snd ep) (reset\<^sub>I g)"
export_code
setUp printProcesses printConfigFromAST nexts_code executable_triv apply_triv
extractLTLs lookupLTL
checking SML
export_code
setUp printProcesses printConfigFromAST nexts_code executable_triv apply_triv
extractLTLs lookupLTL
in SML
file \<open>Promela.sml\<close>
end
|
module Oscar.Class.Injectivity where
open import Oscar.Level
record Injectivity {a} {A : Set a} {b} {B : Set b} {ℓ₁} (_≋₁_ : A → B → Set ℓ₁)
{i} {I : Set i} {ℓ₂} (_≋₂_ : I → I → Set ℓ₂)
(f : I → A)
(g : I → B)
: Set (a ⊔ b ⊔ ℓ₁ ⊔ i ⊔ ℓ₂) where
field
injectivity : ∀ {x y} → f x ≋₁ g y → x ≋₂ y
open Injectivity ⦃ … ⦄ public
record Injectivityoid a b ℓ₁ i ℓ₂ : Set (lsuc (a ⊔ b ⊔ ℓ₁ ⊔ i ⊔ ℓ₂)) where
field
{A} : Set a
{B} : Set b
_≋₁_ : A → B → Set ℓ₁
I : Set i
_≋₂_ : I → I → Set ℓ₂
μₗ : I → A
μᵣ : I → B
`injectivity : ∀ {x y} → μₗ x ≋₁ μᵣ y → x ≋₂ y
|
(* MacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop
Welcome to Coq 8.4pl5 (October 2014)
Coq < Section Modus_ponens.
Coq < Theorem MP: forall P Q: Prop, P /\ (P -> Q) -> Q.
1 subgoal
============================
forall P Q : Prop, P /\ (P -> Q) -> Q
MP < intro P.
1 subgoal
P : Prop
============================
forall Q : Prop, P /\ (P -> Q) -> Q
MP < intro Q.
1 subgoal
P : Prop
Q : Prop
============================
P /\ (P -> Q) -> Q
MP < intro HPPQ.
1 subgoal
P : Prop
Q : Prop
HPPQ : P /\ (P -> Q)
============================
Q
MP < destruct HPPQ as [HP HPQ].
1 subgoal
P : Prop
Q : Prop
HP : P
HPQ : P -> Q
============================
Q
MP < apply HPQ.
1 subgoal
P : Prop
Q : Prop
HP : P
HPQ : P -> Q
============================
P
MP < exact HP.
No more subgoals.
MP < Qed.
intro P.
intro Q.
intro HPPQ.
destruct HPPQ as (HP, HPQ).
apply HPQ.
exact HP.
MP is defined
Coq <
*)
Section Modus_ponens.
Theorem MP: forall P Q: Prop, P /\ (P -> Q) -> Q.
intro P.
intro Q.
intro HPPQ.
destruct HPPQ as [HP HPQ].
apply HPQ.
exact HP.
Qed.
|
Formal statement is: lemma Re_sgn [simp]: "Re(sgn z) = Re(z)/cmod z" Informal statement is: The real part of the signum function is the real part of the argument divided by the modulus of the argument. |
[STATEMENT]
lemma le_rem_simps [simp]:
"le_rem_s (LOC a) = a"
"le_rem_s (ENV a) = a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. le_rem_s (LOC a) = a &&& le_rem_s (ENV a) = a
[PROOF STEP]
by (unfold le_rem_s_def, auto) |
/-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng, Stanislas Polu, David Renshaw, OpenAI GPT-f
-/
import mathzoo.imports.miniF2F
open_locale nat rat real big_operators topological_space
theorem numbertheory_2dvd4expn
(n : ℕ)
(h₀ : n ≠ 0) :
2 ∣ 4^n :=
begin
apply dvd_pow _ h₀,
norm_num,
end |
import data.real.irrational
import topology.basic
import algebra.order.floor
--OUTPUT 1
theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) (hα : ¬ is_rat α) : ∀ y ∈ Icc 0 1, ∃ x ∈ Icc 0 1, x ≠ y ∧ x ∈ {i • α | i ∈ ℤ} :=
begin
assume (y : ℝ) (h1 : y ∈ Icc 0 1),
have h2 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h3 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h4 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h5 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h6 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h7 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h8 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h9 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h10 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h11 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h12 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h13 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h14 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h15 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h16 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h17 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h18 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h19 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h20 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h21 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h22 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h23 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h24 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h25 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h26 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h27 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h28 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h29 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h30 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h31 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h32 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h33 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h34 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h35 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h36 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h37 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h38 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h39 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h40 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h41 : ∀ i j : ℤ, i ≠ j → {i • α} ≠ {j • α}, from by auto [hα, is_rat_iff_rat],
have h42 : ∀ i j : ℤ, i ≠ j → {i • α} ≠
end --Needs more than 2000 tokens!
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset],
have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left],
have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans],
show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset],
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
calc (x + y)^2 = (x+y)*(x+y) : by auto [sq]
... = x*(x+y) + y*(x+y) : by auto [add_mul]
... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring]
... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring]
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)],
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹],
have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1],
have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2],
have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one],
have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul],
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)],
end
/--`theorem`
Squeeze Theorem for Real Numbers
Let $\sequence {x_n}$, $\sequence {y_n}$ and $\sequence {z_n}$ be sequences in $\R$.
Let $\sequence {y_n}$ and $\sequence {z_n}$ both be convergent to the following limit:
:$\ds \lim_{n \mathop \to \infty} y_n = l, \lim_{n \mathop \to \infty} z_n = l$
Suppose that:
:$\forall n \in \N: y_n \le x_n \le z_n$
Then:
:$x_n \to l$ as $n \to \infty$
that is:
:$\ds \lim_{n \mathop \to \infty} x_n = l$
`proof`
From Negative of Absolute Value:
:$\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$
Let $\epsilon > 0$.
We need to prove that:
:$\exists N: \forall n > N: \size {x_n - l} < \epsilon$
As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that:
:$\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$
As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that:
:$\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$
Let $N = \max \set {N_1, N_2}$.
Then if $n > N$, it follows that $n > N_1$ and $n > N_2$.
So:
:$\forall n > N: l - \epsilon < y_n < l + \epsilon$
:$\forall n > N: l - \epsilon < z_n < l + \epsilon$
But:
:$\forall n \in \N: y_n \le x_n \le z_n$
So:
:$\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$
and so:
:$\forall n > N: l - \epsilon < x_n < l + \epsilon$
So:
:$\forall n > N: \size {x_n - l} < \epsilon$
Hence the result.
{{qed}}
-/
theorem squeeze_theorem_real_numbers (x y z : ℕ → ℝ) (l : ℝ) :
let seq_limit : (ℕ → ℝ) → ℝ → Prop := λ (u : ℕ → ℝ) (l : ℝ), ∀ ε > 0, ∃ N, ∀ n > N, |u n - l| < ε in
seq_limit y l → seq_limit z l → (∀ n : ℕ, (y n) ≤ (x n) ∧ (x n) ≤ (z n)) → seq_limit x l :=
begin
assume seq_limit (h2 : seq_limit y l) (h3 : seq_limit z l) (h4 : ∀ (n : ℕ), y n ≤ x n ∧ x n ≤ z n) (ε),
have h5 : ∀ x, |x - l| < ε ↔ (((l - ε) < x) ∧ (x < (l + ε))),
from by auto [abs_sub_lt_iff] using [linarith],
assume (h7 : ε > 0),
cases h2 ε h7 with N1 h8,
cases h3 ε h7 with N2 h9,
let N := max N1 N2,
use N,
have h10 : ∀ n > N, n > N1 ∧ n > N2 := by auto [lt_of_le_of_lt, le_max_left, le_max_right],
have h11 : ∀ n > N, (((l - ε) < (y n)) ∧ ((y n) ≤ (x n))) ∧ (((x n) ≤ (z n)) ∧ ((z n) < l+ε)),
from by auto [h8, h10, h5, h9],
have h15 : ∀ n > N, ((l - ε) < (x n)) ∧ ((x n) < (l+ε)),
from by auto [h11] using [linarith],
show ∀ (n : ℕ), n > N → |x n - l| < ε,
from by auto [h5, h15],
end
/--`theorem`
Density of irrational orbit
The fractional parts of the integer multiples of an irrational number form a dense subset of the unit interval
`proof`
Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then
$$
i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor,
$$
which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. Hence,
$$
S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}
$$
is an infinite subset of $\left[0,1\right]$.
By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$.
To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$.
QED
-/
theorem
FEW SHOT PROMPTS TO CODEX(END)-/
|
lemmas isCont_scaleR [simp] = bounded_bilinear.isCont [OF bounded_bilinear_scaleR] |
Wheeler had been expecting and openly hoping for war with Nazi Germany for a year prior to the outbreak of hostilities ; he believed that the United Kingdom 's involvement in the conflict would remedy the shame that he thought had been brought upon the country by its signing of the Munich Agreement in September 1938 . Volunteering for the armed services , he was assigned to assemble the 48th Light Anti @-@ Aircraft Battery at Enfield , where he set about recruiting volunteers , including his son . As the 48th swelled in size , it was converted into the 42nd Mobile Light Anti @-@ Aircraft Regiment in the Royal Artillery , which consisted of four batteries and was led by Wheeler – now promoted to the rank of colonel – as Commanding Officer . Given the nickname of " Flash Alf " by those serving under him , he was recognised by colleagues as a ruthless disciplinarian and was blamed by many for the death of one of his soldiers from influenza during training . Having been appointed secretary of the Society of Antiquaries in 1939 and then director in 1940 , he travelled to London to deal with society affairs on various occasions . In 1941 Wheeler was awarded a Fellowship of the British Academy . Cole had meanwhile entered into an affair with a man named Clive Entwistle , who lambasted Wheeler as " that whiskered baboon " . When Wheeler discovered Entwistle in bed with his wife , he initiated divorce proceedings that were finalised in March 1942 .
|
lemmas scaleR_sum_right = real_vector.scale_sum_right |
export
record Core t where
constructor MkCore
runCore : IO (Either String t)
pure : a -> Core a
pure x = MkCore (pure (pure x))
export
(<*>) : Core (a -> b) -> Core a -> Core b
(<*>) (MkCore f) (MkCore a) = MkCore [| f `Prelude.(<*>)` a |]
addm : Maybe Int -> Maybe Int -> Maybe Int
addm x y = [| x + y |]
|
From fae_gtlc_mu.cast_calculus Require Export types lang consistency.
From fae_gtlc_mu Require Export prelude.
From Coq Require Import List.
Reserved Notation "Γ ⊢ₜ e : τ" (at level 74, e, τ at next level).
(** Typing derivations *)
Inductive typed (Γ : list type) : expr → type → Prop :=
| Var_typed x τ (pτ : Closed τ) : (Γ !! x = Some τ) → Γ ⊢ₜ Var x : τ
| Unit_typed : Γ ⊢ₜ Unit : TUnit
| Pair_typed e1 e2 τ1 τ2 :
Γ ⊢ₜ e1 : τ1 → Γ ⊢ₜ e2 : τ2 → Γ ⊢ₜ Pair e1 e2 : TProd τ1 τ2
| Fst_typed e τ1 τ2 : Γ ⊢ₜ e : TProd τ1 τ2 → Γ ⊢ₜ Fst e : τ1
| Snd_typed e τ1 τ2 : Γ ⊢ₜ e : TProd τ1 τ2 → Γ ⊢ₜ Snd e : τ2
| InjL_typed e τ1 τ2 (pτ2 : Closed τ2) : Γ ⊢ₜ e : τ1 → Γ ⊢ₜ InjL e : TSum τ1 τ2
| InjR_typed e τ1 (pτ1 : Closed τ1) τ2 : Γ ⊢ₜ e : τ2 → Γ ⊢ₜ InjR e : TSum τ1 τ2
| Case_typed e0 e1 e2 τ1 τ2 ρ :
Γ ⊢ₜ e0 : TSum τ1 τ2 → τ1 :: Γ ⊢ₜ e1 : ρ → τ2 :: Γ ⊢ₜ e2 : ρ →
Γ ⊢ₜ Case e0 e1 e2 : ρ
| Lam_typed e τ1 (pτ1 : Closed τ1) τ2 : τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Lam e : TArrow τ1 τ2
| App_typed e1 e2 τ1 τ2 : Γ ⊢ₜ e1 : TArrow τ1 τ2 → Γ ⊢ₜ e2 : τ1 → Γ ⊢ₜ App e1 e2 : τ2
| Fold_typed e τ : Γ ⊢ₜ e : τ.[TRec τ/] → Γ ⊢ₜ Fold e : TRec τ
| Unfold_typed e τ : Γ ⊢ₜ e : TRec τ → Γ ⊢ₜ Unfold e : τ.[TRec τ/]
(* typing for CAST *)
| Cast_typed e τi τf (pτf : Closed τf) (pC : consistency_open τi τf) :
Γ ⊢ₜ e : τi →
Γ ⊢ₜ Cast e τi τf : τf
(* typing for BLAME *)
| CastError_typed τ : Closed τ → Γ ⊢ₜ CastError : τ
where "Γ ⊢ₜ e : τ" := (typed Γ e τ).
From fae_gtlc_mu.cast_calculus Require Export types_lemmas.
(* Our typing derivations are defined such that for any τ, if something is well-typed of type τ, τ is closed (i.e. τ does not contain free variables). *)
Lemma typed_closed {Γ} {e} {τ} : Γ ⊢ₜ e : τ → Closed τ.
Proof.
intro d. induction d.
- auto.
- apply TUnit_Closed.
- by apply TProd_closed.
- by eapply TProd_closed1.
- by eapply TProd_closed2.
- by eapply TSum_closed.
- by eapply TSum_closed.
- auto.
- by apply TArrow_closed.
- by eapply TArrow_closed2.
- by apply closed_Fold_typed_help.
- by apply TRec_closed_unfold.
- auto.
- auto.
Qed.
|
Formal statement is: lemma coeffs_uminus [code abstract]: "coeffs (- p) = map uminus (coeffs p)" Informal statement is: The coefficients of $-p$ are the negations of the coefficients of $p$. |
lemma (in sigma_algebra) restriction_in_sets: fixes A :: "nat \<Rightarrow> 'a set" assumes "S \<in> M" and *: "range A \<subseteq> (\<lambda>A. S \<inter> A) ` M" (is "_ \<subseteq> ?r") shows "range A \<subseteq> M" "(\<Union>i. A i) \<in> (\<lambda>A. S \<inter> A) ` M" |
(* An attempt to adapt the tests from [Examples.v] for CoqHammer
http://cl-informatik.uibk.ac.at/cek/coqhammer/
Currently, CoqHammer does not seem to be very powerful in linear arithmetic...
*)
Require Export Tactic.
Lemma simple2_x (v1 v2: Qc) :
v1 <= 6*v2 ->
6*v2 <= v1 -> v1 <> 6*v2 + 1.
Proof.
vpl.
Qed.
From Hammer Require Import Hammer Reconstr.
Require Import ZArith.
Local Open Scope Z_scope.
Lemma h_ex_intro (x: Z) (f: Z -> Z):
(x <= 1)
-> (f x) < (f 1)
-> (x < 1).
Proof.
hammer.
Qed.
Lemma h_simple2 (v1 v2: Z) :
v1 <= v2 ->
v2 <= v1 -> v1 <> v2 + 1.
Proof.
hammer.
Qed.
Lemma h_simple2_x (v1 v2: Z) :
v1 <= 6*v2 ->
6*v2 <= v1 -> v1 <> 6*v2 + 1.
Proof.
hammer.
(* NB: omega succeeds to prove the goal *)
Abort.
Lemma besson_example (x y z: Z) (f: Z -> Z):
f((f x) - (f y)) <> (f z)
-> x <= y
-> y+z <= x
-> z < 0.
Proof.
hammer.
Abort.
|
module Loop
import Loop
|
-- WARNING: This file was generated automatically by Vehicle
-- and should not be modified manually!
-- Metadata
-- - Agda version: 2.6.2
-- - AISEC version: 0.1.0.1
-- - Time generated: ???
{-# OPTIONS --allow-exec #-}
open import Vehicle
open import Data.Unit
open import Data.Empty
open import Data.Product
open import Data.Nat as ℕ using (ℕ)
open import Data.Fin as Fin using (Fin; #_)
open import Data.List
open import Data.List.Relation.Unary.All as List
open import Relation.Binary.PropositionalEquality
module simple-let-temp-output where
abstract
e1 : let x = ⊤ in let y = ⊥ in x × y
e1 = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
}
abstract
e2 : let y = # 1 in y Fin.≥ # 2
e2 = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
}
e3 : ℕ
e3 = let y = 1 ℕ.+ 1 in y
lamLet : ℕ → ℕ
lamLet x = let y = x in y
abstract
forallLet : ∀ (x : Fin 2) → let y = x in y ≡ # 1
forallLet = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
}
abstract
letForall : let y = # 1 in ∀ (x : Fin 2) → y ≡ x
letForall = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
}
abstract
forallInLet : List.All (λ (x : Fin 2) → let y = x in y ≡ # 1) (# 1 ∷ [])
forallInLet = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
}
abstract
letForallIn : let y = # 1 in List.All (λ (x : Fin 2) → y ≡ x) (# 1 ∷ [])
letForallIn = checkSpecification record
{ proofCache = "/home/matthew/Code/AISEC/vehicle/proofcache.vclp"
} |
/-
Copyright (c) 2021 Vladimir Goryachev. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez
-/
import data.nat.count
import order.order_iso_nat
/-!
# The `n`th Number Satisfying a Predicate
This file defines a function for "what is the `n`th number that satisifies a given predicate `p`",
and provides lemmas that deal with this function and its connection to `nat.count`.
## Main definitions
* `nth p n`: The `n`-th natural `k` (zero-indexed) such that `p k`. If there is no
such natural (that is, `p` is true for at most `n` naturals), then `nth p n = 0`.
## Main results
* `nat.nth_set_card`: For a fintely-often true `p`, gives the cardinality of the set of numbers
satisfying `p` above particular values of `nth p`
* `nat.count_nth_gc`: Establishes a Galois connection between `nth p` and `count p`.
* `nat.nth_eq_order_iso_of_nat`: For an infinitely-ofter true predicate, `nth` agrees with the
order-isomorphism of the subtype to the natural numbers.
There has been some discussion on the subject of whether both of `nth` and
`nat.subtype.order_iso_of_nat` should exist. See discussion
[here](https://github.com/leanprover-community/mathlib/pull/9457#pullrequestreview-767221180).
Future work should address how lemmas that use these should be written.
-/
open finset
namespace nat
variable (p : ℕ → Prop)
/-- Find the `n`-th natural number satisfying `p` (indexed from `0`, so `nth p 0` is the first
natural number satisfying `p`), or `0` if there is no such number. See also
`subtype.order_iso_of_nat` for the order isomorphism with ℕ when `p` is infinitely often true. -/
noncomputable def nth : ℕ → ℕ
| n := Inf { i : ℕ | p i ∧ ∀ k < n, nth k < i }
lemma nth_zero : nth p 0 = Inf { i : ℕ | p i } := by { rw nth, simp }
@[simp] lemma nth_zero_of_zero (h : p 0) : nth p 0 = 0 :=
by simp [nth_zero, h]
lemma nth_zero_of_exists [decidable_pred p] (h : ∃ n, p n) : nth p 0 = nat.find h :=
by { rw [nth_zero], convert nat.Inf_def h }
lemma nth_set_card_aux {n : ℕ} (hp : (set_of p).finite)
(hp' : {i : ℕ | p i ∧ ∀ t < n, nth p t < i}.finite) (hle : n ≤ hp.to_finset.card) :
hp'.to_finset.card = hp.to_finset.card - n :=
begin
unfreezingI { induction n with k hk },
{ congr,
simp only [forall_false_left, nat.not_lt_zero, forall_const, and_true] },
have hp'': {i : ℕ | p i ∧ ∀ t, t < k → nth p t < i}.finite,
{ refine hp.subset (λ x hx, _),
rw set.mem_set_of_eq at hx,
exact hx.left },
have hle' := nat.sub_pos_of_lt hle,
specialize hk hp'' (k.le_succ.trans hle),
rw [nat.sub_succ', ←hk],
convert_to (finset.erase hp''.to_finset (nth p k)).card = _,
{ congr,
ext a,
simp only [set.finite.mem_to_finset, ne.def, set.mem_set_of_eq, finset.mem_erase],
refine ⟨λ ⟨hp, hlt⟩,
⟨(hlt _ (lt_add_one k)).ne', ⟨hp, λ n hn, hlt n (hn.trans_le k.le_succ)⟩⟩, _⟩,
rintro ⟨hak : _ ≠ _, hp, hlt⟩,
refine ⟨hp, λ n hn, _⟩,
rw lt_succ_iff at hn,
obtain hnk | rfl := hn.lt_or_eq,
{ exact hlt _ hnk },
{ refine lt_of_le_of_ne _ (ne.symm hak),
rw nth,
apply nat.Inf_le,
simpa [hp] using hlt } },
apply finset.card_erase_of_mem,
rw [nth, set.finite.mem_to_finset],
apply Inf_mem,
rwa [←hp''.nonempty_to_finset, ←finset.card_pos, hk],
end
lemma nth_set_card {n : ℕ} (hp : (set_of p).finite)
(hp' : {i : ℕ | p i ∧ ∀ k < n, nth p k < i}.finite) :
hp'.to_finset.card = hp.to_finset.card - n :=
begin
obtain hn | hn := le_or_lt n hp.to_finset.card,
{ exact nth_set_card_aux p hp _ hn },
rw nat.sub_eq_zero_of_le hn.le,
simp only [finset.card_eq_zero, set.finite_to_finset_eq_empty_iff, ←set.subset_empty_iff],
convert_to _ ⊆ {i : ℕ | p i ∧ ∀ (k : ℕ), k < hp.to_finset.card → nth p k < i},
{ symmetry,
rw [←set.finite_to_finset_eq_empty_iff, ←finset.card_eq_zero,
←nat.sub_self hp.to_finset.card],
{ apply nth_set_card_aux p hp _ le_rfl },
{ exact hp.subset (λ x hx, hx.1) } },
exact λ x hx, ⟨hx.1, λ k hk, hx.2 _ (hk.trans hn)⟩,
end
lemma nth_set_nonempty_of_lt_card {n : ℕ} (hp : (set_of p).finite) (hlt: n < hp.to_finset.card) :
{i : ℕ | p i ∧ ∀ k < n, nth p k < i}.nonempty :=
begin
have hp': {i : ℕ | p i ∧ ∀ (k : ℕ), k < n → nth p k < i}.finite,
{ exact hp.subset (λ x hx, hx.1) },
rw [←hp'.nonempty_to_finset, ←finset.card_pos, nth_set_card p hp],
exact nat.sub_pos_of_lt hlt,
end
lemma nth_mem_of_lt_card_finite_aux (n : ℕ) (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) :
nth p n ∈ {i : ℕ | p i ∧ ∀ k < n, nth p k < i} :=
begin
rw nth,
apply Inf_mem,
exact nth_set_nonempty_of_lt_card _ _ hlt,
end
lemma nth_mem_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) :
p (nth p n) := (nth_mem_of_lt_card_finite_aux p n hp hlt).1
lemma nth_strict_mono_of_finite {m n : ℕ} (hp : (set_of p).finite)
(hlt : n < hp.to_finset.card) (hmn : m < n) : nth p m < nth p n :=
(nth_mem_of_lt_card_finite_aux p _ hp hlt).2 _ hmn
lemma nth_mem_of_infinite_aux (hp : (set_of p).infinite) (n : ℕ) :
nth p n ∈ { i : ℕ | p i ∧ ∀ k < n, nth p k < i } :=
begin
rw nth,
apply Inf_mem,
let s : set ℕ := ⋃ (k < n), { i : ℕ | nth p k ≥ i },
convert_to ((set_of p) \ s).nonempty,
{ ext i,
simp },
refine (hp.diff $ (set.finite_lt_nat _).bUnion _).nonempty,
exact λ k h, set.finite_le_nat _,
end
lemma nth_mem_of_infinite (hp : (set_of p).infinite) (n : ℕ) : p (nth p n) :=
(nth_mem_of_infinite_aux p hp n).1
lemma nth_strict_mono (hp : (set_of p).infinite) : strict_mono (nth p) :=
λ a b, (nth_mem_of_infinite_aux p hp b).2 _
lemma nth_injective_of_infinite (hp : (set_of p).infinite) : function.injective (nth p) :=
begin
intros m n h,
wlog h' : m ≤ n,
rw le_iff_lt_or_eq at h',
obtain (h' | rfl) := h',
{ simpa [h] using nth_strict_mono p hp h' },
{ refl },
end
lemma nth_monotone (hp : (set_of p).infinite) : monotone (nth p) :=
(nth_strict_mono p hp).monotone
lemma nth_mono_of_finite {a b : ℕ} (hp : (set_of p).finite) (hb : b < hp.to_finset.card)
(hab : a ≤ b) : nth p a ≤ nth p b :=
begin
obtain rfl | h := hab.eq_or_lt,
{ exact le_rfl },
{ exact (nth_strict_mono_of_finite p hp hb h).le }
end
lemma le_nth_of_lt_nth_succ_finite {k a : ℕ} (hp : (set_of p).finite)
(hlt : k.succ < hp.to_finset.card) (h : a < nth p k.succ) (ha : p a) :
a ≤ nth p k :=
begin
by_contra' hak,
refine h.not_le _,
rw nth,
apply nat.Inf_le,
refine ⟨ha, λ n hn, lt_of_le_of_lt _ hak⟩,
exact nth_mono_of_finite p hp (k.le_succ.trans_lt hlt) (le_of_lt_succ hn),
end
lemma le_nth_of_lt_nth_succ_infinite {k a : ℕ} (hp : (set_of p).infinite)
(h : a < nth p k.succ) (ha : p a) :
a ≤ nth p k :=
begin
by_contra' hak,
refine h.not_le _,
rw nth,
apply nat.Inf_le,
exact ⟨ha, λ n hn, (nth_monotone p hp (le_of_lt_succ hn)).trans_lt hak⟩,
end
section count
variables [decidable_pred p]
@[simp] lemma count_nth_zero : count p (nth p 0) = 0 :=
begin
rw [count_eq_card_filter_range, finset.card_eq_zero, nth_zero],
ext a,
simp_rw [not_mem_empty, mem_filter, mem_range, iff_false],
rintro ⟨ha, hp⟩,
exact ha.not_le (nat.Inf_le hp),
end
lemma filter_range_nth_eq_insert_of_finite (hp : (set_of p).finite) {k : ℕ}
(hlt : k.succ < hp.to_finset.card) :
finset.filter p (finset.range (nth p k.succ)) =
insert (nth p k) (finset.filter p (finset.range (nth p k))) :=
begin
ext a,
simp_rw [mem_insert, mem_filter, mem_range],
split,
{ rintro ⟨ha, hpa⟩,
refine or_iff_not_imp_left.mpr (λ h, ⟨lt_of_le_of_ne _ h, hpa⟩),
exact le_nth_of_lt_nth_succ_finite p hp hlt ha hpa },
{ rintro (ha | ⟨ha, hpa⟩),
{ rw ha,
refine ⟨nth_strict_mono_of_finite p hp hlt (lt_add_one _), _⟩,
apply nth_mem_of_lt_card_finite p hp,
exact (k.le_succ).trans_lt hlt },
refine ⟨ha.trans _, hpa⟩,
exact nth_strict_mono_of_finite p hp hlt (lt_add_one _) }
end
lemma count_nth_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite)
(hlt : n < hp.to_finset.card) : count p (nth p n) = n :=
begin
induction n with k hk,
{ exact count_nth_zero _ },
{ rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_finite p hp hlt,
finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk (lt_of_succ_lt hlt)],
simp, },
end
lemma filter_range_nth_eq_insert_of_infinite (hp : (set_of p).infinite) (k : ℕ) :
(finset.range (nth p k.succ)).filter p = insert (nth p k) ((finset.range (nth p k)).filter p) :=
begin
ext a,
simp_rw [mem_insert, mem_filter, mem_range],
split,
{ rintro ⟨ha, hpa⟩,
rw nth at ha,
refine or_iff_not_imp_left.mpr (λ hne, ⟨(le_of_not_lt $ λ h, _).lt_of_ne hne, hpa⟩),
exact ha.not_le (nat.Inf_le ⟨hpa, λ b hb, (nth_monotone p hp (le_of_lt_succ hb)).trans_lt h⟩) },
{ rintro (rfl | ⟨ha, hpa⟩),
{ exact ⟨nth_strict_mono p hp (lt_succ_self k), nth_mem_of_infinite p hp _⟩ },
{ exact ⟨ha.trans (nth_strict_mono p hp (lt_succ_self k)), hpa⟩ } }
end
lemma count_nth_of_infinite (hp : (set_of p).infinite) (n : ℕ) : count p (nth p n) = n :=
begin
induction n with k hk,
{ exact count_nth_zero _ },
{ rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_infinite p hp,
finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk],
simp, },
end
@[simp] lemma nth_count {n : ℕ} (hpn : p n) : nth p (count p n) = n :=
begin
obtain hp | hp := em (set_of p).finite,
{ refine count_injective _ hpn _,
{ apply nth_mem_of_lt_card_finite p hp,
exact count_lt_card hp hpn },
{ exact count_nth_of_lt_card_finite _ _ (count_lt_card hp hpn) } },
{ apply count_injective (nth_mem_of_infinite _ hp _) hpn,
apply count_nth_of_infinite p hp }
end
lemma nth_count_eq_Inf {n : ℕ} : nth p (count p n) = Inf {i : ℕ | p i ∧ n ≤ i} :=
begin
rw nth,
congr,
ext a,
simp only [set.mem_set_of_eq, and.congr_right_iff],
intro hpa,
refine ⟨λ h, _, λ hn k hk, lt_of_lt_of_le _ hn⟩,
{ by_contra ha,
simp only [not_le] at ha,
have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha),
rwa [nth_count p hpa, lt_self_iff_false] at hn },
{ apply (count_monotone p).reflect_lt,
convert hk,
obtain hp | hp : (set_of p).finite ∨ (set_of p).infinite := em (set_of p).finite,
{ rw count_nth_of_lt_card_finite _ hp,
exact hk.trans ((count_monotone _ hn).trans_lt (count_lt_card hp hpa)) },
{ apply count_nth_of_infinite p hp } }
end
lemma nth_count_le (hp : (set_of p).infinite) (n : ℕ) : n ≤ nth p (count p n) :=
begin
rw nth_count_eq_Inf,
suffices h : Inf {i : ℕ | p i ∧ n ≤ i} ∈ {i : ℕ | p i ∧ n ≤ i},
{ exact h.2 },
apply Inf_mem,
obtain ⟨m, hp, hn⟩ := hp.exists_nat_lt n,
exact ⟨m, hp, hn.le⟩
end
lemma count_nth_gc (hp : (set_of p).infinite) : galois_connection (count p) (nth p) :=
begin
rintro x y,
rw [nth, le_cInf_iff ⟨0, λ _ _, nat.zero_le _⟩ ⟨nth p y, nth_mem_of_infinite_aux p hp y⟩],
dsimp,
refine ⟨_, λ h, _⟩,
{ rintro hy n ⟨hn, h⟩,
obtain hy' | rfl := hy.lt_or_eq,
{ exact (nth_count_le p hp x).trans (h (count p x) hy').le },
{ specialize h (count p n),
replace hn : nth p (count p n) = n := nth_count _ hn,
replace h : count p x ≤ count p n := by rwa [hn, lt_self_iff_false, imp_false, not_lt] at h,
refine (nth_count_le p hp x).trans _,
rw ← hn,
exact nth_monotone p hp h }, },
{ rw ←count_nth_of_infinite p hp y,
exact count_monotone _ (h (nth p y) ⟨nth_mem_of_infinite p hp y,
λ k hk, nth_strict_mono p hp hk⟩) }
end
lemma count_le_iff_le_nth (hp : (set_of p).infinite) {a b : ℕ} :
count p a ≤ b ↔ a ≤ nth p b := count_nth_gc p hp _ _
lemma lt_nth_iff_count_lt (hp : (set_of p).infinite) {a b : ℕ} :
a < count p b ↔ nth p a < b := lt_iff_lt_of_le_iff_le $ count_le_iff_le_nth p hp
lemma nth_lt_of_lt_count (n k : ℕ) (h : k < count p n) : nth p k < n :=
begin
obtain hp | hp := em (set_of p).finite,
{ refine (count_monotone p).reflect_lt _,
rwa count_nth_of_lt_card_finite p hp,
refine h.trans_le _,
rw count_eq_card_filter_range,
exact finset.card_le_of_subset (λ x hx, hp.mem_to_finset.2 (mem_filter.1 hx).2) },
{ rwa ← lt_nth_iff_count_lt _ hp }
end
lemma le_nth_of_count_le (n k : ℕ) (h: n ≤ nth p k) : count p n ≤ k :=
begin
by_contra hc,
apply not_lt.mpr h,
apply nth_lt_of_lt_count,
simpa using hc
end
end count
lemma nth_zero_of_nth_zero (h₀ : ¬p 0) {a b : ℕ} (hab : a ≤ b) (ha : nth p a = 0) :
nth p b = 0 :=
begin
rw [nth, Inf_eq_zero] at ⊢ ha,
cases ha,
{ exact (h₀ ha.1).elim },
{ refine or.inr (set.eq_empty_of_subset_empty $ λ x hx, _),
rw ←ha,
exact ⟨hx.1, λ k hk, hx.2 k $ hk.trans_le hab⟩ }
end
/-- When `p` is true infinitely often, `nth` agrees with `nat.subtype.order_iso_of_nat`. -/
lemma nth_eq_order_iso_of_nat [decidable_pred p] (i : infinite (set_of p)) (n : ℕ) :
nth p n = nat.subtype.order_iso_of_nat (set_of p) n :=
begin
have hi := set.infinite_coe_iff.mp i,
induction n with k hk;
simp only [subtype.order_iso_of_nat_apply, subtype.of_nat, nat_zero_eq_zero],
{ rw [nat.subtype.coe_bot, nth_zero_of_exists], },
{ simp only [nat.subtype.succ, set.mem_set_of_eq, subtype.coe_mk, subtype.val_eq_coe],
rw [subtype.order_iso_of_nat_apply] at hk,
set b := nth p k.succ - nth p k - 1 with hb,
replace hb : p (↑(subtype.of_nat (set_of p) k) + b + 1),
{ rw [hb, ←hk, tsub_right_comm],
have hn11: nth p k.succ - 1 + 1 = nth p k.succ,
{ rw tsub_add_cancel_iff_le,
exact succ_le_of_lt (pos_of_gt (nth_strict_mono p hi (lt_add_one k))), },
rw add_tsub_cancel_of_le,
{ rw hn11,
apply nth_mem_of_infinite p hi },
{ rw [← lt_succ_iff, ← nat.add_one, hn11],
apply nth_strict_mono p hi,
exact lt_add_one k } },
have H : (∃ n: ℕ , p (↑(subtype.of_nat (set_of p) k) + n + 1)) := ⟨b, hb⟩,
set t := nat.find H with ht,
obtain ⟨hp, hmin⟩ := (nat.find_eq_iff _).mp ht,
rw [←ht, ←hk] at hp hmin ⊢,
rw [nth, Inf_def ⟨_, nth_mem_of_infinite_aux p hi k.succ⟩, nat.find_eq_iff],
refine ⟨⟨by convert hp, λ r hr, _⟩, λ n hn, _⟩,
{ rw lt_succ_iff at ⊢ hr,
exact (nth_monotone p hi hr).trans (by simp) },
simp only [exists_prop, not_and, not_lt, set.mem_set_of_eq, not_forall],
refine λ hpn, ⟨k, lt_add_one k, _⟩,
by_contra' hlt,
replace hn : n - nth p k - 1 < t,
{ rw tsub_lt_iff_left,
{ rw tsub_lt_iff_left hlt.le,
convert hn using 1,
ac_refl },
exact le_tsub_of_add_le_left (succ_le_of_lt hlt) },
refine hmin (n - nth p k - 1) hn _,
convert hpn,
have hn11 : n - 1 + 1 = n := nat.sub_add_cancel (pos_of_gt hlt),
rwa [tsub_right_comm, add_tsub_cancel_of_le],
rwa [←hn11, lt_succ_iff] at hlt },
end
end nat
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
Class(InertTranspose, BaseContainer, SumsBase, rec(
dims := self >> Reversed(self.child(1).dims()),
toAMat := self >> AMatMat(TransposedMat(MatSPL(self.child(1))))
));
Class(InertConjTranspose, BaseContainer, SumsBase, rec(
dims := self >> Reversed(self.child(1).dims()),
toAMat := self >> AMatMat(Global.Conjugate(TransposedMat(MatSPL(self.child(1)))))
));
InertConjTranspose.conjTranspose := self >> self.child(1);
|
/-
Copyright (c) 2021 Alexander Griffin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Alexander Griffin.
-/
import group_theory.specific_groups.dihedral
/-!
# Dihedral Group Centers
In this file we prove which elements can and cannot
be members of the center of a (non-degenerate) dihedral group.
## Main results
- `sr_not_mem_center`: No reflection is central (if the group is non-degenerate).
- `r_not_mem_center`: Rotations with order greater than 2 are not central.
- `r_mem_center_r`: Rotations with order at most 2 commute with all rotations.
- `r_mem_center_sr`: Rotations with order at most 2 commute with all reflections.
## Notation
- `r i`: A rotation element of a dihedral group.
- `sr i`: A reflection element of a dihedral group.
## References
See the file for dihedral groups in mathlib.
-/
open dihedral_group
variables {n : ℕ}
variables {x : dihedral_group n}
namespace dihedral_github
/--
No reflection is central (if the group is non-degenerate).
`i` is any `zmod n`.
-/
lemma sr_not_mem_center [fact (n > 2)] (i : zmod n): ∃ x, sr i * x ≠ x * r i :=
begin
use (r 1),
end
/--
Rotations with order greater than 2 are not central.
`i` is any `zmod n` term satisfying `2 * i ≠ 0`.
-/
theorem r_not_mem_center (i : zmod n): 2 * i ≠ 0 → ∃ x, r i * x ≠ x * r i :=
begin
intro h,
use (sr 1),
have : r i * sr 1 = sr (1 - i), by refl,
rw this,
have : sr 1 * r i = sr (1 + i), by refl,
rw this,
ring_nf,
simp,
rwa [eq_comm, ← sub_eq_zero, sub_neg_eq_add, ← two_mul],
end
/--
Rotations with order at most 2 commute with all rotations.
`i` is any `zmod n` term satisfying `2 * i = 0`.
-/
theorem r_mem_center_r (i : zmod n): 2 * i = 0 → ∀ (j : zmod n), r i * r j = r j * r i :=
begin
intros h j,
have : r i * r j = r (i + j), by refl,
rw this,
have : r j * r i = r (j + i), by refl,
rw this,
ring_nf,
ring,
end
/--
Rotations with order at most 2 commute with all reflections.
`i` is any `zmod n` term satisfying `2 * i = 0`.
-/
theorem r_mem_center_sr (i : zmod n): 2 * i = 0 → ∀ (j : zmod n), r i * sr j = sr j * r i :=
begin
intros h j,
have : r i * sr j = sr (j - i), by refl,
rw this,
have : sr j * r i = sr (j + i), by refl,
rw this,
ring_nf,
rw sub_eq_add_neg, congr,
rwa [eq_comm, ← sub_eq_zero, sub_neg_eq_add, ← two_mul],
end
end dihedral_github |
(* Title: HOL/Types_To_Sets/Examples/Finite.thy
Author: Ondřej Kunčar, TU München
*)
theory Finite
imports "../Types_To_Sets" Prerequisites
begin
section \<open>The Type-Based Theorem\<close>
text\<open>This example file shows how we perform the relativization in presence of axiomatic
type classes: we internalize them.\<close>
definition injective :: "('a \<Rightarrow> 'b) \<Rightarrow> bool"
where "injective f \<equiv> (\<forall>x y. f x = f y \<longrightarrow> x = y)"
text\<open>We want to relativize the following type-based theorem using the type class finite.\<close>
lemma type_based: "\<exists>f :: 'a::finite \<Rightarrow> nat. injective f"
unfolding injective_def
using finite_imp_inj_to_nat_seg[of "UNIV::'a set", unfolded inj_on_def] by auto
section \<open>Definitions and Setup for The Relativization\<close>
text\<open>We have to define what being injective on a set means.\<close>
definition injective_on :: "'a set \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool"
where "injective_on A f \<equiv> \<forall>x \<in> A. \<forall>y \<in> A. f x = f y \<longrightarrow> x = y"
text\<open>The predicate injective_on is the relativization of the predicate injective.\<close>
lemma injective_transfer[transfer_rule]:
includes lifting_syntax
assumes [transfer_rule]: "right_total T"
assumes [transfer_rule]: "bi_unique T"
shows "((T ===> (=)) ===> (=)) (injective_on (Collect(Domainp T))) injective"
unfolding injective_on_def[abs_def] injective_def[abs_def] by transfer_prover
text\<open>Similarly, we define the relativization of the internalization
of the type class finite, class.finite\<close>
definition finite_on :: "'a set => bool" where "finite_on A = finite A"
lemma class_finite_transfer[transfer_rule]:
assumes [transfer_rule]: "right_total (T::'a\<Rightarrow>'b\<Rightarrow>bool)"
assumes [transfer_rule]: "bi_unique T"
shows "(=) (finite_on (Collect(Domainp T))) (class.finite TYPE('b))"
unfolding finite_on_def class.finite_def by transfer_prover
text\<open>The aforementioned development can be automated. The main part is already automated
by the transfer_prover.\<close>
section \<open>The Relativization to The Set-Based Theorem\<close>
lemmas internalized = type_based[internalize_sort "'a::finite"]
text\<open>We internalized the type class finite and thus reduced the task to the
original relativization algorithm.\<close>
thm internalized
text\<open>This is the set-based variant.\<close>
lemma set_based:
assumes "(A::'a set) \<noteq> {}"
shows "finite_on A \<longrightarrow> (\<exists>f :: 'a \<Rightarrow> nat. injective_on A f)"
proof -
{
text\<open>We define the type 'b to be isomorphic to A.\<close>
assume T: "\<exists>(Rep :: 'b \<Rightarrow> 'a) Abs. type_definition Rep Abs A"
from T obtain rep :: "'b \<Rightarrow> 'a" and abs :: "'a \<Rightarrow> 'b" where t: "type_definition rep abs A"
by auto
text\<open>Setup for the Transfer tool.\<close>
define cr_b where "cr_b == \<lambda>r a. r = rep a"
note type_definition_Domainp[OF t cr_b_def, transfer_domain_rule]
note typedef_right_total[OF t cr_b_def, transfer_rule]
note typedef_bi_unique[OF t cr_b_def, transfer_rule]
have ?thesis
text\<open>Relativization by the Transfer tool.\<close>
using internalized[where 'a = 'b, untransferred, simplified]
by blast
} note * = this[cancel_type_definition, OF assms] text\<open>We removed the definition of 'b.\<close>
show ?thesis by (rule *)
qed
text\<open>The Final Result. We can compare the type-based and the set-based statement.\<close>
thm type_based set_based
end
|
Require Import CoRN.algebra.RSetoid.
Require Import
Unicode.Utf8 Setoid List Permutation Setoid Morphisms SetoidPermutation
stdlib_omissions.Pair.
Fixpoint separates {A} (l: list A): list (A * list A) :=
match l with
| nil => nil
| x :: xs => (x, xs) :: map (fun pq => (fst pq, x :: snd pq)) (separates xs)
end.
(**
separates (0::1::2::nil)= (0, 1 :: 2 :: nil) :: (1, 0 :: 2 :: nil) :: (2, 0 :: 1 :: nil) :: nil
*)
Lemma separates_length {A} (l: list A): length (separates l) = length l.
Proof.
induction l. intuition.
simpl. rewrite map_length.
congruence.
Qed.
Lemma separates_elem_lengths {A} (l x: list A): In x (map (@snd _ _) (separates l)) →
length l = S (length x).
Proof with auto.
revert x.
induction l; simpl. intuition.
intros x [[] | C]...
rewrite map_map in C.
simpl in C.
destruct (proj1 (in_map_iff _ _ _) C) as [x0 [[]?]].
rewrite (IHl (snd x0)). reflexivity.
apply in_map_iff. eauto.
Qed.
#[global]
Instance separates_Proper {A}:
Proper (@Permutation _ ==> SetoidPermutation (pair_rel eq (@Permutation _))) (@separates A).
Proof with simpl; auto; intuition.
intros ?? P.
induction P...
3:eauto.
apply s_perm_skip. split...
apply (map_perm_proper (pair_rel eq (@Permutation A)))...
intros ?? [??]. split...
rewrite s_perm_swap.
repeat apply s_perm_skip...
do 2 rewrite map_map.
apply (map_perm_proper (pair_rel eq (SetoidPermutation eq)))...
intros ?? [C D]. split...
apply perm_trans with (l':=(x :: y :: snd x0))...
do 2 apply perm_skip...
apply SetoidPermutation_eq...
Qed.
|
informal statement Show that $ \int_{-\infty}^{\infty} \frac{\cos x}{x^2 + a^2} dx = \pi \frac{e^{-a}}{a}$ for $a > 0$.formal statement theorem exercise_3_9 : ∫ x in 0..1, real.log (real.sin (real.pi * x)) = - real.log 2 := |
{-# OPTIONS --show-implicit #-}
module AgdaFeatureTerminationViaExplicitness where
data Nat : Set where
zero : Nat
suc : (n : Nat) → Nat
id : {A : Set} → A → A
id = λ x → x
data Pat (n : Nat) : Set where
pzero : Pat n
psuc : Pat n → Pat n
data Cat : Nat → Set where
cat : ∀ {n} → Cat (suc n)
postulate
up : ∀ {n} → (Cat n → Cat n) → Cat (suc n)
down : ∀ {n} → Cat (suc n) → Cat n
rectify-works : ∀ {x y} → Pat x → Pat y
rectify-fails : ∀ {x y} → Pat x → Pat (id y)
test-works1 : ∀ {n} → Pat n → Cat n → Cat n
test-works1 (psuc t) acc = down (up (test-works1 t))
test-works1 t cat = up (test-works1 (rectify-works t))
{-# TERMINATING #-}
test-fails2 : ∀ {n} → Pat n → Cat n → Cat n
test-fails2 (psuc t) acc = down (up (test-fails2 t))
test-fails2 t cat = up (test-fails2 (rectify-fails t))
test-works3 : ∀ {n} → Pat n → Cat n → Cat n
test-works3 (psuc t) cat = down (up (test-works3 t))
test-works3 t@pzero (cat {n = n}) = up (test-works3 {n = n} (rectify-fails t))
|
(*
Authors: Asta Halkjær From, Agnes Moesgård Eschen & Jørgen Villadsen, DTU Compute
*)
theory System_M1 imports System_L1 begin
text \<open>Mendelson\<close>
inductive M (\<open>\<MM>\<close>) where
M_MP: \<open>\<MM> q\<close> if \<open>\<MM> p\<close> and \<open>\<MM> (p \<rightarrow> q)\<close> |
M_1: \<open>\<MM> (p \<rightarrow> (q \<rightarrow> p))\<close> |
M_2: \<open>\<MM> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)))\<close> |
M_3: \<open>\<MM> (((\<sim> p) \<rightarrow> (\<sim> q)) \<rightarrow> (((\<sim> p) \<rightarrow> q) \<rightarrow> p))\<close>
lemma M_4: \<open>\<MM> ((\<sim> p) \<rightarrow> (((\<sim> q) \<rightarrow> (\<sim> p)) \<rightarrow> (p \<rightarrow> q)))\<close>
using M_1 M_2 M_3 M_MP by metis
lemma M_5: \<open>\<MM> ((\<sim> p) \<rightarrow> (p \<rightarrow> q))\<close>
using M_1 M_2 M_4 M_MP by metis
lemma M_6: \<open>\<MM> (((\<sim> q) \<rightarrow> q) \<rightarrow> ((\<sim> q) \<rightarrow> p))\<close>
using M_2 M_5 M_MP by metis
lemma M_7: \<open>\<MM> (q \<rightarrow> (((\<sim> q) \<rightarrow> q) \<rightarrow> ((\<sim> q) \<rightarrow> p)))\<close>
using M_1 M_6 M_MP by metis
lemma M_8: \<open>\<MM> (q \<rightarrow> ((\<sim> q) \<rightarrow> p))\<close>
using M_1 M_2 M_7 M_MP by metis
lemma M_9: \<open>\<MM> (p \<rightarrow> ((\<sim> p) \<rightarrow> q))\<close>
using M_8.
lemma M_10: \<open>\<MM> ((q \<rightarrow> r) \<rightarrow> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r))))\<close>
using M_1 M_2 M_MP by metis
lemma M_11: \<open>\<MM> ((q \<rightarrow> r) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_1 M_2 M_10 M_MP by metis
lemma M_12: \<open>\<MM> (((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> q)) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_2 M_11 M_MP by metis
lemma M_13: \<open>\<MM> ((p \<rightarrow> q) \<rightarrow> (((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> q)) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r))))\<close>
using M_1 M_12 M_MP by metis
lemma M_14: \<open>\<MM> ((p \<rightarrow> q) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_1 M_2 M_13 M_MP by metis
lemma M_15: \<open>\<MM> (((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> (p \<rightarrow> q)) \<rightarrow> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_2 M_MP by metis
lemma M_16: \<open>\<MM> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> p))\<close>
using M_1 M_2 M_MP by metis
lemma M_17: \<open>\<MM> (p \<rightarrow> p)\<close>
using M_1 M_16 M_MP by metis
lemma M_18: \<open>\<MM> ((p \<rightarrow> (p \<rightarrow> q)) \<rightarrow> (p \<rightarrow> p))\<close>
using M_1 M_17 M_MP by metis (* under substitution this lemma is the same as M_16 *)
lemma M_19: \<open>\<MM> ((p \<rightarrow> (p \<rightarrow> q)) \<rightarrow> (p \<rightarrow> q))\<close>
using M_15 M_18 M_MP by metis
lemma M_20: \<open>\<MM> (((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)) \<rightarrow> ((q \<rightarrow> (p \<rightarrow> q)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> r))))\<close>
using M_11.
lemma M_21: \<open>\<MM> (((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> q)))\<close>
using M_1 M_MP by metis
lemma M_22: \<open>\<MM> (((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> r)))\<close>
using M_2 M_20 M_21 M_MP by metis
lemma M_23: \<open>\<MM> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> r)))\<close>
using M_2 M_11 M_22 M_MP by metis
lemma M_24: \<open>\<MM> (((\<sim> q) \<rightarrow> (\<sim> p)) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_3 M_11 M_14 M_MP oops
lemma M_25: \<open>\<MM> (((\<sim> q) \<rightarrow> q) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close>
using M_6 M_11 M_MP oops
lemma M_26: \<open>\<MM> (((\<sim> q) \<rightarrow> q) \<rightarrow> (((\<sim> q) \<rightarrow> q) \<rightarrow> q))\<close>
using M_17 M_23 M_MP by (metis M_1 M_3)
lemma M_27: \<open>\<MM> (((\<sim> p) \<rightarrow> p) \<rightarrow> p)\<close>
using M_19 M_26 M_MP by metis
theorem M_iff_L1: \<open>\<MM> p \<longleftrightarrow> \<turnstile> p\<close>
proof
have L1_M_1: \<open>\<turnstile> (p \<rightarrow> (q \<rightarrow> p))\<close> for p q
using L1_completeness by simp
have L1_M_2: \<open>\<turnstile> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)))\<close> for p q r
using L1_completeness by simp
have L1_M_3: \<open>\<turnstile> (((\<sim> p) \<rightarrow> (\<sim> q)) \<rightarrow> (((\<sim> p) \<rightarrow> q) \<rightarrow> p))\<close> for p q
using L1_completeness by simp
show \<open>\<turnstile> p\<close> if \<open>\<MM> p\<close>
using that by (induct) (metis MP, metis L1_M_1, metis L1_M_2, metis L1_M_3)
show \<open>\<MM> p\<close> if \<open>\<turnstile> p\<close>
using that by (induct) (metis M_MP, metis M_14, metis M_27, metis M_9)
qed
theorem M_soundness: \<open>\<MM> p \<Longrightarrow> I \<Turnstile> p\<close>
by (induct rule: M.induct) auto
theorem M_completeness: \<open>\<forall>I. (I \<Turnstile> p) \<Longrightarrow> \<MM> p\<close>
using M_iff_L1 by (simp add: L1_completeness)
section \<open>Soundness and Completeness\<close>
theorem main: \<open>valid p = \<MM> p\<close>
unfolding valid_def using M_soundness M_completeness by blast
lemmas M1 = M.intros main
end
|
lemma and_trans (P Q R : Prop) : P ∧ Q → Q ∧ R → P ∧ R :=
begin
intros pq qr,
cases pq with p q,
cases qr with q r,
split,
{
exact p,
},
{
exact r,
},
end |
% clc; clear all; close all;
%% hydro data
hydro = struct();
hydro = readAQWA(hydro, 'WEC3.AH1', 'WEC3.LIS');
hydro = radiationIRF(hydro,100,[],[],[],[]);
hydro = radiationIRFSS(hydro,[],[]);
hydro = excitationIRF(hydro,100,[],[],[],[]);
writeBEMIOH5(hydro)
%% Plot hydro data
% plotBEMIO(hydro)
|
% !TeX root = ../main.tex
% Add the above to each chapter to make compiling the PDF easier in some editors.
\section{Section}
Citation test \parencite{Devlin:2018}.
|
State Before: n : ℕ
⊢ antidiagonal (n + 1) = (n + 1, 0) ::ₘ map (Prod.map id Nat.succ) (antidiagonal n) State After: no goals Tactic: rw [antidiagonal, List.Nat.antidiagonal_succ', ← coe_add, add_comm, antidiagonal, coe_map,
coe_add, List.singleton_append, cons_coe] |
import os
from astropy.tests.helper import assert_quantity_allclose
from specutils import Spectrum1D
def test_create_filters(specviz_gui):
workspace = specviz_gui.add_workspace()
filters, loader_name_map = workspace._create_loader_filters()
# Simple sanity test to make sure regression was removed
assert filters[0] == 'Auto (*)'
assert loader_name_map['Auto (*)'] is None
def test_export_data(specviz_gui, tmpdir):
fname = str(tmpdir.join('export.ecsv'))
workspace = specviz_gui._workspaces[0]
data_item = workspace.current_item
workspace.export_data_item(data_item, fname, '*.ecsv')
assert os.path.isfile(fname)
exported = Spectrum1D.read(fname, format='ECSV')
original = data_item.data_item.spectrum
assert_quantity_allclose(exported.flux, original.flux)
assert_quantity_allclose(exported.spectral_axis, original.spectral_axis)
if original.uncertainty is None:
assert exported.uncertainty is None
else:
assert_quantity_allclose(exported.uncertainty, original.uncertainty)
|
/-
Copyright (c) 2020 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
! This file was ported from Lean 3 source module data.polynomial.lifts
! leanprover-community/mathlib commit 63417e01fbc711beaf25fa73b6edb395c0cfddd0
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.Polynomial.AlgebraMap
import Mathlib.Data.Polynomial.Monic
/-!
# Polynomials that lift
Given semirings `R` and `S` with a morphism `f : R →+* S`, we define a subsemiring `lifts` of
`S[X]` by the image of `RingHom.of (map f)`.
Then, we prove that a polynomial that lifts can always be lifted to a polynomial of the same degree
and that a monic polynomial that lifts can be lifted to a monic polynomial (of the same degree).
## Main definition
* `lifts (f : R →+* S)` : the subsemiring of polynomials that lift.
## Main results
* `lifts_and_degree_eq` : A polynomial lifts if and only if it can be lifted to a polynomial
of the same degree.
* `lifts_and_degree_eq_and_monic` : A monic polynomial lifts if and only if it can be lifted to a
monic polynomial of the same degree.
* `lifts_iff_alg` : if `R` is commutative, a polynomial lifts if and only if it is in the image of
`mapAlg`, where `mapAlg : R[X] →ₐ[R] S[X]` is the only `R`-algebra map
that sends `X` to `X`.
## Implementation details
In general `R` and `S` are semiring, so `lifts` is a semiring. In the case of rings, see
`lifts_iff_lifts_ring`.
Since we do not assume `R` to be commutative, we cannot say in general that the set of polynomials
that lift is a subalgebra. (By `lift_iff` this is true if `R` is commutative.)
-/
open Classical BigOperators Polynomial
noncomputable section
namespace Polynomial
universe u v w
section Semiring
variable {R : Type u} [Semiring R] {S : Type v} [Semiring S] {f : R →+* S}
/-- We define the subsemiring of polynomials that lifts as the image of `RingHom.of (map f)`. -/
def lifts (f : R →+* S) : Subsemiring S[X] :=
RingHom.rangeS (mapRingHom f)
#align polynomial.lifts Polynomial.lifts
theorem mem_lifts (p : S[X]) : p ∈ lifts f ↔ ∃ q : R[X], map f q = p := by
simp only [coe_mapRingHom, lifts, RingHom.mem_rangeS]
#align polynomial.mem_lifts Polynomial.mem_lifts
theorem lifts_iff_set_range (p : S[X]) : p ∈ lifts f ↔ p ∈ Set.range (map f) := by
simp only [coe_mapRingHom, lifts, Set.mem_range, RingHom.mem_rangeS]
#align polynomial.lifts_iff_set_range Polynomial.lifts_iff_set_range
theorem lifts_iff_ringHom_rangeS (p : S[X]) : p ∈ lifts f ↔ p ∈ (mapRingHom f).rangeS := by
simp only [coe_mapRingHom, lifts, Set.mem_range, RingHom.mem_rangeS]
#align polynomial.lifts_iff_ring_hom_srange Polynomial.lifts_iff_ringHom_rangeS
theorem lifts_iff_coeff_lifts (p : S[X]) : p ∈ lifts f ↔ ∀ n : ℕ, p.coeff n ∈ Set.range f := by
rw [lifts_iff_ringHom_rangeS, mem_map_rangeS f]
rfl
#align polynomial.lifts_iff_coeff_lifts Polynomial.lifts_iff_coeff_lifts
/-- If `(r : R)`, then `C (f r)` lifts. -/
theorem C_mem_lifts (f : R →+* S) (r : R) : C (f r) ∈ lifts f :=
⟨C r, by
simp only [coe_mapRingHom, map_C, Set.mem_univ, Subsemiring.coe_top, eq_self_iff_true,
and_self_iff]⟩
set_option linter.uppercaseLean3 false in
#align polynomial.C_mem_lifts Polynomial.C_mem_lifts
/-- If `(s : S)` is in the image of `f`, then `C s` lifts. -/
theorem C'_mem_lifts {f : R →+* S} {s : S} (h : s ∈ Set.range f) : C s ∈ lifts f := by
obtain ⟨r, rfl⟩ := Set.mem_range.1 h
use C r
simp only [coe_mapRingHom, map_C, Set.mem_univ, Subsemiring.coe_top, eq_self_iff_true,
and_self_iff]
set_option linter.uppercaseLean3 false in
#align polynomial.C'_mem_lifts Polynomial.C'_mem_lifts
/-- The polynomial `X` lifts. -/
theorem X_mem_lifts (f : R →+* S) : (X : S[X]) ∈ lifts f :=
⟨X, by
simp only [coe_mapRingHom, Set.mem_univ, Subsemiring.coe_top, eq_self_iff_true, map_X,
and_self_iff]⟩
set_option linter.uppercaseLean3 false in
#align polynomial.X_mem_lifts Polynomial.X_mem_lifts
/-- The polynomial `X ^ n` lifts. -/
theorem X_pow_mem_lifts (f : R →+* S) (n : ℕ) : (X ^ n : S[X]) ∈ lifts f :=
⟨X ^ n, by
simp only [coe_mapRingHom, map_pow, Set.mem_univ, Subsemiring.coe_top, eq_self_iff_true,
map_X, and_self_iff]⟩
set_option linter.uppercaseLean3 false in
#align polynomial.X_pow_mem_lifts Polynomial.X_pow_mem_lifts
/-- If `p` lifts and `(r : R)` then `r * p` lifts. -/
theorem base_mul_mem_lifts {p : S[X]} (r : R) (hp : p ∈ lifts f) : C (f r) * p ∈ lifts f := by
simp only [lifts, RingHom.mem_rangeS] at hp⊢
obtain ⟨p₁, rfl⟩ := hp
use C r * p₁
simp only [coe_mapRingHom, map_C, map_mul]
#align polynomial.base_mul_mem_lifts Polynomial.base_mul_mem_lifts
/-- If `(s : S)` is in the image of `f`, then `monomial n s` lifts. -/
theorem monomial_mem_lifts {s : S} (n : ℕ) (h : s ∈ Set.range f) : monomial n s ∈ lifts f := by
obtain ⟨r, rfl⟩ := Set.mem_range.1 h
use monomial n r
simp only [coe_mapRingHom, Set.mem_univ, map_monomial, Subsemiring.coe_top, eq_self_iff_true,
and_self_iff]
#align polynomial.monomial_mem_lifts Polynomial.monomial_mem_lifts
/-- If `p` lifts then `p.erase n` lifts. -/
theorem erase_mem_lifts {p : S[X]} (n : ℕ) (h : p ∈ lifts f) : p.erase n ∈ lifts f := by
rw [lifts_iff_ringHom_rangeS, mem_map_rangeS] at h⊢
intro k
by_cases hk : k = n
· use 0
simp only [hk, RingHom.map_zero, erase_same]
obtain ⟨i, hi⟩ := h k
use i
simp only [hi, hk, erase_ne, Ne.def, not_false_iff]
#align polynomial.erase_mem_lifts Polynomial.erase_mem_lifts
section LiftDeg
theorem monomial_mem_lifts_and_degree_eq {s : S} {n : ℕ} (hl : monomial n s ∈ lifts f) :
∃ q : R[X], map f q = monomial n s ∧ q.degree = (monomial n s).degree := by
by_cases hzero : s = 0
· use 0
simp only [hzero, degree_zero, eq_self_iff_true, and_self_iff, monomial_zero_right,
Polynomial.map_zero]
rw [lifts_iff_set_range] at hl
obtain ⟨q, hq⟩ := hl
replace hq := (ext_iff.1 hq) n
have hcoeff : f (q.coeff n) = s := by
simp [coeff_monomial] at hq
exact hq
use monomial n (q.coeff n)
constructor
· simp only [hcoeff, map_monomial]
have hqzero : q.coeff n ≠ 0 := by
intro habs
simp only [habs, RingHom.map_zero] at hcoeff
exact hzero hcoeff.symm
rw [← C_mul_X_pow_eq_monomial]
rw [← C_mul_X_pow_eq_monomial]
simp only [hzero, hqzero, Ne.def, not_false_iff, degree_C_mul_X_pow]
#align polynomial.monomial_mem_lifts_and_degree_eq Polynomial.monomial_mem_lifts_and_degree_eq
/-- A polynomial lifts if and only if it can be lifted to a polynomial of the same degree. -/
theorem mem_lifts_and_degree_eq {p : S[X]} (hlifts : p ∈ lifts f) :
∃ q : R[X], map f q = p ∧ q.degree = p.degree := by
generalize hd : p.natDegree = d
revert hd p
induction' d using Nat.strong_induction_on with n hn
intros p hlifts hdeg
by_cases erase_zero : p.eraseLead = 0
· rw [← eraseLead_add_monomial_natDegree_leadingCoeff p, erase_zero, zero_add, leadingCoeff]
exact
monomial_mem_lifts_and_degree_eq
(monomial_mem_lifts p.natDegree ((lifts_iff_coeff_lifts p).1 hlifts p.natDegree))
have deg_erase := Or.resolve_right (eraseLead_natDegree_lt_or_eraseLead_eq_zero p) erase_zero
have pzero : p ≠ 0 := by
intro habs
exfalso
rw [habs, eraseLead_zero, eq_self_iff_true, not_true] at erase_zero
exact erase_zero
have lead_zero : p.coeff p.natDegree ≠ 0 := by
rw [← leadingCoeff, Ne.def, leadingCoeff_eq_zero] ; exact pzero
obtain ⟨lead, hlead⟩ :=
monomial_mem_lifts_and_degree_eq
(monomial_mem_lifts p.natDegree ((lifts_iff_coeff_lifts p).1 hlifts p.natDegree))
have deg_lead : lead.degree = p.natDegree := by
rw [hlead.2, ← C_mul_X_pow_eq_monomial, degree_C_mul_X_pow p.natDegree lead_zero]
rw [hdeg] at deg_erase
obtain ⟨erase, herase⟩ :=
hn p.eraseLead.natDegree deg_erase (erase_mem_lifts p.natDegree hlifts)
(refl p.eraseLead.natDegree)
use erase + lead
constructor
· simp only [hlead, herase, Polynomial.map_add]
rw [←eraseLead, ←leadingCoeff]
rw [eraseLead_add_monomial_natDegree_leadingCoeff p]
rw [degree_eq_natDegree pzero, ←deg_lead]
apply degree_add_eq_right_of_degree_lt
rw [herase.2, deg_lead, ←degree_eq_natDegree pzero]
exact degree_erase_lt pzero
#align polynomial.mem_lifts_and_degree_eq Polynomial.mem_lifts_and_degree_eq
end LiftDeg
section Monic
/-- A monic polynomial lifts if and only if it can be lifted to a monic polynomial
of the same degree. -/
theorem lifts_and_degree_eq_and_monic [Nontrivial S] {p : S[X]} (hlifts : p ∈ lifts f)
(hp : p.Monic) : ∃ q : R[X], map f q = p ∧ q.degree = p.degree ∧ q.Monic := by
cases' subsingleton_or_nontrivial R with hR hR
· obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq hlifts
exact ⟨q, hq.1, hq.2, monic_of_subsingleton _⟩
have H : erase p.natDegree p + X ^ p.natDegree = p := by
simpa only [hp.leadingCoeff, C_1, one_mul, eraseLead] using eraseLead_add_C_mul_X_pow p
by_cases h0 : erase p.natDegree p = 0
· rw [← H, h0, zero_add]
refine' ⟨X ^ p.natDegree, _, _, monic_X_pow p.natDegree⟩
· rw [Polynomial.map_pow, map_X]
· rw [degree_X_pow, degree_X_pow]
obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq (erase_mem_lifts p.natDegree hlifts)
have p_neq_0 : p ≠ 0 := by intro hp; apply h0; rw [hp]; simp only [natDegree_zero, erase_zero]
have hdeg : q.degree < (X ^ p.natDegree).degree := by
rw [@degree_X_pow R, hq.2, ←degree_eq_natDegree p_neq_0]
exact degree_erase_lt p_neq_0
refine' ⟨q + X ^ p.natDegree, _, _, (monic_X_pow _).add_of_right hdeg⟩
· rw [Polynomial.map_add, hq.1, Polynomial.map_pow, map_X, H]
· rw [degree_add_eq_right_of_degree_lt hdeg, degree_X_pow, degree_eq_natDegree hp.ne_zero]
#align polynomial.lifts_and_degree_eq_and_monic Polynomial.lifts_and_degree_eq_and_monic
theorem lifts_and_natDegree_eq_and_monic {p : S[X]} (hlifts : p ∈ lifts f) (hp : p.Monic) :
∃ q : R[X], map f q = p ∧ q.natDegree = p.natDegree ∧ q.Monic := by
cases' subsingleton_or_nontrivial S with hR hR
· obtain rfl : p = 1 := Subsingleton.elim _ _
refine' ⟨1, Subsingleton.elim _ _, by simp, by simp⟩
obtain ⟨p', h₁, h₂, h₃⟩ := lifts_and_degree_eq_and_monic hlifts hp
exact ⟨p', h₁, natDegree_eq_of_degree_eq h₂, h₃⟩
#align polynomial.lifts_and_nat_degree_eq_and_monic Polynomial.lifts_and_natDegree_eq_and_monic
end Monic
end Semiring
section Ring
variable {R : Type u} [Ring R] {S : Type v} [Ring S] (f : R →+* S)
/-- The subring of polynomials that lift. -/
def liftsRing (f : R →+* S) : Subring S[X] :=
RingHom.range (mapRingHom f)
#align polynomial.lifts_ring Polynomial.liftsRing
/-- If `R` and `S` are rings, `p` is in the subring of polynomials that lift if and only if it is in
the subsemiring of polynomials that lift. -/
theorem lifts_iff_liftsRing (p : S[X]) : p ∈ lifts f ↔ p ∈ liftsRing f := by
simp only [lifts, liftsRing, RingHom.mem_range, RingHom.mem_rangeS]
#align polynomial.lifts_iff_lifts_ring Polynomial.lifts_iff_liftsRing
end Ring
section Algebra
variable {R : Type u} [CommSemiring R] {S : Type v} [Semiring S] [Algebra R S]
/-- The map `R[X] → S[X]` as an algebra homomorphism. -/
def mapAlg (R : Type u) [CommSemiring R] (S : Type v) [Semiring S] [Algebra R S] :
R[X] →ₐ[R] S[X] :=
@aeval _ S[X] _ _ _ (X : S[X])
#align polynomial.map_alg Polynomial.mapAlg
/-- `mapAlg` is the morphism induced by `R → S`. -/
theorem mapAlg_eq_map (p : R[X]) : mapAlg R S p = map (algebraMap R S) p := by
simp only [mapAlg, aeval_def, eval₂_eq_sum, map, algebraMap_apply, RingHom.coe_comp]
ext; congr
#align polynomial.map_alg_eq_map Polynomial.mapAlg_eq_map
/-- A polynomial `p` lifts if and only if it is in the image of `mapAlg`. -/
theorem mem_lifts_iff_mem_alg (R : Type u) [CommSemiring R] {S : Type v} [Semiring S] [Algebra R S]
(p : S[X]) : p ∈ lifts (algebraMap R S) ↔ p ∈ AlgHom.range (@mapAlg R _ S _ _) := by
simp only [coe_mapRingHom, lifts, mapAlg_eq_map, AlgHom.mem_range, RingHom.mem_rangeS]
#align polynomial.mem_lifts_iff_mem_alg Polynomial.mem_lifts_iff_mem_alg
/-- If `p` lifts and `(r : R)` then `r • p` lifts. -/
theorem smul_mem_lifts {p : S[X]} (r : R) (hp : p ∈ lifts (algebraMap R S)) :
r • p ∈ lifts (algebraMap R S) := by
rw [mem_lifts_iff_mem_alg] at hp⊢
exact Subalgebra.smul_mem (mapAlg R S).range hp r
#align polynomial.smul_mem_lifts Polynomial.smul_mem_lifts
end Algebra
end Polynomial
|
integer x,y
read x,y
x = 10
write "Hello", x, y
end
real list function LL (integer y, real list w)
integer MESA
return
end
subroutine A(integer n, x(n), logical z(100))
complex c(3)
integer i
data i/1/, x/.true./, c/(3.2:1.8),(3.1:0.3),(0.:-3.4)/
A = 0
return
end
subroutine S
return
end |
module test
abstract interface
subroutine foo()
end subroutine
end interface
end module test
|
/-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import algebra.big_operators.order
import algebra.big_operators.ring
import algebra.char_zero.lemmas
import data.rat.cast
/-!
# The Oxford Invariants Puzzle Challenges - Summer 2021, Week 3, Problem 1
## Original statement
Let `n ≥ 3`, `a₁, ..., aₙ` be strictly positive integers such that `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` for
`i = 2, ..., n - 1`. Show that $\sum_{i=1}^{n-1}\dfrac{a_0a_n}{a_ia_{i+1}} ∈ \mathbb N$.
## Comments
Mathlib is based on type theory, so saying that a rational is a natural doesn't make sense. Instead,
we ask that there exists `b : ℕ` whose cast to `α` is the sum we want.
In mathlib, `ℕ` starts at `0`. To make the indexing cleaner, we use `a₀, ..., aₙ₋₁` instead of
`a₁, ..., aₙ`. Similarly, it's nicer to not use subtraction of naturals, so we replace
`aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` by `aᵢ₊₁ ∣ aᵢ + aᵢ₊₂`.
We don't actually have to work in `ℚ` or `ℝ`. We can be even more general by stating the result for
any linearly ordered field.
Instead of having `n` naturals, we use a function `a : ℕ → ℕ`.
In the proof itself, we replace `n : ℕ, 1 ≤ n` by `n + 1`.
The statement is actually true for `n = 0, 1` (`n = 1, 2` before the reindexing) as the sum is
simply `0` and `1` respectively. So the version we prove is slightly more general.
Overall, the indexing is a bit of a mess to understand. But, trust Lean, it works.
## Formalised statement
Let `n : ℕ`, `a : ℕ → ℕ`, `∀ i ≤ n, 0 < a i`, `∀ i, i + 2 ≤ n → aᵢ₊₁ ∣ aᵢ + aᵢ₊₂` (read `→` as
"implies"). Then there exists `b : ℕ` such that `b` as an element of any linearly ordered field
equals $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$.
## Proof outline
The case `n = 0` is trivial.
For `n + 1`, we prove the result by induction but by adding `aₙ₊₁ ∣ aₙ * b - a₀` to the induction
hypothesis, where `b` is the previous sum, $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$, as a
natural.
* Base case:
* $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1})$ is a natural:
$\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1}) = (a_0 a_1) / (a_0 a_1) = 1$.
* Divisibility condition:
`a₀ * 1 - a₀ = 0` is clearly divisible by `a₁`.
* Induction step:
* $\sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1})$ is a natural:
$$\sum_{i=0}^{n+1} (a_0 a_{n+2}) / (a_i a_{i+1})
= \sum_{i=0}^n\ (a_0 a_{n+2}) / (a_i a_{i+1}) + (a_0 a_{n+2}) / (a_{n+1} a_{n+2})
= a_{n+2} / a_{n+1} × \sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1}) + a_0 / a_{n+1}
= a_{n+2} / a_{n+1} × b + a_0 / a_{n+1}
= (a_n + a_{n+2}) / a_{n+1} × b - (a_n b - a_0)(a_{n+1})$$
which is a natural because `(aₙ + aₙ₊₂)/aₙ₊₁`, `b` and `(aₙ * b - a₀)/aₙ₊₁` are (plus an
annoying inequality, or the fact that the original sum is positive because its terms are).
* Divisibility condition:
`aₙ₊₁ * ((aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁) - a₀ = aₙ₊₁aₙ₊₂b` is divisible by `aₙ₊₂`.
-/
open_locale big_operators
variables {α : Type*} [linear_ordered_field α]
theorem week3_p1 (n : ℕ) (a : ℕ → ℕ) (a_pos : ∀ i ≤ n, 0 < a i)
(ha : ∀ i, i + 2 ≤ n → a (i + 1) ∣ a i + a (i + 2)) :
∃ b : ℕ, (b : α) = ∑ i in finset.range n, (a 0 * a n)/(a i * a (i + 1)) :=
begin
-- Treat separately `n = 0` and `n ≥ 1`
cases n,
/- Case `n = 0`
The sum is trivially equal to `0` -/
{ exact ⟨0, by rw [nat.cast_zero, finset.sum_range_zero]⟩ }, -- `⟨Claim it, Prove it⟩`
/- Case `n ≥ 1`. We replace `n` by `n + 1` everywhere to make this inequality explicit
Set up the stronger induction hypothesis -/
rsuffices ⟨b, hb, -⟩ :
∃ b : ℕ, (b : α) = ∑ i in finset.range (n + 1), (a 0 * a (n + 1)) / (a i * a (i + 1))
∧ a (n + 1) ∣ a n * b - a 0,
{ exact ⟨b, hb⟩ },
simp_rw ←@nat.cast_pos α at a_pos,
/- Declare the induction
`ih` will be the induction hypothesis -/
induction n with n ih,
/- Base case
Claim that the sum equals `1`-/
{ refine ⟨1, _, _⟩,
-- Check that this indeed equals the sum
{ rw [nat.cast_one, finset.sum_range_one, div_self],
exact (mul_pos (a_pos 0 (nat.zero_le _)) (a_pos 1 (nat.zero_lt_succ _))).ne' },
-- Check the divisibility condition
{ rw [mul_one, tsub_self],
exact dvd_zero _ } },
/- Induction step
`b` is the value of the previous sum as a natural, `hb` is the proof that it is indeed the value,
and `han` is the divisibility condition -/
obtain ⟨b, hb, han⟩ := ih (λ i hi, ha i $ nat.le_succ_of_le hi)
(λ i hi, a_pos i $ nat.le_succ_of_le hi),
specialize ha n le_rfl,
have ha₀ : a 0 ≤ a n * b, -- Needing this is an artifact of `ℕ`-subtraction.
{ rw [←@nat.cast_le α, nat.cast_mul, hb, ←div_le_iff' (a_pos _ $ n.le_succ.trans $ nat.le_succ _),
←mul_div_mul_right _ _ (a_pos _ $ nat.le_succ _).ne'],
suffices h : ∀ i, i ∈ finset.range (n + 1) → 0 ≤ (a 0 : α) * a (n + 1) / (a i * a (i + 1)),
{ exact finset.single_le_sum h (finset.self_mem_range_succ n) },
refine (λ i _, div_nonneg _ _); refine mul_nonneg _ _; exact nat.cast_nonneg _ },
-- Claim that the sum equals `(aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁`
refine ⟨(a n + a (n + 2))/ a (n + 1) * b - (a n * b - a 0) / a (n + 1), _, _⟩,
-- Check that this indeed equals the sum
{ calc
(((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : ℕ) : α)
= (a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : begin
norm_cast,
rw nat.cast_sub (nat.div_le_of_le_mul _),
rw [←mul_assoc, nat.mul_div_cancel' ha, add_mul],
exact tsub_le_self.trans (nat.le_add_right _ _),
end
... = a (n + 2) / a (n + 1) * b + (a 0 * a (n + 2)) / (a (n + 1) * a (n + 2))
: by rw [add_div, add_mul, sub_div, mul_div_right_comm, add_sub_sub_cancel,
mul_div_mul_right _ _ (a_pos _ le_rfl).ne']
... = ∑ (i : ℕ) in finset.range (n + 2), a 0 * a (n + 2) / (a i * a (i + 1))
: begin
rw [finset.sum_range_succ, hb, finset.mul_sum],
congr, ext i,
rw [←mul_div_assoc, ←mul_div_right_comm, mul_div_assoc, mul_div_cancel _
(a_pos _ $ nat.le_succ _).ne', mul_comm],
end },
-- Check the divisibility condition
{ rw [mul_tsub, ← mul_assoc, nat.mul_div_cancel' ha, add_mul,
nat.mul_div_cancel' han, add_tsub_tsub_cancel ha₀, add_tsub_cancel_right],
exact dvd_mul_right _ _ }
end
|
lemma cos_arg_i_mult_zero [simp]: "y \<noteq> 0 \<Longrightarrow> Re y = 0 \<Longrightarrow> cos (arg y) = 0" |
import tactic.interactive
example : ¬ ∀ (α : Type) (r : Prop), r → (∃ x : α, r) :=
begin
intro h,
cases h empty _ true.intro with w,
cases w
end
example (α : Type) [inhabited α] (r : Prop) : r → (∃ x : α, r) :=
λ h, ⟨inhabited.default α, h⟩
#print foo
|
module _ (A : Set) where
data A where
|
[STATEMENT]
lemma smcf_proj_fst_is_semifunctor:
assumes "i \<in>\<^sub>\<circ> I"
shows "\<pi>\<^sub>S\<^sub>M\<^sub>C\<^sub>.\<^sub>1 \<AA> \<BB> : \<AA> \<times>\<^sub>S\<^sub>M\<^sub>C \<BB> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<pi>\<^sub>S\<^sub>M\<^sub>C\<^sub>.\<^sub>1 \<AA> \<BB> : \<AA> \<times>\<^sub>S\<^sub>M\<^sub>C \<BB> \<mapsto>\<mapsto>\<^sub>S\<^sub>M\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>
[PROOF STEP]
by
(
rule
psmc_smcf_proj_is_semifunctor[
where i=0, simplified, folded smcf_proj_fst_def smc_prod_2_def
]
) |
Formal statement is: lemma convex_prod: assumes "\<And>i. i \<in> Basis \<Longrightarrow> convex {x. P i x}" shows "convex {x. \<forall>i\<in>Basis. P i (x\<bullet>i)}" Informal statement is: If $P_i$ is a convex set for each $i \in \{1, \ldots, n\}$, then the set $\{(x_1, \ldots, x_n) \in \mathbb{R}^n \mid x_i \in P_i \text{ for all } i\}$ is convex. |
/-
Copyright (c) 2021 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
! This file was ported from Lean 3 source module category_theory.limits.constructions.weakly_initial
! leanprover-community/mathlib commit 239d882c4fb58361ee8b3b39fb2091320edef10a
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.CategoryTheory.Limits.Shapes.WideEqualizers
import Mathbin.CategoryTheory.Limits.Shapes.Products
import Mathbin.CategoryTheory.Limits.Shapes.Terminal
/-!
# Constructions related to weakly initial objects
This file gives constructions related to weakly initial objects, namely:
* If a category has small products and a small weakly initial set of objects, then it has a weakly
initial object.
* If a category has wide equalizers and a weakly initial object, then it has an initial object.
These are primarily useful to show the General Adjoint Functor Theorem.
-/
universe v u
namespace CategoryTheory
open Limits
variable {C : Type u} [Category.{v} C]
/--
If `C` has (small) products and a small weakly initial set of objects, then it has a weakly initial
object.
-/
theorem has_weakly_initial_of_weakly_initial_set_and_hasProducts [HasProducts.{v} C] {ι : Type v}
{B : ι → C} (hB : ∀ A : C, ∃ i, Nonempty (B i ⟶ A)) : ∃ T : C, ∀ X, Nonempty (T ⟶ X) :=
⟨∏ B, fun X => ⟨Pi.π _ _ ≫ (hB X).choose_spec.some⟩⟩
#align category_theory.has_weakly_initial_of_weakly_initial_set_and_has_products CategoryTheory.has_weakly_initial_of_weakly_initial_set_and_hasProducts
/-- If `C` has (small) wide equalizers and a weakly initial object, then it has an initial object.
The initial object is constructed as the wide equalizer of all endomorphisms on the given weakly
initial object.
-/
theorem hasInitial_of_weakly_initial_and_hasWideEqualizers [HasWideEqualizers.{v} C] {T : C}
(hT : ∀ X, Nonempty (T ⟶ X)) : HasInitial C :=
by
let endos := T ⟶ T
let i := wide_equalizer.ι (id : endos → endos)
haveI : Nonempty endos := ⟨𝟙 _⟩
have : ∀ X : C, Unique (wide_equalizer (id : endos → endos) ⟶ X) :=
by
intro X
refine' ⟨⟨i ≫ Classical.choice (hT X)⟩, fun a => _⟩
let E := equalizer a (i ≫ Classical.choice (hT _))
let e : E ⟶ wide_equalizer id := equalizer.ι _ _
let h : T ⟶ E := Classical.choice (hT E)
have : ((i ≫ h) ≫ e) ≫ i = i ≫ 𝟙 _ :=
by
rw [category.assoc, category.assoc]
apply wide_equalizer.condition (id : endos → endos) (h ≫ e ≫ i)
rw [category.comp_id, cancel_mono_id i] at this
haveI : is_split_epi e := is_split_epi.mk' ⟨i ≫ h, this⟩
rw [← cancel_epi e]
apply equalizer.condition
exact has_initial_of_unique (wide_equalizer (id : endos → endos))
#align category_theory.has_initial_of_weakly_initial_and_has_wide_equalizers CategoryTheory.hasInitial_of_weakly_initial_and_hasWideEqualizers
end CategoryTheory
|
open import Relation.Binary.Core
module PLRTree.Insert.Properties {A : Set}
(_≤_ : A → A → Set)
(tot≤ : Total _≤_) where
open import Data.Sum
open import PLRTree {A}
open import PLRTree.Compound {A}
open import PLRTree.Insert _≤_ tot≤
lemma-insert-compound : (x : A)(t : PLRTree) → Compound (insert x t)
lemma-insert-compound x leaf = compound
lemma-insert-compound x (node perfect y l r)
with tot≤ x y | l | r
... | inj₁ x≤y | leaf | leaf = compound
... | inj₁ x≤y | leaf | node _ _ _ _ = compound
... | inj₁ x≤y | node _ _ _ _ | leaf = compound
... | inj₁ x≤y | node _ _ _ _ | node _ _ _ _ = compound
... | inj₂ y≤x | leaf | leaf = compound
... | inj₂ y≤x | leaf | node _ _ _ _ = compound
... | inj₂ y≤x | node _ _ _ _ | leaf = compound
... | inj₂ y≤x | node _ _ _ _ | node _ _ _ _ = compound
lemma-insert-compound x (node left y l _)
with tot≤ x y
... | inj₁ x≤y
with insert y l | lemma-insert-compound y l
... | node perfect _ _ _ | compound = compound
... | node left _ _ _ | compound = compound
... | node right _ _ _ | compound = compound
lemma-insert-compound x (node left y l _) | inj₂ y≤x
with insert x l | lemma-insert-compound x l
... | node perfect _ _ _ | compound = compound
... | node left _ _ _ | compound = compound
... | node right _ _ _ | compound = compound
lemma-insert-compound x (node right y _ r)
with tot≤ x y
... | inj₁ x≤y
with insert y r | lemma-insert-compound y r
... | node perfect _ _ _ | compound = compound
... | node left _ _ _ | compound = compound
... | node right _ _ _ | compound = compound
lemma-insert-compound x (node right y _ r) | inj₂ y≤x
with insert x r | lemma-insert-compound x r
... | node perfect _ _ _ | compound = compound
... | node left _ _ _ | compound = compound
... | node right _ _ _ | compound = compound
|
C
C Copyright (c) 2013-2017 The University of Tennessee and The University
C of Tennessee Research Foundation. All rights
C reserved.
C $COPYRIGHT$
C
C Additional copyrights may follow
C
C $HEADER$
C
C
C original code purely by Graham Fagg
C Oct-Nov 2000
C
C adopted to the new semantics of FTMPI by Edgar Gabriel
C July 2003
C
C reimplemented using ULFM by George Bosilca
C June 2010
C
C This program shows how to do a master-slave framework with FT-MPI. We
C introduce structures for the work and for each proc. This is
C necessary, since we are designing this example now to work with
C REBUILD, BLANK and SHRINK modes.
C
C Additionally, this example makes use of the two additional
C attributes of FT-MPI, which indicate who has died and how
C many have died. By activating the COLLECTIVE_CHECKWHODIED flag,
C a more portable (however also more expensive) version of the
C checkwhodied routines is invoked. Attention: the collective
C version of checkwhodied just works for the REBUILD mode!
C
C Graham Fagg 2000(c)
C Edgar Gabriel 2003(c)
C George Bosilca 2010(c)
C Aurelien Bouteiller 2016(c)
program fpift
implicit none
include "mpif.h"
include "mpif-ext.h"
include "fsolvergen.inc"
integer myrank, size, rc, comm
call MPI_Init ( rc )
call MPI_Comm_rank (MPI_COMM_WORLD, myrank, rc)
call MPI_Comm_size (MPI_COMM_WORLD, size, rc)
write (*,*) "I am [", myrank,"] of [", size, "]"
c Create my own communicator to play with
call MPI_Comm_dup(MPI_COMM_WORLD, comm, rc)
maxworkers = size-1
if ( myrank.eq.0) then
if(size.gt.MAXSIZE) then
write (*,*) "This program can use a maximum ", MAXSIZE,
& "processes."
call MPI_Abort(MPI_COMM_WORLD, 1)
end if
write (*,*) "I am [", myrank, "] and I will manage [",
& maxworkers, "] workers"
call master(comm)
else
call slave(comm)
end if
call MPI_Finalize (rc)
end
|
Definitely not “wasted” time. I think “Spending quality time together” would have been a more appropriate title. It was great to see everyone!
I agree! I hope it was just the title that suggested otherwise! |
/-
Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Aaron Anderson, Jalex Stark.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.matrix.char_p
import Mathlib.linear_algebra.char_poly.basic
import Mathlib.linear_algebra.matrix
import Mathlib.ring_theory.polynomial.basic
import Mathlib.algebra.polynomial.big_operators
import Mathlib.group_theory.perm.cycles
import Mathlib.field_theory.finite.basic
import Mathlib.PostPort
universes u v u_1
namespace Mathlib
/-!
# Characteristic polynomials
We give methods for computing coefficients of the characteristic polynomial.
## Main definitions
- `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial
over a nonzero ring is the dimension of the matrix
- `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic
polynomial, up to sign.
- `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the
characteristic polynomial, where d is the dimension of the matrix.
For a nonzero ring, this is the second-highest coefficient.
-/
theorem char_matrix_apply_nat_degree {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] {M : matrix n n R} [nontrivial R] (i : n) (j : n) :
polynomial.nat_degree (char_matrix M i j) = ite (i = j) 1 0 :=
sorry
theorem char_matrix_apply_nat_degree_le {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] {M : matrix n n R} (i : n) (j : n) :
polynomial.nat_degree (char_matrix M i j) ≤ ite (i = j) 1 0 :=
sorry
theorem char_poly_sub_diagonal_degree_lt {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] (M : matrix n n R) :
polynomial.degree
(char_poly M -
finset.prod finset.univ fun (i : n) => polynomial.X - coe_fn polynomial.C (M i i)) <
↑(fintype.card n - 1) :=
sorry
theorem char_poly_coeff_eq_prod_coeff_of_le {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] (M : matrix n n R) {k : ℕ} (h : fintype.card n - 1 ≤ k) :
polynomial.coeff (char_poly M) k =
polynomial.coeff
(finset.prod finset.univ fun (i : n) => polynomial.X - coe_fn polynomial.C (M i i)) k :=
sorry
theorem det_of_card_zero {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
(h : fintype.card n = 0) (M : matrix n n R) : matrix.det M = 1 :=
sorry
theorem char_poly_degree_eq_dim {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
[nontrivial R] (M : matrix n n R) : polynomial.degree (char_poly M) = ↑(fintype.card n) :=
sorry
theorem char_poly_nat_degree_eq_dim {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] [nontrivial R] (M : matrix n n R) :
polynomial.nat_degree (char_poly M) = fintype.card n :=
polynomial.nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M)
theorem char_poly_monic {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
(M : matrix n n R) : polynomial.monic (char_poly M) :=
sorry
theorem trace_eq_neg_char_poly_coeff {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] [Nonempty n] (M : matrix n n R) :
coe_fn (matrix.trace n R R) M = -polynomial.coeff (char_poly M) (fintype.card n - 1) :=
sorry
-- I feel like this should use polynomial.alg_hom_eval₂_algebra_map
theorem mat_poly_equiv_eval {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
(M : matrix n n (polynomial R)) (r : R) (i : n) (j : n) :
polynomial.eval (coe_fn (matrix.scalar n) r) (coe_fn mat_poly_equiv M) i j =
polynomial.eval r (M i j) :=
sorry
theorem eval_det {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
(M : matrix n n (polynomial R)) (r : R) :
polynomial.eval r (matrix.det M) =
matrix.det (polynomial.eval (coe_fn (matrix.scalar n) r) (coe_fn mat_poly_equiv M)) :=
sorry
theorem det_eq_sign_char_poly_coeff {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n]
[fintype n] (M : matrix n n R) :
matrix.det M = (-1) ^ fintype.card n * polynomial.coeff (char_poly M) 0 :=
sorry
@[simp] theorem finite_field.char_poly_pow_card {n : Type v} [DecidableEq n] [fintype n]
{K : Type u_1} [field K] [fintype K] (M : matrix n n K) :
char_poly (M ^ fintype.card K) = char_poly M :=
sorry
@[simp] theorem zmod.char_poly_pow_card {n : Type v} [DecidableEq n] [fintype n] {p : ℕ}
[fact (nat.prime p)] (M : matrix n n (zmod p)) : char_poly (M ^ p) = char_poly M :=
eq.mp (Eq._oldrec (Eq.refl (char_poly (M ^ fintype.card (zmod p)) = char_poly M)) (zmod.card p))
(finite_field.char_poly_pow_card M)
theorem finite_field.trace_pow_card {n : Type v} [DecidableEq n] [fintype n] {K : Type u_1}
[field K] [fintype K] [Nonempty n] (M : matrix n n K) :
coe_fn (matrix.trace n K K) (M ^ fintype.card K) =
coe_fn (matrix.trace n K K) M ^ fintype.card K :=
sorry
theorem zmod.trace_pow_card {n : Type v} [DecidableEq n] [fintype n] {p : ℕ} [fact (nat.prime p)]
[Nonempty n] (M : matrix n n (zmod p)) :
coe_fn (matrix.trace n (zmod p) (zmod p)) (M ^ p) =
coe_fn (matrix.trace n (zmod p) (zmod p)) M ^ p :=
sorry
namespace matrix
theorem is_integral {R : Type u} [comm_ring R] {n : Type v} [DecidableEq n] [fintype n]
(M : matrix n n R) : is_integral R M :=
Exists.intro (char_poly M) { left := char_poly_monic M, right := aeval_self_char_poly M }
theorem min_poly_dvd_char_poly {n : Type v} [DecidableEq n] [fintype n] {K : Type u_1} [field K]
(M : matrix n n K) : minpoly K M ∣ char_poly M :=
minpoly.dvd K M (aeval_self_char_poly M)
end Mathlib |
import combinatorics.simple_graph.coloring
--OUTPUT 1
theorem bipartite_two_colorable {G : Type*} [graph G] : two_colorable G ↔ bipartite G :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
have h1 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from
assume h2 : two_colorable G,
let A := {a : G | a.color = red} in
let B := {b : G | b.color = blue} in
have h3 : ∀ a : G, a ∈ A ∨ a ∈ B, from assume a : G,
or.elim (eq_or_ne (a.color) red)
(assume h4 : a.color = red, or.inl (by {exact set.mem_of_eq h4}))
(assume h5 : a.color ≠ red, or.inr (by {exact set.mem_of_ne h5})),
have h6 : ∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b), from assume a b : G,
assume h7 : a ∈ A ∧ b ∈ A,
assume h8 : a ≈ b,
have h9 : a.color = red ∧ b.color = red, from by {split,exact h7.left,exact h7.right},
have h10 : a.color = b.color, from by {rw h8,exact h9.left},
have h11 : false, from by {rw h10 at h9.right,exact h9.right.symm},
show ¬(a ≈ b), from by {exact false.elim h11},
have h12 : ∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b), from assume a b : G,
assume h7 : a ∈ B ∧ b ∈ B,
assume h8 : a ≈ b,
have h9 : a.color = blue ∧ b.color = blue, from by {split,exact h7.left,exact h7.right},
have h10 : a.color = b.color, from by {rw h8,exact h9.left},
have h11 : false, from by {rw h10 at h9.right,exact h9.right.symm},
show ¬(a ≈ b), from by {exact false.elim h11},
have h13 : ∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A), from assume a b : G,
assume h7 : a ≈ b,
have h8 : a.color = b.color, from by {rw h7},
or.elim (eq_or_ne (a.color) red)
(assume h9 : a.color = red, or.inl (by {split,exact set.mem_of_eq h9,exact set.mem_of_ne (by {rw h8 at h9,exact h9.symm})}))
(assume h10 : a.color ≠ red, or.inr (by {split,exact set.mem_of_ne h10,exact set.mem_of_eq (by {rw h8 at h10,exact h10.symm})})),
have h14 : ∀ a : G, a ∈ A ∨ a ∈ B, from h3,
have h15 : ∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b), from h6,
have h16 : ∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b), from h12,
have h17 : ∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A), from h13,
show ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from
exists.intro A (exists.intro B (and.intro h14 (and.intro h15 (and.intro h16 h17)))),
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h18 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from h1,
have h19 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from h1,
have h20 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from h1,
have h21 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G, a ≈ b → (a ∈ A ∧ b ∈ B) ∨ (a ∈ B ∧ b ∈ A)), from h1,
have h22 : two_colorable G → ∃ (A B : set G), (∀ a : G, a ∈ A ∨ a ∈ B) ∧ (∀ a b : G, a ∈ A ∧ b ∈ A → ¬(a ≈ b)) ∧ (∀ a b : G, a ∈ B ∧ b ∈ B → ¬(a ≈ b)) ∧ (∀ a b : G
end --Needs more than 2000 tokens!
--OUTPUT 2
theorem bipartite_iff_two_colorable (G : Type*) [graph G] : bipartite G ↔ two_colorable G :=
begin
split,
assume h1 : bipartite G,
show two_colorable G, from h1.two_colorable,
assume h2 : two_colorable G,
show bipartite G, from h2.bipartite,
end
--OUTPUT 3
theorem bipartite_graph_two_colorable (G : Type*) [decidable_eq G] [fintype G] [fintype (G × G)] :
(∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1)) ↔
(∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1)) :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color. Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue. Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$. This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h1 : (∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1)) →
(∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1)), from
assume (h : ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1)),
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
have h2 : ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1), from h,
have h3 : ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from
by {
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h4 : ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1), from h2,
have h5 : ∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2, from and.left h4,
have h6 : ∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1, from and.right h4,
have h7 : ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from
by {
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h8 : ∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2, from h5,
have h9 : ∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1, from h6,
have h10 : ∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2, from by {
assume (x y : G) (h : (x,y) ∈ G),
have h11 : (x,y) ∈ G, from h,
have h12 : x ∈ V1 ∧ y ∈ V2, from h8 x y h11,
have h13 : x ∈ V1, from and.left h12,
have h14 : y ∈ V2, from and.right h12,
show x ∈ V1 ∨ y ∈ V2, from or.inl h13,
},
have h11 : ∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1, from by {
assume (x y : G) (h : (x,y) ∈ G),
have h12 : (x,y) ∈ G, from h,
have h13 : x ∈ V2 ∧ y ∈ V1, from h9 x y h12,
have h14 : x ∈ V2, from and.left h13,
have h15 : y ∈ V1, from and.right h13,
show x ∈ V2 ∨ y ∈ V1, from or.inr h15,
},
show ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from
by {
use V1, use V2,
have h12 : (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from by {
split, exact h10, exact h11,
},
show (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from h12,
},
},
show ∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∨ y ∈ V1), from h7,
},
show (∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∧ y ∈ V2) ∧ (∀ (x y : G), (x,y) ∈ G → x ∈ V2 ∧ y ∈ V1)) →
(∃ (V1 V2 : set G), (∀ (x y : G), (x,y) ∈ G → x ∈ V1 ∨ y ∈ V2) ∧ (∀ (x y : G), (x,y)
end --Needs more than 2000 tokens!
--OUTPUT 4
theorem bipartite_graph_two_colorable {G : Type*} [graph G] : (∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E) ↔ (∃ f : G → ℕ, ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b) :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
have h1 : (∃ f : G → ℕ, ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b) → (∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E), from by {
assume hcol : (∃ f : G → ℕ, ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b),
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have hcol_def : ∃ f : G → ℕ, ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b, from hcol,
let f : G → ℕ := classical.some hcol_def,
have hcol_spec : ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b, from classical.some_spec hcol_def,
let A : set G := {v : G | f v = 0},
let B : set G := {v : G | f v = 1},
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h2 : ∀ a b : G, a ∈ A ∧ b ∈ A → (a,b) ∉ G.E, from by {
assume (a b : G) (hab : a ∈ A ∧ b ∈ A),
have h3 : f a = 0 ∧ f b = 0, from by {split,apply hab.left,apply hab.right},
have h4 : f a = f b, from by {rw h3.left,rw h3.right},
have h5 : f a ≠ f b, from by {apply hcol_spec,exact hab.left,exact hab.right},
show (a,b) ∉ G.E, from by {apply not_of_eq_not_of_eq h4 h5},
},
have h3 : ∀ a b : G, a ∈ B ∧ b ∈ B → (a,b) ∉ G.E, from by {
assume (a b : G) (hab : a ∈ B ∧ b ∈ B),
have h4 : f a = 1 ∧ f b = 1, from by {split,apply hab.left,apply hab.right},
have h5 : f a = f b, from by {rw h4.left,rw h4.right},
have h6 : f a ≠ f b, from by {apply hcol_spec,exact hab.left,exact hab.right},
show (a,b) ∉ G.E, from by {apply not_of_eq_not_of_eq h5 h6},
},
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h4 : ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from by {
assume (a b : G) (hab : a ∈ A ∧ b ∈ B),
have h5 : f a = 0 ∧ f b = 1, from by {split,apply hab.left,apply hab.right},
have h6 : f a ≠ f b, from by {rw h5.left,rw h5.right,apply ne.symm,exact dec_trivial},
show (a,b) ∈ G.E, from by {apply hcol_spec,exact hab.left,exact hab.right,exact h6},
},
show ∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from by {
use A,
use B,
have h5 : ∀ v : G, v ∈ A ∨ v ∈ B, from by {
assume v : G,
have h6 : f v = 0 ∨ f v = 1, from by {apply nat.eq_zero_or_eq_one_of_ne_zero,exact hcol_spec v v (v,v)},
show v ∈ A ∨ v ∈ B, from by {rw h6,left,apply set.mem_def.mp,reflexivity,right,apply set.mem_def.mp,reflexivity},
},
have h6 : ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from h4,
show ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from by {
assume v : G,
split,
apply h5,
apply h6,
},
},
},
-- Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$.
have h2 : (∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E) → (∃ f : G → ℕ, ∀ a b : G, (a,b) ∈ G.E → f a ≠ f b), from by {
assume (hbip : ∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E),
have hbip_def : ∃ A B : set G, ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from hbip,
let A : set G := classical.some hbip_def,
let B : set G := classical.some (classical.some_spec hbip_def).right.left,
have hbip_spec : ∀ v : G, v ∈ A ∨ v ∈ B ∧ ∀ a b : G, a ∈ A ∧ b ∈ B → (a,b) ∈ G.E, from classical.some_spec hbip_def,
-- Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
have h3 : ∀ a b : G, (a,b) ∈ G.E → a ∈ A ∧ b ∈ B, from by {
assume (a b : G) (hab : (a,b) ∈ G.E),
have h4 : a ∈ A ∨ a ∈ B, from by {apply hbip_spec.left},
have h5 : b ∈ A ∨ b ∈ B, from
end --Needs more than 2000 tokens!
--OUTPUT 5
theorem bipartite_iff_two_colorable (G : Type*) [graph G] : (∃ A B : set G, bipartite G A B) ↔ two_colorable G :=
begin
split,
{ assume h1 : ∃ A B : set G, bipartite G A B,
rcases h1 with ⟨A, B, h2⟩,
use A, use B,
exact h2, },
{ assume h1 : two_colorable G,
rcases h1 with ⟨A, B, h2⟩,
use A, use B,
exact h2, },
end
--OUTPUT 6
theorem bipartite_graph_two_colorable {G : Type*} [graph G] : two_colorable G ↔ bipartite G :=
begin
-- Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color.
assume h1 : two_colorable G,
-- Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue.
have h2 : ∃ A B : set G.vertex, (∀ v : G.vertex, v ∈ A ∨ v ∈ B) ∧ (∀ v : G.vertex, v ∈ A → ¬ v ∈ B) ∧ (∀ v : G.vertex, v ∈ B → ¬ v ∈ A), from
exists_two_colorable_partition h1,
-- Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$.
have h3 : ∀ v : G.vertex, v ∈ A → ∀ u : G.vertex, u ∈ A → ¬ (v, u) ∈ G.edge, from
assume v : G.vertex,
assume hv : v ∈ A,
assume u : G.vertex,
assume hu : u ∈ A,
assume h4 : (v, u) ∈ G.edge,
have h5 : v ∈ B, from (h2.right v hv),
have h6 : u ∈ B, from (h2.right u hu),
have h7 : (v, u) ∈ G.edge, from h4,
have h8 : (u, v) ∈ G.edge, from (graph.edge_symm G) h7,
have h9 : u ∈ A, from (h2.right u h6),
have h10 : v ∈ A, from (h2.right v h5),
have h11 : (u, v) ∈ G.edge, from h8,
show false, from (graph.edge_irrefl G) h9 h11,
have h4 : ∀ v : G.vertex, v ∈ B → ∀ u : G.vertex, u ∈ B → ¬ (v, u) ∈ G.edge, from
assume v : G.vertex,
assume hv : v ∈ B,
assume u : G.vertex,
assume hu : u ∈ B,
assume h5 : (v, u) ∈ G.edge,
have h6 : v ∈ A, from (h2.right v hv),
have h7 : u ∈ A, from (h2.right u hu),
have h8 : (v, u) ∈ G.edge, from h5,
have h9 : (u, v) ∈ G.edge, from (graph.edge_symm G) h8,
have h10 : u ∈ B, from (h2.right u h7),
have h11 : v ∈ B, from (h2.right v h6),
have h12 : (u, v) ∈ G.edge, from h9,
show false, from (graph.edge_irrefl G) h10 h12,
-- This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
have h5 : ∀ v u : G.vertex, (v, u) ∈ G.edge → (v ∈ A ∧ u ∈ B) ∨ (v ∈ B ∧ u ∈ A), from
assume v u : G.vertex,
assume h6 : (v, u) ∈ G.edge,
have h7 : (v ∈ A ∨ v ∈ B), from (h2.left v),
have h8 : (u ∈ A ∨ u ∈ B), from (h2.left u),
have h9 : (v ∈ A ∧ u ∈ B) ∨ (v ∈ B ∧ u ∈ A), from or.elim (or.elim h7 (assume h10 : v ∈ A, or.inl ⟨h10, (h2.right v h10)⟩) (assume h10 : v ∈ B, or.inr ⟨(h2.right v h10), h10⟩)) (assume h10 : v ∈ A ∧ u ∈ B, or.inl h10) (assume h10 : v ∈ B ∧ u ∈ A, or.inr h10),
show (v ∈ A ∧ u ∈ B) ∨ (v ∈ B ∧ u ∈ A), from h9,
show two_colorable G ↔ bipartite G, from ⟨by obviously, by obviously⟩,
end
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
-- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
-- Then $A ⊆ S$ and $B ⊆ S$, by power set definition
have h1 : (A ⊆ S) ∧ (B ⊆ S), from by {split,apply set.subset_of_mem_powerset,exact hA,apply set.subset_of_mem_powerset,exact hB},
-- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset
have h2 : (A ∩ B) ⊆ A, from by apply set.inter_subset_left,
-- Then $(A ∩ B) ⊆ S$, by subset relation is transitive
have h3 : (A ∩ B) ⊆ S, from by {apply set.subset.trans h2 h1.left},
-- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition
show (A ∩ B) ∈ 𝒫 S, from by {apply set.mem_powerset h3},
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
-- expand the power
calc (x + y)^2 = (x+y)*(x+y) : by rw sq
-- distributive property of multiplication over addition gives:
... = x*(x+y) + y*(x+y) : by rw add_mul
-- applying the above property further gives:
... = x*x + x*y + y*x + y*y : by {rw [mul_comm x (x+y),mul_comm y (x+y)], rw [add_mul,add_mul], ring}
-- rearranging the terms using commutativity and adding gives:
... = x^2 + 2*x*y + y^2 : by {repeat {rw ← sq}, rw mul_comm y x, ring}
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
-- Group has Latin Square Property
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by {
assume a b : G, use a⁻¹ * b, obviously, },
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by {
assume a b : G, use b * a⁻¹, obviously, },
-- Setting $b = a$, this becomes:
have h3 : ∀ a : G, ∃! x : G, a * x = a, from
assume a : G, h1 a a,
have h4 : ∀ a : G, ∃! y : G, y * a = a, from
assume a : G, h2 a a,
-- These $x$ and $y$ are both $(1 : G)$, by definition of identity element
have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from assume a :G,
exists_unique.unique (h3 a) (classical.some_spec (exists_unique.exists (h3 a)))
(mul_one a),
have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from assume a : G,
exists_unique.unique (h4 a) (classical.some_spec (exists_unique.exists (h4 a))) (one_mul a),
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by {
use (1 : G),
have h7 : ∀ e : G, (∀ a : G, e * a = a ∧ a * e = a) → e = 1, from by {
assume (e : G) (hident : ∀ a : G, e * a = a ∧ a * e = a),
have h8 : ∀ a : G, e = classical.some (h3 a).exists, from assume (a : G),
exists_unique.unique (h3 a) (hident a).right
(classical.some_spec (exists_unique.exists (h3 a))),
have h9 : ∀ a : G, e = classical.some (h4 a).exists, from assume (a : G),
exists_unique.unique (h4 a) (hident a).left
(classical.some_spec (exists_unique.exists (h4 a))),
show e = (1 : G), from eq.trans (h9 e) (h6 _),
},
exact ⟨by obviously, h7⟩,
}
end
/--`theorem`
Bipartite Graph is two colorable
Let $G$ be a graph. Then $G$ is 2-colorable if and only if $G$ is bipartite.
`proof`
Let $G$ be a 2-colorable graph, which means we can color every vertex either red or blue, and no edge will have both endpoints colored the same color. Let $A$ denote the subset of vertices colored red, and let $B$ denote the subset of vertices colored blue. Since all vertices of $A$ are red, there are no edges within $A$, and similarly for $B$. This implies that every edge has one endpoint in $A$ and the other in $B$, which means $G$ is bipartite.
Conversely, suppose $G$ is bipartite, that is, we can partition the vertices into two subsets $V_{1}, V_{2}$ every edge has one endpoint in $V_{1}$ and the other in $V_{2}$. Then coloring every vertex of $V_{1}$ red and every vertex of $V_{2}$ blue yields a valid coloring, so $G$ is 2-colorable.
QED
-/
theorem
FEW SHOT PROMPTS TO CODEX(END)-/
|
lemma maze (P Q R S T U: Prop)
(p : P)
(h : P → Q)
(i : Q → R)
(j : Q → T)
(k : S → T)
(l : T → U)
: U :=
begin
exact l(j(h(p))),
end
|
(*
Authors: Asta Halkjær From, Agnes Moesgård Eschen & Jørgen Villadsen, DTU Compute
*)
theory System_R1 imports System_L1 begin
text \<open>System R from Alfred Whitehead, Bertrand Russell: Principia Mathematica
(Second Ed. 1925-1927)\<close>
text \<open>Derivations are taken from: On Axiom Systems of Propositional Calculi. V
by Kiyoshi Iseki and Shotaro Tanaka (1965)\<close>
inductive R (\<open>\<RR>\<close>) where
R_MP: \<open>\<RR> q\<close> if \<open>\<RR> p\<close> and \<open>\<RR> (p \<rightarrow> q)\<close> |
R_1: \<open>\<RR> (p \<rightarrow> (q \<rightarrow> p))\<close> |
R_2: \<open>\<RR> ((p \<rightarrow> q) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close> |
R_3: \<open>\<RR> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> r)))\<close> |
R_4: \<open>\<RR> ((\<sim> (\<sim> p)) \<rightarrow> p)\<close> |
R_5: \<open>\<RR> ((p \<rightarrow> (\<sim> p)) \<rightarrow> (\<sim> p))\<close> |
R_6: \<open>\<RR> ((p \<rightarrow> (\<sim> q)) \<rightarrow> (q \<rightarrow> (\<sim> p)))\<close>
lemma R_7: \<open>\<RR> (q \<rightarrow> (p \<rightarrow> p))\<close>
using R_1 R_3 R_MP by metis
lemma R_8: \<open>\<RR> (p \<rightarrow> p)\<close>
using R_1 R_7 R_MP by metis
lemma R_9: \<open>\<RR> (p \<rightarrow> (\<sim> (\<sim> p)))\<close>
using R_6 R_8 R_MP by metis
lemma R_10: \<open>\<RR> ((q \<rightarrow> r) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> (p \<rightarrow> r)))\<close>
using R_2 R_3 R_MP by metis
lemma R_11: \<open>\<RR> ((q \<rightarrow> (\<sim> (\<sim> p))) \<rightarrow> (q \<rightarrow> p))\<close>
using R_4 R_10 R_MP by metis
lemma R_12: \<open>\<RR> (((\<sim> p) \<rightarrow> (\<sim> q)) \<rightarrow> (q \<rightarrow> p))\<close>
using R_2 R_6 R_11 R_MP by metis
lemma R_13: \<open>\<RR> ((\<sim> p) \<rightarrow> (p \<rightarrow> q))\<close>
using R_1 R_2 R_12 R_MP by metis
lemma R_14: \<open>\<RR> (p \<rightarrow> ((\<sim> p) \<rightarrow> q))\<close>
using R_3 R_13 R_MP by metis
lemma R_15: \<open>\<RR> ((p \<rightarrow> (\<sim> (\<sim> q))) \<rightarrow> (p \<rightarrow> q))\<close>
using R_4 R_10 R_MP by metis (* under substitution this lemma is the same as R_11 *)
lemma R_16: \<open>\<RR> (((\<sim> p) \<rightarrow> q) \<rightarrow> ((\<sim> p) \<rightarrow> (\<sim> (\<sim> q))))\<close>
using R_9 R_10 R_MP by metis
lemma R_17: \<open>\<RR> (((\<sim> p) \<rightarrow> q) \<rightarrow> ((\<sim> q) \<rightarrow> p))\<close>
using R_2 R_12 R_16 R_MP by metis
lemma R_18: \<open>\<RR> ((p \<rightarrow> q) \<rightarrow> ((\<sim> (\<sim> p)) \<rightarrow> q))\<close>
using R_2 R_4 R_MP by metis
lemma R_19: \<open>\<RR> ((((\<sim> (\<sim> p)) \<rightarrow> q) \<rightarrow> r) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> r))\<close>
using R_2 R_18 R_MP by metis
lemma R_20: \<open>\<RR> ((((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)) \<rightarrow> s) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> s))\<close>
using R_2 R_MP by metis
lemma R_21: \<open>\<RR> ((p \<rightarrow> q) \<rightarrow> (((p \<rightarrow> r) \<rightarrow> s) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> s)))\<close>
using R_2 R_20 R_MP by metis
lemma R_22: \<open>\<RR> (((p \<rightarrow> r) \<rightarrow> s) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> s)))\<close>
using R_3 R_21 R_MP by metis
lemma R_23: \<open>\<RR> ((((\<sim> q) \<rightarrow> (\<sim> p)) \<rightarrow> r) \<rightarrow> ((p \<rightarrow> q) \<rightarrow> r))\<close>
using R_17 R_19 R_22 R_MP by metis
lemma R_24: \<open>\<RR> (((\<sim> p) \<rightarrow> p) \<rightarrow> (\<sim> (\<sim> p)))\<close>
using R_5 R_23 R_MP by metis
lemma R_25: \<open>\<RR> (((\<sim> p) \<rightarrow> p) \<rightarrow> p)\<close>
using R_15 R_24 R_MP by metis
theorem R_iff_L1: \<open>\<RR> p \<longleftrightarrow> \<turnstile> p\<close>
proof
have L1_R_1: \<open>\<turnstile> (p \<rightarrow> (q \<rightarrow> p))\<close> for p q
using L1_completeness by simp
have L1_R_2: \<open>\<turnstile> ((p \<rightarrow> q) \<rightarrow> ((q \<rightarrow> r) \<rightarrow> (p \<rightarrow> r)))\<close> for p q r
using L1_completeness by simp
have L1_R_3: \<open>\<turnstile> ((p \<rightarrow> (q \<rightarrow> r)) \<rightarrow> (q \<rightarrow> (p \<rightarrow> r)))\<close> for p q r
using L1_completeness by simp
have L1_R_4: \<open>\<turnstile> ((\<sim> (\<sim> p)) \<rightarrow> p)\<close> for p
using L1_completeness by simp
have L1_R_5: \<open>\<turnstile> ((p \<rightarrow> (\<sim> p)) \<rightarrow> (\<sim> p))\<close> for p
using L1_completeness by simp
have L1_R_6: \<open>\<turnstile> ((p \<rightarrow> (\<sim> q)) \<rightarrow> (q \<rightarrow> (\<sim> p)))\<close> for p q
using L1_completeness by simp
show \<open>\<turnstile> p\<close> if \<open>\<RR> p\<close>
using that by (induct) (metis MP, metis L1_R_1, metis L1_R_2, metis L1_R_3,
metis L1_R_4, metis L1_R_5, metis L1_R_6)
show \<open>\<RR> p\<close> if \<open>\<turnstile> p\<close>
using that by (induct) (metis R_MP, metis R_2, metis R_25, metis R_14)
qed
theorem R_soundness: \<open>\<RR> p \<Longrightarrow> I \<Turnstile> p\<close>
by (induct rule: R.induct) auto
theorem R_completeness: \<open>\<forall>I. (I \<Turnstile> p) \<Longrightarrow> \<RR> p\<close>
using R_iff_L1 by (simp add: L1_completeness)
section \<open>Soundness and Completeness\<close>
theorem main: \<open>valid p = \<RR> p\<close>
unfolding valid_def using R_soundness R_completeness by blast
lemmas R1 = R.intros main
end
|
% gravity_demo.m
% Copyright 2003-2010 The MathWorks, Inc.
clear, close all, clc
get_video_data, disp('press any key to select region'), pause
select_region, disp('press any key to remove background'), pause
remove_background, disp('press any key to segment balls'), pause
segment_by_threshold, disp('press any key to suppress noise'), pause
suppress_noise, disp('press any key to locate ball positions'), pause
locate_ball_positions, disp('press any key to fit circle'), pause
fit_circle, disp('press any key to transform XY points to polar'), pause
%transform_to_polar, disp('press any key to fit damped sinusoid'), pause
%fit_damped_sinusoid, disp('press any key to calibrate pixel size'), pause
transform_to_polar, disp('press any key to model system'), pause
edit model_system
model_system, disp('press any key to calibrate pixel size'), pause
calibrate_resolution, disp('press any key to calculate gravity'), pause
edit calculate_gravity
calculate_gravity |
informal statement Prove that in the ring $\mathbb{Z}[x],(2) \cap(x)=(2 x)$.formal statement theorem exercise_10_4_6 {R : Type*} [comm_ring R]
[no_zero_divisors R] {I J : ideal R} (x : I ⊓ J) :
is_nilpotent ((ideal.quotient.mk (I*J)) x) := |
Installation, Shipping & Collection Services.
© 2019 Art Collective LLC. All rights reserved. |
[STATEMENT]
theorem pick_inverse [intro]: "\<lfloor>pick A\<rfloor> = A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
proof (cases A)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a. A = \<lfloor>a\<rfloor> \<Longrightarrow> \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
fix a
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a. A = \<lfloor>a\<rfloor> \<Longrightarrow> \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
assume a: "A = \<lfloor>a\<rfloor>"
[PROOF STATE]
proof (state)
this:
A = \<lfloor>a\<rfloor>
goal (1 subgoal):
1. \<And>a. A = \<lfloor>a\<rfloor> \<Longrightarrow> \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
A = \<lfloor>a\<rfloor>
[PROOF STEP]
have "pick A \<sim> a"
[PROOF STATE]
proof (prove)
using this:
A = \<lfloor>a\<rfloor>
goal (1 subgoal):
1. pick A \<sim> a
[PROOF STEP]
by (simp only: pick_equiv)
[PROOF STATE]
proof (state)
this:
pick A \<sim> a
goal (1 subgoal):
1. \<And>a. A = \<lfloor>a\<rfloor> \<Longrightarrow> \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
pick A \<sim> a
[PROOF STEP]
have "\<lfloor>pick A\<rfloor> = \<lfloor>a\<rfloor>"
[PROOF STATE]
proof (prove)
using this:
pick A \<sim> a
goal (1 subgoal):
1. \<lfloor>pick A\<rfloor> = \<lfloor>a\<rfloor>
[PROOF STEP]
..
[PROOF STATE]
proof (state)
this:
\<lfloor>pick A\<rfloor> = \<lfloor>a\<rfloor>
goal (1 subgoal):
1. \<And>a. A = \<lfloor>a\<rfloor> \<Longrightarrow> \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
with a
[PROOF STATE]
proof (chain)
picking this:
A = \<lfloor>a\<rfloor>
\<lfloor>pick A\<rfloor> = \<lfloor>a\<rfloor>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
A = \<lfloor>a\<rfloor>
\<lfloor>pick A\<rfloor> = \<lfloor>a\<rfloor>
goal (1 subgoal):
1. \<lfloor>pick A\<rfloor> = A
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lfloor>pick A\<rfloor> = A
goal:
No subgoals!
[PROOF STEP]
qed |
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h : μ ≤ ν
⊢ μ ≤ 0 + ν
[PROOFSTEP]
rwa [zero_add]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
⊢ ↑↑(μ - ν) s = ↑↑μ s - ↑↑ν s
[PROOFSTEP]
let measure_sub : Measure α :=
MeasureTheory.Measure.ofMeasurable (fun (t : Set α) (_ : MeasurableSet t) => μ t - ν t) (by simp)
(by
intro g h_meas h_disj; simp only; rw [ENNReal.tsum_sub]
repeat' rw [← MeasureTheory.measure_iUnion h_disj h_meas]
exacts [MeasureTheory.measure_ne_top _ _, fun i => h₂ _ (h_meas _)])
-- Now, we demonstrate `μ - ν = measure_sub`, and apply it.
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
⊢ (fun t x => ↑↑μ t - ↑↑ν t) ∅ (_ : MeasurableSet ∅) = 0
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
⊢ ∀ ⦃f : ℕ → Set α⦄ (h : ∀ (i : ℕ), MeasurableSet (f i)),
Pairwise (Disjoint on f) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), f i) (_ : MeasurableSet (⋃ (b : ℕ), f b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (f i) (_ : MeasurableSet (f i))
[PROOFSTEP]
intro g h_meas h_disj
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ (fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i))
[PROOFSTEP]
simp only
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑μ (⋃ (i : ℕ), g i) - ↑↑ν (⋃ (i : ℕ), g i) = ∑' (i : ℕ), (↑↑μ (g i) - ↑↑ν (g i))
[PROOFSTEP]
rw [ENNReal.tsum_sub]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑μ (⋃ (i : ℕ), g i) - ↑↑ν (⋃ (i : ℕ), g i) = ∑' (i : ℕ), ↑↑μ (g i) - ∑' (i : ℕ), ↑↑ν (g i)
case h₁
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ∑' (i : ℕ), ↑↑ν (g i) ≠ ⊤
case h₂
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ (fun i => ↑↑ν (g i)) ≤ fun i => ↑↑μ (g i)
[PROOFSTEP]
repeat' rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑μ (⋃ (i : ℕ), g i) - ↑↑ν (⋃ (i : ℕ), g i) = ∑' (i : ℕ), ↑↑μ (g i) - ∑' (i : ℕ), ↑↑ν (g i)
[PROOFSTEP]
rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑μ (⋃ (i : ℕ), g i) - ↑↑ν (⋃ (i : ℕ), g i) = ↑↑μ (⋃ (i : ℕ), g i) - ∑' (i : ℕ), ↑↑ν (g i)
[PROOFSTEP]
rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
case h₁
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ∑' (i : ℕ), ↑↑ν (g i) ≠ ⊤
[PROOFSTEP]
rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
case h₁
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑ν (⋃ (i : ℕ), g i) ≠ ⊤
[PROOFSTEP]
rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
case h₂
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ (fun i => ↑↑ν (g i)) ≤ fun i => ↑↑μ (g i)
[PROOFSTEP]
rw [← MeasureTheory.measure_iUnion h_disj h_meas]
[GOAL]
case h₁
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ ↑↑ν (⋃ (i : ℕ), g i) ≠ ⊤
case h₂
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
g : ℕ → Set α
h_meas : ∀ (i : ℕ), MeasurableSet (g i)
h_disj : Pairwise (Disjoint on g)
⊢ (fun i => ↑↑ν (g i)) ≤ fun i => ↑↑μ (g i)
[PROOFSTEP]
exacts [MeasureTheory.measure_ne_top _ _, fun i => h₂ _ (h_meas _)]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
⊢ ↑↑(μ - ν) s = ↑↑μ s - ↑↑ν s
[PROOFSTEP]
have h_measure_sub_add : ν + measure_sub = μ :=
by
ext1 t h_t_measurable_set
simp only [Pi.add_apply, coe_add]
rw [MeasureTheory.Measure.ofMeasurable_apply _ h_t_measurable_set, add_comm,
tsub_add_cancel_of_le (h₂ t h_t_measurable_set)]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
⊢ ν + measure_sub = μ
[PROOFSTEP]
ext1 t h_t_measurable_set
[GOAL]
case h
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
t : Set α
h_t_measurable_set : MeasurableSet t
⊢ ↑↑(ν + measure_sub) t = ↑↑μ t
[PROOFSTEP]
simp only [Pi.add_apply, coe_add]
[GOAL]
case h
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
t : Set α
h_t_measurable_set : MeasurableSet t
⊢ ↑↑ν t +
↑↑(ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i))))
t =
↑↑μ t
[PROOFSTEP]
rw [MeasureTheory.Measure.ofMeasurable_apply _ h_t_measurable_set, add_comm,
tsub_add_cancel_of_le (h₂ t h_t_measurable_set)]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ ↑↑(μ - ν) s = ↑↑μ s - ↑↑ν s
[PROOFSTEP]
have h_measure_sub_eq : μ - ν = measure_sub :=
by
rw [MeasureTheory.Measure.sub_def]
apply le_antisymm
· apply sInf_le
simp [le_refl, add_comm, h_measure_sub_add]
apply le_sInf
intro d h_d
rw [← h_measure_sub_add, mem_setOf_eq, add_comm d] at h_d
apply Measure.le_of_add_le_add_left h_d
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ μ - ν = measure_sub
[PROOFSTEP]
rw [MeasureTheory.Measure.sub_def]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ sInf {d | μ ≤ d + ν} = measure_sub
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ sInf {d | μ ≤ d + ν} ≤ measure_sub
[PROOFSTEP]
apply sInf_le
[GOAL]
case a.a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ measure_sub ∈ {d | μ ≤ d + ν}
[PROOFSTEP]
simp [le_refl, add_comm, h_measure_sub_add]
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ measure_sub ≤ sInf {d | μ ≤ d + ν}
[PROOFSTEP]
apply le_sInf
[GOAL]
case a.a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
⊢ ∀ (b : Measure α), b ∈ {d | μ ≤ d + ν} → measure_sub ≤ b
[PROOFSTEP]
intro d h_d
[GOAL]
case a.a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
d : Measure α
h_d : d ∈ {d | μ ≤ d + ν}
⊢ measure_sub ≤ d
[PROOFSTEP]
rw [← h_measure_sub_add, mem_setOf_eq, add_comm d] at h_d
[GOAL]
case a.a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
d : Measure α
h_d : ν + measure_sub ≤ ν + d
⊢ measure_sub ≤ d
[PROOFSTEP]
apply Measure.le_of_add_le_add_left h_d
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
h_measure_sub_eq : μ - ν = measure_sub
⊢ ↑↑(μ - ν) s = ↑↑μ s - ↑↑ν s
[PROOFSTEP]
rw [h_measure_sub_eq]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : MeasurableSet s
h₂ : ν ≤ μ
measure_sub : Measure α :=
ofMeasurable (fun t x => ↑↑μ t - ↑↑ν t) (_ : ↑↑μ ∅ - ↑↑ν ∅ = 0)
(_ :
∀ ⦃g : ℕ → Set α⦄ (h_meas : ∀ (i : ℕ), MeasurableSet (g i)),
Pairwise (Disjoint on g) →
(fun t x => ↑↑μ t - ↑↑ν t) (⋃ (i : ℕ), g i) (_ : MeasurableSet (⋃ (b : ℕ), g b)) =
∑' (i : ℕ), (fun t x => ↑↑μ t - ↑↑ν t) (g i) (_ : MeasurableSet (g i)))
h_measure_sub_add : ν + measure_sub = μ
h_measure_sub_eq : μ - ν = measure_sub
⊢ ↑↑measure_sub s = ↑↑μ s - ↑↑ν s
[PROOFSTEP]
apply Measure.ofMeasurable_apply _ h₁
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
inst✝ : IsFiniteMeasure ν
h₁ : ν ≤ μ
⊢ μ - ν + ν = μ
[PROOFSTEP]
ext1 s h_s_meas
[GOAL]
case h
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s✝ : Set α
inst✝ : IsFiniteMeasure ν
h₁ : ν ≤ μ
s : Set α
h_s_meas : MeasurableSet s
⊢ ↑↑(μ - ν + ν) s = ↑↑μ s
[PROOFSTEP]
rw [add_apply, sub_apply h_s_meas h₁, tsub_add_cancel_of_le (h₁ s h_s_meas)]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
⊢ restrict (μ - ν) s = restrict μ s - restrict ν s
[PROOFSTEP]
repeat' rw [sub_def]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
⊢ restrict (μ - ν) s = restrict μ s - restrict ν s
[PROOFSTEP]
rw [sub_def]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
⊢ restrict (sInf {d | μ ≤ d + ν}) s = restrict μ s - restrict ν s
[PROOFSTEP]
rw [sub_def]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
⊢ restrict (sInf {d | μ ≤ d + ν}) s = sInf {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
rw [sub_def]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
⊢ restrict (sInf {d | μ ≤ d + ν}) s = sInf {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
have h_nonempty : {d | μ ≤ d + ν}.Nonempty := ⟨μ, Measure.le_add_right le_rfl⟩
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ restrict (sInf {d | μ ≤ d + ν}) s = sInf {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
rw [restrict_sInf_eq_sInf_restrict h_nonempty h_meas_s]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ sInf ((fun μ => restrict μ s) '' {d | μ ≤ d + ν}) = sInf {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ sInf ((fun μ => restrict μ s) '' {d | μ ≤ d + ν}) ≤ sInf {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
refine' sInf_le_sInf_of_forall_exists_le _
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ ∀ (x : Measure α),
x ∈ {d | restrict μ s ≤ d + restrict ν s} → ∃ y, y ∈ (fun μ => restrict μ s) '' {d | μ ≤ d + ν} ∧ y ≤ x
[PROOFSTEP]
intro ν' h_ν'_in
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : ν' ∈ {d | restrict μ s ≤ d + restrict ν s}
⊢ ∃ y, y ∈ (fun μ => restrict μ s) '' {d | μ ≤ d + ν} ∧ y ≤ ν'
[PROOFSTEP]
rw [mem_setOf_eq] at h_ν'_in
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
⊢ ∃ y, y ∈ (fun μ => restrict μ s) '' {d | μ ≤ d + ν} ∧ y ≤ ν'
[PROOFSTEP]
refine' ⟨ν'.restrict s, _, restrict_le_self⟩
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
⊢ restrict ν' s ∈ (fun μ => restrict μ s) '' {d | μ ≤ d + ν}
[PROOFSTEP]
refine' ⟨ν' + (⊤ : Measure α).restrict sᶜ, _, _⟩
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
⊢ ν' + restrict ⊤ sᶜ ∈ {d | μ ≤ d + ν}
[PROOFSTEP]
rw [mem_setOf_eq, add_right_comm, Measure.le_iff]
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
⊢ ∀ (s_1 : Set α), MeasurableSet s_1 → ↑↑μ s_1 ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) s_1
[PROOFSTEP]
intro t h_meas_t
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ t ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) t
[PROOFSTEP]
repeat' rw [← measure_inter_add_diff t h_meas_s]
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ t ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) t
[PROOFSTEP]
rw [← measure_inter_add_diff t h_meas_s]
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) + ↑↑μ (t \ s) ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) t
[PROOFSTEP]
rw [← measure_inter_add_diff t h_meas_s]
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) + ↑↑μ (t \ s) ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) (t ∩ s) + ↑↑(ν' + ν + restrict ⊤ sᶜ) (t \ s)
[PROOFSTEP]
rw [← measure_inter_add_diff t h_meas_s]
[GOAL]
case a.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) + ↑↑μ (t \ s) ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) (t ∩ s) + ↑↑(ν' + ν + restrict ⊤ sᶜ) (t \ s)
[PROOFSTEP]
refine' add_le_add _ _
[GOAL]
case a.refine'_1.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) (t ∩ s)
[PROOFSTEP]
rw [add_apply, add_apply]
[GOAL]
case a.refine'_1.refine'_1
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) ≤ ↑↑ν' (t ∩ s) + ↑↑ν (t ∩ s) + ↑↑(restrict ⊤ sᶜ) (t ∩ s)
[PROOFSTEP]
apply le_add_right _
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ s) ≤ ↑↑ν' (t ∩ s) + ↑↑ν (t ∩ s)
[PROOFSTEP]
rw [← restrict_eq_self μ (inter_subset_right _ _), ← restrict_eq_self ν (inter_subset_right _ _)]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑(restrict μ s) (t ∩ s) ≤ ↑↑ν' (t ∩ s) + ↑↑(restrict ν s) (t ∩ s)
[PROOFSTEP]
apply h_ν'_in _ (h_meas_t.inter h_meas_s)
[GOAL]
case a.refine'_1.refine'_2
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t \ s) ≤ ↑↑(ν' + ν + restrict ⊤ sᶜ) (t \ s)
[PROOFSTEP]
rw [add_apply, restrict_apply (h_meas_t.diff h_meas_s), diff_eq, inter_assoc, inter_self, ← add_apply]
[GOAL]
case a.refine'_1.refine'_2
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑μ (t ∩ sᶜ) ≤ ↑↑(ν' + ν + ⊤) (t ∩ sᶜ)
[PROOFSTEP]
have h_mu_le_add_top : μ ≤ ν' + ν + ⊤ := by simp only [add_top, le_top]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ μ ≤ ν' + ν + ⊤
[PROOFSTEP]
simp only [add_top, le_top]
[GOAL]
case a.refine'_1.refine'_2
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
h_mu_le_add_top : μ ≤ ν' + ν + ⊤
⊢ ↑↑μ (t ∩ sᶜ) ≤ ↑↑(ν' + ν + ⊤) (t ∩ sᶜ)
[PROOFSTEP]
exact Measure.le_iff'.1 h_mu_le_add_top _
[GOAL]
case a.refine'_2
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
⊢ (fun μ => restrict μ s) (ν' + restrict ⊤ sᶜ) = restrict ν' s
[PROOFSTEP]
ext1 t h_meas_t
[GOAL]
case a.refine'_2.h
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
ν' : Measure α
h_ν'_in : restrict μ s ≤ ν' + restrict ν s
t : Set α
h_meas_t : MeasurableSet t
⊢ ↑↑((fun μ => restrict μ s) (ν' + restrict ⊤ sᶜ)) t = ↑↑(restrict ν' s) t
[PROOFSTEP]
simp [restrict_apply h_meas_t, restrict_apply (h_meas_t.inter h_meas_s), inter_assoc]
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ sInf {d | restrict μ s ≤ d + restrict ν s} ≤ sInf ((fun μ => restrict μ s) '' {d | μ ≤ d + ν})
[PROOFSTEP]
refine' sInf_le_sInf_of_forall_exists_le _
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
⊢ ∀ (x : Measure α),
x ∈ (fun μ => restrict μ s) '' {d | μ ≤ d + ν} → ∃ y, y ∈ {d | restrict μ s ≤ d + restrict ν s} ∧ y ≤ x
[PROOFSTEP]
refine' ball_image_iff.2 fun t h_t_in => ⟨t.restrict s, _, le_rfl⟩
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
t : Measure α
h_t_in : t ∈ {d | μ ≤ d + ν}
⊢ restrict t s ∈ {d | restrict μ s ≤ d + restrict ν s}
[PROOFSTEP]
rw [Set.mem_setOf_eq, ← restrict_add]
[GOAL]
case a
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_meas_s : MeasurableSet s
h_nonempty : Set.Nonempty {d | μ ≤ d + ν}
t : Measure α
h_t_in : t ∈ {d | μ ≤ d + ν}
⊢ restrict μ s ≤ restrict (t + ν) s
[PROOFSTEP]
exact restrict_mono Subset.rfl h_t_in
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_le : restrict μ s ≤ restrict ν s
h_meas_s : MeasurableSet s
⊢ ↑↑(μ - ν) s = 0
[PROOFSTEP]
rw [← restrict_apply_self, restrict_sub_eq_restrict_sub_restrict, sub_eq_zero_of_le]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_le : restrict μ s ≤ restrict ν s
h_meas_s : MeasurableSet s
⊢ ↑↑0 s = 0
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_le : restrict μ s ≤ restrict ν s
h_meas_s : MeasurableSet s
⊢ restrict μ s ≤ restrict ν s
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u_1
m : MeasurableSpace α
μ ν : Measure α
s : Set α
h_le : restrict μ s ≤ restrict ν s
h_meas_s : MeasurableSet s
⊢ MeasurableSet s
[PROOFSTEP]
simp [*]
|
open import Agda.Builtin.Char
open import Agda.Builtin.Coinduction
open import Agda.Builtin.IO
open import Agda.Builtin.List
open import Agda.Builtin.Unit
open import Agda.Builtin.String
data Colist {a} (A : Set a) : Set a where
[] : Colist A
_∷_ : A → ∞ (Colist A) → Colist A
{-# FOREIGN GHC
data Colist a = Nil | Cons a (MAlonzo.RTE.Inf (Colist a))
type Colist' l a = Colist a
fromColist :: Colist a -> [a]
fromColist Nil = []
fromColist (Cons x xs) = x : fromColist (MAlonzo.RTE.flat xs)
#-}
{-# COMPILE GHC Colist = data Colist' (Nil | Cons) #-}
to-colist : ∀ {a} {A : Set a} → List A → Colist A
to-colist [] = []
to-colist (x ∷ xs) = x ∷ ♯ to-colist xs
a-definition-that-uses-♭ :
∀ {a} {A : Set a} → Colist A → Colist A
a-definition-that-uses-♭ [] = []
a-definition-that-uses-♭ (x ∷ xs) =
x ∷ ♯ a-definition-that-uses-♭ (♭ xs)
postulate
putStr : Colist Char → IO ⊤
{-# COMPILE GHC putStr = putStr . fromColist #-}
main : IO ⊤
main = putStr (a-definition-that-uses-♭
(to-colist (primStringToList "apa\n")))
|
# GetNoAuditCalibrationCopies1Data.r
# G E T D A T A
source("../common/DataUtil.r")
if (!exists('dir.string') || (is.null(dir.string))) {dir.string <- "./"}
filesList <- grep(pattern="^Giant.*\\.txt$", dir(dir.string),
perl=TRUE, value = TRUE)
dat.noaudit <- read.table(filesList[1],
header=TRUE,sep=" ", na.strings="nolinefound")
mdmlosspct <- dat.noaudit$EmpiricalLosses / 100.0
newdat <- cbind(dat.noaudit,mdmlosspct)
dat.noaudit <- newdat
# P L O T D A T A
library(ggplot2)
source("../common/PlotUtil.r")
trows <- dat.noaudit
gp <- ggplot(data=trows,aes(x=lifem,y=safe(mdmlosspct)))
nCopies <- 1
trows <- fnSelectCopies(dat.noaudit, nCopies)
gp <- gp +
aes(trows, x=(lifem), y=(safe(mdmlosspct))) +
geom_point(data=trows,
color="red", size=3, shape=(point.DOT)) +
geom_line(data=trows,
linetype="dashed", color="black", size=1)
gp <- fnPlotLogScales(gp, x="YES", y="YES"
, xbreaks=c(2,5,10,50,100,1000,10000)
, ybreaks=c(0.1,1,10,100)
)
gp <- fnPlotTitles(gp
,titleline="With a single copy, losses are unacceptable, "
%+% "even with high quality disks"
%+% "\n(document losses over 10 years)"
,titlesize=16
,xlabel="1MB sector half-life (megahours)"
%+% " (lower error rate \u2192)"
,ylabel="permanent document losses (% of collection)"
,labelsize=14
)
gp <- fnPlotPercentLine(gp)
gp <- fnPlotMilleLine(gp)
#gp <- fnPlotSubMilleLine(gp)
# A N N O T A T I O N S
labelsize <- 10
gp <- gp + geom_text(x=log10(150.0), y=log10(0.04)
,label="Increasing quality of storage \u2192 \u2192 \u2192"
,size=labelsize, color="red"
,fontface="plain", family="sans")
gp <- gp + geom_text(x=log10(10000.0), y=log10(1.2)
,label="Decreasing\ndocument\nlosses "
%+% "\n\u2193\n\u2193\n\u2193"
,size=labelsize, color="red"
,fontface="plain", family="sans"
,hjust=1)
plot(gp)
fnPlotMakeFile(gp, "baseline-noaudit.png")
# Unwind any remaining sink()s to close output files.
while (sink.number() > 0) {sink()}
|
{-# OPTIONS --without-K #-}
-- Two equivalent approached to define the advantage in
-- a (bit) guessing game
open import Data.Two
open import Data.Nat.NP hiding (_==_)
open import Data.Nat.Distance
open import Data.Product.NP
open import Function
open import Explore.Core
open import Explore.Properties
open import Explore.Summable
open import Explore.Sum
open import Explore.Product
open import Explore.Two
open import Relation.Binary.PropositionalEquality.NP
module Explore.GuessingGameFlipping
(R : Set)(sum : Sum R)(sum-ind : SumInd sum)(⅁ : 𝟚 → R → 𝟚) where
open Operators
X Y : R → 𝟚
X = ⅁ 0₂
Y = ⅁ 1₂
R' = 𝟚 × R
sum' : Sum R'
sum' = 𝟚ˢ ×ˢ sum
open FromSum sum' renaming (count to #'_)
open FromSumInd sum-ind renaming (count to #_)
G : R' → 𝟚
G (b , r) = b == ⅁ b r
1/2 : R' → 𝟚
1/2 = fst
-- TODO use the library
lemma : ∀ X → sum (const 1) ≡ #(not ∘ X) + # X
lemma X = sum-ind P refl (λ {a}{b} → part1 {a}{b}) part2
where
count = FromSum.count
P = λ s → s (const 1) ≡ count s (not ∘ X) + count s X
part1 : ∀ {s₀ s₁} → P s₀ → P s₁ → P (λ f → s₀ f + s₁ f)
part1 {s₀} {s₁} Ps₀ Ps₁ rewrite Ps₀ | Ps₁ = +-interchange (count s₀ (not ∘ X)) (count s₀ X) (count s₁ (not ∘ X)) (count s₁ X)
part2 : ∀ x → P (λ f → f x)
part2 x with X x
part2 x | 0₂ = refl
part2 x | 1₂ = refl
thm : dist (#' G) (#' 1/2) ≡ dist (# Y) (# X)
thm = dist (#' G) (#' 1/2)
≡⟨ cong (dist (#' G)) helper ⟩
dist (#' G) (#(not ∘ X) + # X)
≡⟨ refl ⟩ -- #' definition
dist (# (_==_ 0₂ ∘ X) + # (_==_ 1₂ ∘ Y)) (# (not ∘ X) + # X)
≡⟨ refl ⟩ -- #' definition
dist (# (not ∘ X) + # Y) (# (not ∘ X) + # X)
≡⟨ dist-x+ (# (not ∘ X)) (# Y) (# X) ⟩
dist (# Y) (# X)
∎
where
open ≡-Reasoning
helper = #' 1/2
≡⟨ refl ⟩
sum (const 0) + sum (const 1)
≡⟨ cong (λ p → p + sum (const 1)) sum-zero ⟩
sum (const 1)
≡⟨ lemma X ⟩
# (not ∘ X) + # X
∎
|
[STATEMENT]
lemma Ext_method_inheritance:
"filter_tab (\<lambda>sig m. tprg \<turnstile> Ext inherits method sig m)
(Map.empty(fst ((\<lambda>(s, m). (s, Base, m)) Base_foo)\<mapsto>
snd ((\<lambda>(s, m). (s, Base, m)) Base_foo)))
= Map.empty"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. filter_tab (\<lambda>sig m. tprg \<turnstile> Ext inherits method sig m) [fst (case Base_foo of (s, m) \<Rightarrow> (s, Base, m)) \<mapsto> snd (case Base_foo of (s, m) \<Rightarrow> (s, Base, m))] = Map.empty
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. filter_tab (\<lambda>sig m. tprg \<turnstile> Ext inherits method sig m) [fst (case Base_foo of (s, m) \<Rightarrow> (s, Base, m)) \<mapsto> snd (case Base_foo of (s, m) \<Rightarrow> (s, Base, m))] = Map.empty
[PROOF STEP]
from Base_foo_not_inherited_in_Ext
[PROOF STATE]
proof (chain)
picking this:
\<not> tprg \<turnstile> Ext inherits (Base, mdecl Base_foo)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> tprg \<turnstile> Ext inherits (Base, mdecl Base_foo)
goal (1 subgoal):
1. filter_tab (\<lambda>sig m. tprg \<turnstile> Ext inherits method sig m) [fst (case Base_foo of (s, m) \<Rightarrow> (s, Base, m)) \<mapsto> snd (case Base_foo of (s, m) \<Rightarrow> (s, Base, m))] = Map.empty
[PROOF STEP]
by (auto intro: filter_tab_all_False simp add: Base_foo_def)
[PROOF STATE]
proof (state)
this:
filter_tab (\<lambda>sig m. tprg \<turnstile> Ext inherits method sig m) [fst (case Base_foo of (s, m) \<Rightarrow> (s, Base, m)) \<mapsto> snd (case Base_foo of (s, m) \<Rightarrow> (s, Base, m))] = Map.empty
goal:
No subgoals!
[PROOF STEP]
qed |
theorem contrapositive (P Q : Prop) :
(P → Q) → (¬ Q → ¬ P) :=
begin
sorry
end
|
(** One can always prove something by overusing absurdity. **)
Axiom absurd_absurd : forall P, ~ ~ ~ P -> P.
Corollary nothing_matters : False.
Proof.
apply absurd_absurd. auto.
Qed.
|
MODULE CDMFT_ED
USE ED_INPUT_VARS
USE ED_AUX_FUNX, only: &
ed_search_variable , &
search_chemical_potential
USE ED_IO, only: &
ed_print_impSigma , &
ed_read_impSigma , &
ed_print_impG , &
ed_read_impG , &
ed_print_impG0 , &
ed_get_sigma_matsubara , &
ed_get_sigma_realaxis , &
ed_get_gimp_matsubara , &
ed_get_gimp_realaxis , &
ed_get_g0imp_matsubara , &
ed_get_g0imp_realaxis , &
ed_get_delta_matsubara , &
ed_get_g0and_matsubara , &
ed_get_delta_realaxis , &
ed_get_g0and_realaxis , &
ed_get_density_matrix , &
ed_get_dens , &
ed_get_custom_observable
USE ED_BATH, only: &
ed_set_Hreplica => set_Hreplica ,&
ed_get_bath_dimension => get_bath_dimension ,&
ed_impose_bath_offset => impose_bath_offset ,&
ed_impose_equal_lambda => impose_equal_lambda
!USE ED_BATH_FUNCTIONS, only: &
USE ED_MAIN, only: &
ed_init_solver , &
ed_solve
USE ED_OBSERVABLES, only: &
init_custom_observables , &
clear_custom_observables , &
add_custom_observable
USE ED_FIT_CHI2, only: ed_chi2_fitgf
END MODULE CDMFT_ED
|
{-# OPTIONS --without-K #-}
open import lib.Basics
open import lib.types.Paths
module lib.types.Torus where
{-
data Torus : Type₀ where
baseT : Torus
loopT1 : baseT == baseT
loopT2 : baseT == baseT
surfT : loopT1 ∙ loopT2 == loopT2 ∙ loopT1
-}
module _ where
private
data #Torus-aux : Type₀ where
#baseT : #Torus-aux
data #Torus : Type₀ where
#torus : #Torus-aux → (Unit → Unit) → #Torus
Torus : Type₀
Torus = #Torus
baseT : Torus
baseT = #torus #baseT _
postulate -- HIT
loopT1 : baseT == baseT
loopT2 : baseT == baseT
surfT : loopT1 ∙ loopT2 == loopT2 ∙ loopT1
{- Dependent elimination and computation rules -}
module TorusElim {i} {P : Torus → Type i} (baseT* : P baseT)
(loopT1* : baseT* == baseT* [ P ↓ loopT1 ])
(loopT2* : baseT* == baseT* [ P ↓ loopT2 ])
(surfT* : loopT1* ∙ᵈ loopT2* == loopT2* ∙ᵈ loopT1*
[ (λ p → baseT* == baseT* [ P ↓ p ]) ↓ surfT ]) where
f : Π Torus P
f = f-aux phantom where
f-aux : Phantom surfT* → Π Torus P
f-aux phantom (#torus #baseT _) = baseT*
postulate -- HIT
loopT1-β : apd f loopT1 == loopT1*
loopT2-β : apd f loopT2 == loopT2*
private
lhs : apd f (loopT1 ∙ loopT2) == loopT1* ∙ᵈ loopT2*
lhs =
apd f (loopT1 ∙ loopT2) =⟨ apd-∙ f loopT1 loopT2 ⟩
apd f loopT1 ∙ᵈ apd f loopT2 =⟨ loopT1-β |in-ctx (λ u → u ∙ᵈ apd f loopT2) ⟩
loopT1* ∙ᵈ apd f loopT2 =⟨ loopT2-β |in-ctx (λ u → loopT1* ∙ᵈ u) ⟩
loopT1* ∙ᵈ loopT2* ∎
rhs : apd f (loopT2 ∙ loopT1) == loopT2* ∙ᵈ loopT1*
rhs =
apd f (loopT2 ∙ loopT1) =⟨ apd-∙ f loopT2 loopT1 ⟩
apd f loopT2 ∙ᵈ apd f loopT1 =⟨ loopT2-β |in-ctx (λ u → u ∙ᵈ apd f loopT1) ⟩
loopT2* ∙ᵈ apd f loopT1 =⟨ loopT1-β |in-ctx (λ u → loopT2* ∙ᵈ u) ⟩
loopT2* ∙ᵈ loopT1* ∎
postulate -- HIT
surfT-β : apd (apd f) surfT == lhs ◃ (surfT* ▹! rhs)
module TorusRec {i} {A : Type i} (baseT* : A) (loopT1* loopT2* : baseT* == baseT*)
(surfT* : loopT1* ∙ loopT2* == loopT2* ∙ loopT1*) where
private
module M = TorusElim {P = λ _ → A} baseT* (↓-cst-in loopT1*) (↓-cst-in loopT2*)
(↓-cst-in-∙ loopT1 loopT2 loopT1* loopT2*
!◃ (↓-cst-in2 surfT* ▹ (↓-cst-in-∙ loopT2 loopT1 loopT2* loopT1*)))
f : Torus → A
f = M.f
loopT1-β : ap f loopT1 == loopT1*
loopT1-β = apd=cst-in {f = f} M.loopT1-β
loopT2-β : ap f loopT2 == loopT2*
loopT2-β = apd=cst-in {f = f} M.loopT2-β
private
lhs : ap f (loopT1 ∙ loopT2) == loopT1* ∙ loopT2*
lhs =
ap f (loopT1 ∙ loopT2) =⟨ ap-∙ f loopT1 loopT2 ⟩
ap f loopT1 ∙ ap f loopT2 =⟨ loopT1-β |in-ctx (λ u → u ∙ ap f loopT2) ⟩
loopT1* ∙ ap f loopT2 =⟨ loopT2-β |in-ctx (λ u → loopT1* ∙ u) ⟩
loopT1* ∙ loopT2* ∎
rhs : ap f (loopT2 ∙ loopT1) == loopT2* ∙ loopT1*
rhs =
ap f (loopT2 ∙ loopT1) =⟨ ap-∙ f loopT2 loopT1 ⟩
ap f loopT2 ∙ ap f loopT1 =⟨ loopT2-β |in-ctx (λ u → u ∙ ap f loopT1) ⟩
loopT2* ∙ ap f loopT1 =⟨ loopT1-β |in-ctx (λ u → loopT2* ∙ u) ⟩
loopT2* ∙ loopT1* ∎
postulate -- Does not look easy
surfT-β : ap (ap f) surfT == (lhs ∙ surfT*) ∙ (! rhs)
-- surfT-β = {!M.surfT-β!}
-- module TorusRecType {i} (baseT* : Type i) (loopT1* loopT2* : baseT* ≃ baseT*)
-- (surfT* : (x : baseT*) → –> loopT2* (–> loopT2* x) == –> loopT1* (–> loopT2* x)) where
-- open TorusRec baseT* (ua loopT1*) (ua loopT2*) {!!} public
-- -- TODO
|
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
! This file was ported from Lean 3 source module analysis.normed_space.add_torsor_bases
! leanprover-community/mathlib commit 2f4cdce0c2f2f3b8cd58f05d556d03b468e1eb2e
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Analysis.NormedSpace.FiniteDimension
import Mathbin.Analysis.Calculus.AffineMap
import Mathbin.Analysis.Convex.Combination
import Mathbin.LinearAlgebra.AffineSpace.FiniteDimensional
/-!
# Bases in normed affine spaces.
This file contains results about bases in normed affine spaces.
## Main definitions:
* `continuous_barycentric_coord`
* `is_open_map_barycentric_coord`
* `affine_basis.interior_convex_hull`
* `exists_subset_affine_independent_span_eq_top_of_open`
* `interior_convex_hull_nonempty_iff_affine_span_eq_top`
-/
section Barycentric
variable {ι 𝕜 E P : Type _} [NontriviallyNormedField 𝕜] [CompleteSpace 𝕜]
variable [NormedAddCommGroup E] [NormedSpace 𝕜 E]
variable [MetricSpace P] [NormedAddTorsor E P]
include E
theorem isOpenMap_barycentric_coord [Nontrivial ι] (b : AffineBasis ι 𝕜 P) (i : ι) :
IsOpenMap (b.Coord i) :=
AffineMap.isOpenMap_linear_iff.mp <|
(b.Coord i).linear.isOpenMap_of_finiteDimensional <|
(b.Coord i).linear_surjective_iff.mpr (b.surjective_coord i)
#align is_open_map_barycentric_coord isOpenMap_barycentric_coord
variable [FiniteDimensional 𝕜 E] (b : AffineBasis ι 𝕜 P)
@[continuity]
theorem continuous_barycentric_coord (i : ι) : Continuous (b.Coord i) :=
(b.Coord i).continuous_of_finiteDimensional
#align continuous_barycentric_coord continuous_barycentric_coord
theorem smooth_barycentric_coord (b : AffineBasis ι 𝕜 E) (i : ι) : ContDiff 𝕜 ⊤ (b.Coord i) :=
(⟨b.Coord i, continuous_barycentric_coord b i⟩ : E →A[𝕜] 𝕜).ContDiff
#align smooth_barycentric_coord smooth_barycentric_coord
end Barycentric
open Set
/-- Given a finite-dimensional normed real vector space, the interior of the convex hull of an
affine basis is the set of points whose barycentric coordinates are strictly positive with respect
to this basis.
TODO Restate this result for affine spaces (instead of vector spaces) once the definition of
convexity is generalised to this setting. -/
theorem AffineBasis.interior_convexHull {ι E : Type _} [Finite ι] [NormedAddCommGroup E]
[NormedSpace ℝ E] (b : AffineBasis ι ℝ E) :
interior (convexHull ℝ (range b)) = { x | ∀ i, 0 < b.Coord i x } :=
by
cases subsingleton_or_nontrivial ι
· -- The zero-dimensional case.
have : range b = univ :=
AffineSubspace.eq_univ_of_subsingleton_span_eq_top (subsingleton_range _) b.tot
simp [this]
· -- The positive-dimensional case.
haveI : FiniteDimensional ℝ E := b.finite_dimensional
have : convexHull ℝ (range b) = ⋂ i, b.coord i ⁻¹' Ici 0 :=
by
rw [b.convex_hull_eq_nonneg_coord, set_of_forall]
rfl
ext
simp only [this, interior_interᵢ, ←
IsOpenMap.preimage_interior_eq_interior_preimage (isOpenMap_barycentric_coord b _)
(continuous_barycentric_coord b _),
interior_Ici, mem_Inter, mem_set_of_eq, mem_Ioi, mem_preimage]
#align affine_basis.interior_convex_hull AffineBasis.interior_convexHull
variable {V P : Type _} [NormedAddCommGroup V] [NormedSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P]
include V
open AffineMap
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (y «expr ∉ » s) -/
/-- Given a set `s` of affine-independent points belonging to an open set `u`, we may extend `s` to
an affine basis, all of whose elements belong to `u`. -/
theorem IsOpen.exists_between_affineIndependent_span_eq_top {s u : Set P} (hu : IsOpen u)
(hsu : s ⊆ u) (hne : s.Nonempty) (h : AffineIndependent ℝ (coe : s → P)) :
∃ t : Set P, s ⊆ t ∧ t ⊆ u ∧ AffineIndependent ℝ (coe : t → P) ∧ affineSpan ℝ t = ⊤ :=
by
obtain ⟨q, hq⟩ := hne
obtain ⟨ε, ε0, hεu⟩ := metric.nhds_basis_closed_ball.mem_iff.1 (hu.mem_nhds <| hsu hq)
obtain ⟨t, ht₁, ht₂, ht₃⟩ := exists_subset_affineIndependent_affineSpan_eq_top h
let f : P → P := fun y => line_map q y (ε / dist y q)
have hf : ∀ y, f y ∈ u := by
refine' fun y => hεu _
simp only [f]
rw [Metric.mem_closedBall, line_map_apply, dist_vadd_left, norm_smul, Real.norm_eq_abs,
dist_eq_norm_vsub V y q, abs_div, abs_of_pos ε0, abs_of_nonneg (norm_nonneg _), div_mul_comm]
exact mul_le_of_le_one_left ε0.le (div_self_le_one _)
have hεyq : ∀ (y) (_ : y ∉ s), ε / dist y q ≠ 0 := fun y hy =>
div_ne_zero ε0.ne' (dist_ne_zero.2 (ne_of_mem_of_not_mem hq hy).symm)
classical
let w : t → ℝˣ := fun p => if hp : (p : P) ∈ s then 1 else Units.mk0 _ (hεyq (↑p) hp)
refine' ⟨Set.range fun p : t => line_map q p (w p : ℝ), _, _, _, _⟩
· intro p hp
use ⟨p, ht₁ hp⟩
simp [w, hp]
· rintro y ⟨⟨p, hp⟩, rfl⟩
by_cases hps : p ∈ s <;>
simp only [w, hps, line_map_apply_one, Units.val_mk0, dif_neg, dif_pos, not_false_iff,
Units.val_one, Subtype.coe_mk] <;>
[exact hsu hps, exact hf p]
· exact (ht₂.units_line_map ⟨q, ht₁ hq⟩ w).range
· rw [affineSpan_eq_affineSpan_lineMap_units (ht₁ hq) w, ht₃]
#align is_open.exists_between_affine_independent_span_eq_top IsOpen.exists_between_affineIndependent_span_eq_top
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (s «expr ⊆ » u) -/
theorem IsOpen.exists_subset_affineIndependent_span_eq_top {u : Set P} (hu : IsOpen u)
(hne : u.Nonempty) :
∃ (s : _)(_ : s ⊆ u), AffineIndependent ℝ (coe : s → P) ∧ affineSpan ℝ s = ⊤ :=
by
rcases hne with ⟨x, hx⟩
rcases hu.exists_between_affine_independent_span_eq_top (singleton_subset_iff.mpr hx)
(singleton_nonempty _) (affineIndependent_of_subsingleton _ _) with
⟨s, -, hsu, hs⟩
exact ⟨s, hsu, hs⟩
#align is_open.exists_subset_affine_independent_span_eq_top IsOpen.exists_subset_affineIndependent_span_eq_top
/-- The affine span of a nonempty open set is `⊤`. -/
theorem IsOpen.affineSpan_eq_top {u : Set P} (hu : IsOpen u) (hne : u.Nonempty) :
affineSpan ℝ u = ⊤ :=
let ⟨s, hsu, hs, hs'⟩ := hu.exists_subset_affineIndependent_span_eq_top hne
top_unique <| hs' ▸ affineSpan_mono _ hsu
#align is_open.affine_span_eq_top IsOpen.affineSpan_eq_top
theorem affineSpan_eq_top_of_nonempty_interior {s : Set V}
(hs : (interior <| convexHull ℝ s).Nonempty) : affineSpan ℝ s = ⊤ :=
top_unique <|
isOpen_interior.affineSpan_eq_top hs ▸
(affineSpan_mono _ interior_subset).trans_eq (affineSpan_convexHull _)
#align affine_span_eq_top_of_nonempty_interior affineSpan_eq_top_of_nonempty_interior
theorem AffineBasis.centroid_mem_interior_convexHull {ι} [Fintype ι] (b : AffineBasis ι ℝ V) :
Finset.univ.centroid ℝ b ∈ interior (convexHull ℝ (range b)) :=
by
haveI := b.nonempty
simp only [b.interior_convex_hull, mem_set_of_eq, b.coord_apply_centroid (Finset.mem_univ _),
inv_pos, Nat.cast_pos, Finset.card_pos, Finset.univ_nonempty, forall_true_iff]
#align affine_basis.centroid_mem_interior_convex_hull AffineBasis.centroid_mem_interior_convexHull
theorem interior_convexHull_nonempty_iff_affineSpan_eq_top [FiniteDimensional ℝ V] {s : Set V} :
(interior (convexHull ℝ s)).Nonempty ↔ affineSpan ℝ s = ⊤ :=
by
refine' ⟨affineSpan_eq_top_of_nonempty_interior, fun h => _⟩
obtain ⟨t, hts, b, hb⟩ := AffineBasis.exists_affine_subbasis h
suffices (interior (convexHull ℝ (range b))).Nonempty
by
rw [hb, Subtype.range_coe_subtype, set_of_mem_eq] at this
refine' this.mono _
mono*
lift t to Finset V using b.finite_set
exact ⟨_, b.centroid_mem_interior_convex_hull⟩
#align interior_convex_hull_nonempty_iff_affine_span_eq_top interior_convexHull_nonempty_iff_affineSpan_eq_top
theorem Convex.interior_nonempty_iff_affineSpan_eq_top [FiniteDimensional ℝ V] {s : Set V}
(hs : Convex ℝ s) : (interior s).Nonempty ↔ affineSpan ℝ s = ⊤ := by
rw [← interior_convexHull_nonempty_iff_affineSpan_eq_top, hs.convex_hull_eq]
#align convex.interior_nonempty_iff_affine_span_eq_top Convex.interior_nonempty_iff_affineSpan_eq_top
|
type Linear end
type Circular end
type General end
type Permuted end
function müller_rec(; ϵ::Float64 = 0.0, ϕ::Float64 = 0.0, ΔG::Float64 = 0.0, α::Float64 = 45.0*π/180, ψ::Float64 = 0.0)
return [1.0 (-2ϵ*sin(ϕ)*sin(2α) + ΔG/2*cos(2α)) 2ϵ*cos(ϕ) (2ϵ*sin(ϕ)*cos(2α) + ΔG/2*sin(2α))
ΔG/2 cos(2α) 0.0 sin(2α)
2ϵ*cos(ϕ + ψ) sin(2α)*sin(ψ) cos(ψ) -cos(2α)*sin(ψ)
2ϵ*sin(ϕ + ψ) -sin(2α)*cos(ψ) sin(ψ) cos(2α)*cos(ψ)]
end
function müller_rec(::Permuted; ϵ::Float64 = 0.0, ϕ::Float64 = 0.0, ΔG::Float64 = 0.0, α::Float64 = 45.0*π/180, ψ::Float64 = 0.0)
return [1.0 (-2ϵ*sin(ϕ)*sin(2α) + ΔG/2*cos(2α)) 2ϵ*cos(ϕ) (2ϵ*sin(ϕ)*cos(2α) + ΔG/2*sin(2α))
-2ϵ*sin(ϕ + ψ) sin(2α)*cos(ψ) -sin(ψ) -cos(2α)*cos(ψ)
2ϵ*cos(ϕ + ψ) sin(2α)*sin(ψ) cos(ψ) -cos(2α)*sin(ψ)
ΔG/2 cos(2α) 0.0 sin(2α)]
end
function müller_rec(::Linear; ϵ::Float64 = 0.0, ϕ::Float64 = 0.0, ΔG::Float64 = 0.0, δα::Float64 = 0.0, ψ::Float64 = 0.0, s = +)
pm = s(1.0)
mp = -pm
return [1.0 pm*ΔG/2 2ϵ*cos(ϕ) 2ϵ*sin(ϕ)
ΔG/2 pm 0.0 pm*2δα
2ϵ*cos(ϕ + ψ) pm*2δα*sin(ψ) cos(ψ) mp*sin(ψ)
2ϵ*sin(ϕ + ψ) mp*2δα*cos(ψ) sin(ψ) pm*cos(ψ)]
end
function müller_rec(::Circular; ϵ::Float64 = 0.0, ϕ::Float64 = 0.0, ΔG::Float64 = 0.0, δα::Float64 = 0.0, ψ::Float64 = 0.0, s = +)
pm = s(1.0)
mp = -pm
return [1.0 mp*2ϵ*sin(ϕ) 2ϵ*cos(ϕ) pm*ΔG/2
ΔG/2 mp*2δα 0.0 pm
2ϵ*cos(ϕ + ψ) pm*sin(ψ) cos(ψ) pm*2δα*sin(ψ)
2ϵ*sin(ϕ + ψ) mp*cos(ψ) sin(ψ) mp*2δα*cos(ψ)]
end
function müller_sky(PAaz::Float64)
cpa = cos(2*PAaz)
spa = sin(2*PAaz)
return [1.0 0.0 0.0 0.0
0.0 cpa spa 0.0
0.0 -spa cpa 0.0
0.0 0.0 0.0 1.0]
end
function lin_pol_source(;flux::Float64 = 1.0, p::Float64 = 0.1, pa::Float64 = 0.0)
return Float64[flux
p*flux*cos(2*pa)
p*flux*sin(2*pa)
0.0]
end
|
print *, "Fortran test"
call zsim_roi_begin()
call zsim_heartbeat()
call zsim_roi_end()
print *, "Fortran test done"
end
|
theory Keep_Drop
imports Base
begin
definition Keep_Drop where
"Keep_Drop \<Gamma> K D \<equiv> \<Gamma> \<Longrightarrow>\<^sub>A K * D"
lemma init:
assumes
"\<Gamma> \<Longrightarrow>\<^sub>A K * D"
shows
"Keep_Drop \<Gamma> K D"
unfolding Keep_Drop_def
using assms by simp
lemma split:
assumes
"\<Gamma>\<^sub>1 \<Longrightarrow>\<^sub>A K\<^sub>1 * D\<^sub>1"
"\<Gamma>\<^sub>2 \<Longrightarrow>\<^sub>A K\<^sub>2 * D\<^sub>2"
shows
"\<Gamma>\<^sub>1 * \<Gamma>\<^sub>2 \<Longrightarrow>\<^sub>A (K\<^sub>1 * K\<^sub>2) * (D\<^sub>1 * D\<^sub>2)"
apply(sep_drule r: assms(1))
apply(sep_drule r: assms(2))
by sep_auto
lemma keep:
assumes
"\<Gamma> \<Longrightarrow>\<^sub>A \<Gamma>'"
shows
"\<Gamma> \<Longrightarrow>\<^sub>A \<Gamma>' * emp"
using assms
by sep_auto
lemma drop: "\<Gamma> \<Longrightarrow>\<^sub>A emp * \<Gamma>"
by simp
method keep_drop_step methods keep_atom =
rule split | (rule keep, keep_atom) | rule drop
method keep_drop methods keep_atom =
rule init, ((keep_drop_step keep_atom)+; fail)
end
|
!
! Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
! See https://llvm.org/LICENSE.txt for license information.
! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
! maxloc in initialization with repeat real elements
program p
integer :: rslt = 2
integer, parameter, dimension(1) :: mn = maxloc((/4.5, 6.8, 6.8, 3.1/))
call check(mn, rslt, 1)
end
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Some code related to propositional equality that relies on the K
-- rule
------------------------------------------------------------------------
{-# OPTIONS --with-K --safe #-}
module Relation.Binary.PropositionalEquality.WithK where
open import Axiom.UniquenessOfIdentityProofs.WithK
open import Relation.Binary
open import Relation.Binary.PropositionalEquality.Core
------------------------------------------------------------------------
-- Re-exporting safe erasure function
-- ≡-erase ignores its `x ≡ y` argument and reduces to refl whenever
-- x and y are judgmentally equal. This is useful when the computation
-- producing the proof `x ≡ y` is expensive.
open import Agda.Builtin.Equality.Erase
using ()
renaming ( primEraseEquality to ≡-erase )
public
------------------------------------------------------------------------
-- Proof irrelevance
≡-irrelevant : ∀ {a} {A : Set a} → Irrelevant {A = A} _≡_
≡-irrelevant = uip
------------------------------------------------------------------------
-- DEPRECATED NAMES
------------------------------------------------------------------------
-- Please use the new names as continuing support for the old names is
-- not guaranteed.
-- Version 1.0
≡-irrelevance = ≡-irrelevant
{-# WARNING_ON_USAGE ≡-irrelevance
"Warning: ≡-irrelevance was deprecated in v1.0.
Please use ≡-irrelevant instead."
#-}
|
lemma imp_trans (P Q R : Prop) : (P → Q) → ((Q → R) → (P → R)) :=
begin
intros hpq hqr,
intro p,
apply hqr,
apply hpq,
exact p,
end
|
[STATEMENT]
lemma convergent_powser'_gbinomial:
"convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)
[PROOF STEP]
have "(\<lambda>n. lcoeff (gbinomial_series abort p) n * x ^ n) sums (1 + x) powr p" if "abs x < 1" for x
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>n. lcoeff (gbinomial_series abort p) n * x ^ n) sums (1 + x) powr p
[PROOF STEP]
using that gen_binomial_real[of x p]
[PROOF STATE]
proof (prove)
using this:
\<bar>x\<bar> < 1
norm x < 1 \<Longrightarrow> (\<lambda>n. (p gchoose n) * x ^ n) sums (1 + x) powr p
goal (1 subgoal):
1. (\<lambda>n. lcoeff (gbinomial_series abort p) n * x ^ n) sums (1 + x) powr p
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<bar>?x\<bar> < 1 \<Longrightarrow> (\<lambda>n. lcoeff (gbinomial_series abort p) n * ?x ^ n) sums (1 + ?x) powr p
goal (1 subgoal):
1. convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
\<bar>?x\<bar> < 1 \<Longrightarrow> (\<lambda>n. lcoeff (gbinomial_series abort p) n * ?x ^ n) sums (1 + ?x) powr p
goal (1 subgoal):
1. convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)
[PROOF STEP]
unfolding convergent_powser'_def
[PROOF STATE]
proof (prove)
using this:
\<bar>?x\<bar> < 1 \<Longrightarrow> (\<lambda>n. lcoeff (gbinomial_series abort p) n * ?x ^ n) sums (1 + ?x) powr p
goal (1 subgoal):
1. \<exists>R>0. \<forall>x. \<bar>x\<bar> < R \<longrightarrow> (\<lambda>n. lcoeff (gbinomial_series abort p) n * x ^ n) sums (1 + x) powr p
[PROOF STEP]
by (force intro!: exI[of _ 1])
[PROOF STATE]
proof (state)
this:
convergent_powser' (gbinomial_series abort p) (\<lambda>x. (1 + x) powr p)
goal:
No subgoals!
[PROOF STEP]
qed |
import tactic
import algebra.group.defs
import data.vector
import data.nat.basic
import data.nat.nth
noncomputable theory
def starStar (u q j a : ℕ) (b₁ b₂ : fin u.succ) (b₀ : fin b₁.1): Prop :=
-- property the b's should have
u = b₀.1 + b₁.1 * ((j+1) + a*q + b₂.1 * q*q)
∧
(∃ c: fin b₁.1.succ, b₁.1 = c.1*c.1)
∧
∀ d: fin b₁.1, d.1 ≠ 1 → d.1 ∣ (b₁.1) → q ∣ d.1
def βexist (u q j a : ℕ) : Prop := a < q ∧ ∃ b₁ b₂ : fin u.succ, ∃ b₀ : fin b₁.1, starStar u q j a b₁ b₂ b₀
def φβ (u q j a : ℕ) : Prop :=
(βexist u q j a ∧ ∀ aa: fin a, ¬ βexist u q j aa.1) ∨
((∀ aa:fin q, ¬ βexist u q j aa.1) ∧ a = 0)
def stage₁ (s p t z y₀ : ℕ) : Prop :=
φβ t p (2*s) z ∧ φβ t p (2*s+1) y₀
/-
Example program:
0 R₀ = R₀ + ∣,
1 HALT
t p encodes the sequence 0,0,1,0 (line number 0, R₀=0, line number 1, R₀=0)
-/
def inc_R0_once (u:fin 1) (u':fin 2) (u₀ u₀' : ℕ) : Prop :=
-- in general it should depend on u but here u must be 0
u'.1 = u.1 + 1 ∧ u₀' = u₀ + 1
-- Example program 0 R₀ += ∣, 1 R₀ -= ∣, 2 HALT
def inc_dec_R0 (u:fin 2) (u':fin 3) (u₀ u₀' : ℕ) : Prop :=
(u.1=0 → u'.1 = u.1 + 1 ∧ u₀' = u₀ + 1)
∧
(u.1=1 → u'.1 = u.1 + 1 ∧ u₀' = u₀ - 1) -- monus
-- Homework program: 0 R₀ += ∣, 1 PRINT, 2 HALT
def inc_R0_print (u:fin 2) (u':fin 3) (u₀ u₀' : ℕ) : Prop :=
(u.1=0 → u'.1 = u.1 + 1 ∧ u₀' = u₀ + 1)
∧
(u.1=1 → u'.1 = u.1 + 1 ∧ u₀' = u₀)
def χ_steps (k:ℕ)(program:(fin k)→(fin k.succ)→ℕ→ ℕ→Prop) (t p i:ℕ) : Prop :=
∀ u:fin k, ∀ u₀:ℕ, ∀ u':fin k.succ, ∀ u₀' : ℕ,
stage₁ i p t u u₀ → stage₁ (i+1) p t u' u₀' →
program u u' u₀ u₀'
def χ₁ (k:ℕ) (program:(fin k)→(fin k.succ)→ℕ→ℕ→Prop) (x₀ z y₀ : ℕ) : Prop := ∃ s p t : ℕ,
stage₁ 0 p t 0 x₀ ∧
stage₁ s p t z y₀ ∧
∀ i:fin s, χ_steps k program t p i.1
def b_0 (i p:ℕ) (a_ : vector (fin p) i) : ℕ :=
(list.of_fn (λ j:fin i, j.1.succ * (p ^ (2*j.1)))).sum
+
(list.of_fn (λ j:fin i, (a_.nth j).1 * p ^ (2*j.1+1))).sum
def t {r:ℕ} (p:ℕ) (a_ : vector (fin p) r.succ) : ℕ :=
b_0 r.succ p a_
def b_1 (i p:ℕ) : ℕ := p^(2*i)
theorem easy {j i r : ℕ} (h: j < r.succ - (i+1)): i+1+j<r.succ:= lt_tsub_iff_left.mp h
def b_2 (i p :ℕ){r:ℕ} (a_ : vector (fin p) (r.succ)) : ℕ :=
(list.of_fn (λ j:fin (r.succ-(i+1)), (a_.nth (⟨i+1+j.1,easy j.2⟩)).1 * p ^ (2*j.1+1))).sum
+
(list.of_fn (λ j:fin (r-i), (i+2+j.1) * p ^ (2*j.1))).sum
def vector_take {n:ℕ} {α:Type}
(x : vector α n) (i:ℕ) (h: i≤ n) : vector α i :=
⟨(x.take i).1, eq.trans ((x.take i).2) (min_eq_left h)⟩
#eval (nat.prime 11 : bool)
example : nat.prime 11 := sorry -- to avoid having to prove this, we state "decode" and "encode" in a simplified way:
theorem decode {p r:ℕ} (a_ : vector (fin p) r.succ)(i:fin r.succ): -- (hprime: nat.prime p):
φβ (t p a_) p i (a_.nth i)
:= sorry
theorem encode {p:ℕ} ( r i:ℕ)(h:i<r.succ)
(a_ : vector (fin p) r.succ) (a:ℕ):
φβ (t p a_) p i a → a = (a_.nth i)
:= λ hφβ, sorry
theorem le_succ_succ {i j:ℕ}: i < j.succ.succ → i ≤ j ∨ i=j.succ :=
λ h, nat.of_le_succ (nat.lt_succ_iff.mp h)
theorem lt_one {i:ℕ} : i < 1 → i=0 := nat.lt_one_iff.mp
theorem lt_two {i:ℕ} : i < 2 → i=0∨ i=1
:=
λ h2,
have i ≤ 0 ∨ i = 1, from le_succ_succ h2,
this.elim
(λ h, or.inl (nat.le_zero_iff.mp h))
(λ h1, or.inr ( h1))
theorem lt_three {i:ℕ} : i < 3 → i=0∨ i=1∨ i=2
:=
λ h3,
have i ≤ 2, from nat.lt_succ_iff.mp h3,
(em (i=2)).elim (
λ h2, or.inr (or.inr h2)
) (
λ hn2,
have i<2, from ne.lt_of_le hn2 this,
have i ≤ 0 ∨ i = 1, from le_succ_succ this,
this.elim
(λ h, or.inl (nat.le_zero_iff.mp h))
(λ h1, or.inr (or.inl h1))
)
theorem true_of_eq {P:ℕ → Prop} {i j :ℕ} (he: i=j) (hP: P j): P i := cast (congr_arg P he).symm hP
theorem of_lt_3 {P:ℕ → Prop}: P 0 → P 1 → P 2 → ∀ i:fin 3, P i.1 :=
λ h0 h1 h2 i, (lt_three i.2).elim (
λ h, true_of_eq h h0
) (
λ h12, h12.elim
(λ h, true_of_eq h h1)
(λ h, true_of_eq h h2)
)
theorem of_lt_2 {P:ℕ → Prop}: P 0 → P 1 → ∀ i:fin 2, P i.1 :=
λ h0 h1 i, (lt_two i.2).elim (
λ h, true_of_eq h h0
) (
λ h, true_of_eq h h1
)
theorem of_lt_1 {P:ℕ → Prop}: P 0 → ∀ i:fin 1, P i.1 :=
λ h0 i, true_of_eq (lt_one i.2) h0
theorem does_halt_longer: χ₁ 2 inc_dec_R0 0 2 0 :=
let p := 11 in
let a_ := (⟨[0,0,1,1,2,0],rfl⟩: vector (fin p) 6) in
let r := 5 in
exists.intro 2 ( -- number of steps s=2
exists.intro p (
exists.intro (t p a_) (
and.intro (
and.intro (decode a_ 0) (decode a_ 1)
) (
and.intro (
and.intro (decode a_ 4) (decode a_ 5)
) (
of_lt_2 (
λ u u₀ u' u₀' h0 h1,
let t:= t p a_, hu := h0.1, hu₀ := h0.2, hu' := h1.1, hu₀' := h1.2 in
and.intro (
λ hu0,
and.intro (
calc u'.1 = 1: encode r 2 dec_trivial a_ u'.1 hu'
... = 0+1: by ring
... = u.1+1: by rw hu0
) (
have Hu₀: u₀ = (vector.nth a_ 1).1, from encode r 1 dec_trivial a_ u₀ hu₀,
show u₀' = u₀ + 1, from calc
_ = (vector.nth a_ 3).1: encode r 3 dec_trivial a_ u₀' hu₀'
... = 0+1: by ring
... = (vector.nth a_ 1).1 + 1: rfl
... = u₀+1: by rw Hu₀
)
) (
λ hu1, -- show line number 1 at stage 0 doesn't, and can't, happen
false.elim (
have u.1 = 0, from encode r 0 dec_trivial a_ u hu,
zero_ne_one (eq.trans this.symm hu1)
)
)
) (
let t:= t p a_ in
show ∀ u:fin 2, ∀ u₀:ℕ, ∀ u':fin 3, ∀ u₀' : ℕ,
stage₁ 1 p t u u₀ → stage₁ (1+1) p t u' u₀' →
inc_dec_R0 u u' u₀ u₀', from
λ u u₀ u' u₀' h0 h1,
let hu := h0.1, hu₀ := h0.2, hu' := h1.1, hu₀' := h1.2 in
show (u.1=0 → u'.1 = u.1 + 1 ∧ u₀' = u₀ + 1)
∧
(u.1=1 → u'.1 = u.1 + 1 ∧ u₀' = u₀ - 1) -- monus
, from
and.intro (
λ hu0,-- can't happen
false.elim (
have u.1 = 1, from encode r 2 dec_trivial a_ u hu,
zero_ne_one (eq.trans hu0.symm this)
)
) (
λ hu1,
and.intro (
calc u'.1 = 2: encode r 4 dec_trivial a_ u'.1 hu'
... = 1+1: by ring
... = u.1+1: by rw hu1
) (
have Hu₀: u₀ = (vector.nth a_ 3).1, from encode r 3 dec_trivial a_ u₀ hu₀,
show u₀' = u₀ - 1, from calc
_ = (vector.nth a_ 5).1: encode r 5 dec_trivial a_ u₀' hu₀'
... = 1-1: by ring
... = (vector.nth a_ 3).1 - 1: rfl
... = u₀-1: by rw Hu₀
)
)
)
)
)
)
)
)
theorem does_halt: χ₁ 1 inc_R0_once 0 1 1 :=
let p := 5 in
let a_ := (⟨[0,0,1,1],rfl⟩: vector (fin p) 4) in
let r := 3 in -- r is length a_ minus one
exists.intro 1 (
exists.intro p
(
exists.intro (t p a_)
(
and.intro (
and.intro (decode a_ 0) (decode a_ 1)
) (
and.intro (
and.intro (decode a_ 2) (decode a_ 3)
) (
of_lt_1 (
λ u u₀ u' u₀',
λ hfst hsnd,
let hu := hfst.1, hu₀ := hfst.2, hu' := hsnd.1, hu₀' := hsnd.2 in
and.intro (
calc u'.1 = 1: encode r 2 dec_trivial a_ u'.1 hu'
... = 0+1: by ring
... = u.1+1: by rw (lt_one u.2)
) (
have Hu₀: u₀ = (vector.nth a_ 1).1, from encode r 1 dec_trivial a_ u₀ hu₀,
show u₀' = u₀ + 1, from calc
_ = (vector.nth a_ r).1: encode r r dec_trivial a_ u₀' hu₀'
... = 0+1: by ring
... = (vector.nth a_ 1).1 + 1: rfl
... = u₀+1: by rw Hu₀
)
)
)
)
)
)
)
theorem homework: χ₁ 2 inc_R0_print 0 2 1 := -- starting at config (0,0), we get to config (2,1)
-- HOMEWORK
sorry
|
[STATEMENT]
lemma chain_reparam_chain'_line_integral_smooth_cubes:
assumes "chain_reparam_chain' one_chain1 one_chain2"
"\<forall>(k2,\<gamma>2)\<in>one_chain2. \<gamma>2 C1_differentiable_on {0..1}"
"\<forall>b\<in>basis.\<forall>(k2,\<gamma>2)\<in>one_chain2. continuous_on (path_image \<gamma>2) (\<lambda>x. F x \<bullet> b)"
"finite basis"
"finite one_chain1"
"boundary_chain one_chain1"
"boundary_chain one_chain2"
"\<forall>(k,\<gamma>)\<in>one_chain1. valid_path \<gamma>"
shows "one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2"
"\<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2 &&& \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
fix b
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
assume "b \<in> basis"
[PROOF STATE]
proof (state)
this:
b \<in> basis
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
fix k \<gamma>
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
assume "(k, \<gamma>)\<in>one_chain2"
[PROOF STATE]
proof (state)
this:
(k, \<gamma>) \<in> one_chain2
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
have "line_integral_exists F {b} \<gamma>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. line_integral_exists F {b} \<gamma>
[PROOF STEP]
apply(rule line_integral_exists_smooth)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<gamma> C1_differentiable_on {0..1}
2. \<forall>b\<in>{b}. continuous_on (path_image \<gamma>) (\<lambda>x. F x \<bullet> b)
3. finite {b}
[PROOF STEP]
using \<open>(k, \<gamma>) \<in> one_chain2\<close> assms(2)
[PROOF STATE]
proof (prove)
using this:
(k, \<gamma>) \<in> one_chain2
\<forall>(k2, \<gamma>2)\<in>one_chain2. \<gamma>2 C1_differentiable_on {0..1}
goal (3 subgoals):
1. \<gamma> C1_differentiable_on {0..1}
2. \<forall>b\<in>{b}. continuous_on (path_image \<gamma>) (\<lambda>x. F x \<bullet> b)
3. finite {b}
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<forall>b\<in>{b}. continuous_on (path_image \<gamma>) (\<lambda>x. F x \<bullet> b)
2. finite {b}
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
chain_reparam_chain' one_chain1 one_chain2
\<forall>(k2, \<gamma>2)\<in>one_chain2. \<gamma>2 C1_differentiable_on {0..1}
\<forall>b\<in>basis. \<forall>(k2, \<gamma>2)\<in>one_chain2. continuous_on (path_image \<gamma>2) (\<lambda>x. F x \<bullet> b)
finite basis
finite one_chain1
boundary_chain one_chain1
boundary_chain one_chain2
\<forall>(k, \<gamma>)\<in>one_chain1. valid_path \<gamma>
goal (2 subgoals):
1. \<forall>b\<in>{b}. continuous_on (path_image \<gamma>) (\<lambda>x. F x \<bullet> b)
2. finite {b}
[PROOF STEP]
using \<open>(k, \<gamma>) \<in> one_chain2\<close> \<open>b \<in> basis\<close>
[PROOF STATE]
proof (prove)
using this:
chain_reparam_chain' one_chain1 one_chain2
\<forall>(k2, \<gamma>2)\<in>one_chain2. \<gamma>2 C1_differentiable_on {0..1}
\<forall>b\<in>basis. \<forall>(k2, \<gamma>2)\<in>one_chain2. continuous_on (path_image \<gamma>2) (\<lambda>x. F x \<bullet> b)
finite basis
finite one_chain1
boundary_chain one_chain1
boundary_chain one_chain2
\<forall>(k, \<gamma>)\<in>one_chain1. valid_path \<gamma>
(k, \<gamma>) \<in> one_chain2
b \<in> basis
goal (2 subgoals):
1. \<forall>b\<in>{b}. continuous_on (path_image \<gamma>) (\<lambda>x. F x \<bullet> b)
2. finite {b}
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite {b}
[PROOF STEP]
using \<open>b \<in> basis\<close>
[PROOF STATE]
proof (prove)
using this:
b \<in> basis
goal (1 subgoal):
1. finite {b}
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
line_integral_exists F {b} \<gamma>
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<lbrakk>?b2 \<in> basis; (?k2, ?\<gamma>2) \<in> one_chain2\<rbrakk> \<Longrightarrow> line_integral_exists F {?b2} ?\<gamma>2
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>?b2 \<in> basis; (?k2, ?\<gamma>2) \<in> one_chain2\<rbrakk> \<Longrightarrow> line_integral_exists F {?b2} ?\<gamma>2
[PROOF STEP]
have a: "\<forall>b\<in>basis. \<forall>(k, \<gamma>)\<in>one_chain2. line_integral_exists F {b} \<gamma>"
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?b2 \<in> basis; (?k2, ?\<gamma>2) \<in> one_chain2\<rbrakk> \<Longrightarrow> line_integral_exists F {?b2} ?\<gamma>2
goal (1 subgoal):
1. \<forall>b\<in>basis. \<forall>(k, \<gamma>)\<in>one_chain2. line_integral_exists F {b} \<gamma>
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<forall>b\<in>basis. \<forall>(k, \<gamma>)\<in>one_chain2. line_integral_exists F {b} \<gamma>
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
have b: "\<forall>(k2,\<gamma>2)\<in>one_chain2. valid_path \<gamma>2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(k2, \<gamma>2)\<in>one_chain2. valid_path \<gamma>2
[PROOF STEP]
using assms(2)
[PROOF STATE]
proof (prove)
using this:
\<forall>(k2, \<gamma>2)\<in>one_chain2. \<gamma>2 C1_differentiable_on {0..1}
goal (1 subgoal):
1. \<forall>(k2, \<gamma>2)\<in>one_chain2. valid_path \<gamma>2
[PROOF STEP]
by (simp add: C1_differentiable_imp_piecewise case_prod_beta valid_path_def)
[PROOF STATE]
proof (state)
this:
\<forall>(k2, \<gamma>2)\<in>one_chain2. valid_path \<gamma>2
goal (2 subgoals):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
2. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
show "one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
[PROOF STEP]
by (rule chain_reparam_chain'_line_integral[OF assms(1) assms(6) assms(7) a b assms(8) assms(5) assms(4) assms(3)])
[PROOF STATE]
proof (state)
this:
one_chain_line_integral F basis one_chain1 = one_chain_line_integral F basis one_chain2
goal (1 subgoal):
1. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
show "\<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
[PROOF STEP]
by (rule chain_reparam_chain'_line_integral[OF assms(1) assms(6) assms(7) a b assms(8) assms(5) assms(4) assms(3)])
[PROOF STATE]
proof (state)
this:
\<forall>(k, \<gamma>)\<in>one_chain1. line_integral_exists F basis \<gamma>
goal:
No subgoals!
[PROOF STEP]
qed |
State Before: n : ℕ
⊢ antidiagonal (n + 1) = (0, n + 1) ::ₘ map (Prod.map Nat.succ id) (antidiagonal n) State After: no goals Tactic: simp only [antidiagonal, List.Nat.antidiagonal_succ, coe_map, cons_coe] |
{-# LANGUAGE ScopedTypeVariables, GADTs #-}
module Main where
import Control.Monad
import Data.Complex
import Data.Int
import Data.List
import Data.Mat
import qualified Data.Map
import Data.Maybe
import System.Environment
import System.Exit
import System.IO
-- A universal datatype for MAT data.
data MatVal =
VDouble Double
| VInt64 Int64
| VBool Bool
| VChar Char
| VComplex (Complex MatVal)
| VStruct (Data.Map.Map String MatVal)
| VArray Int [MatVal]
deriving (Eq, Show)
-- | Transform from the types into the universal representation.
toMatVal :: MatData -> MatVal
toMatVal (MatData MatDouble d) = VDouble d
toMatVal (MatData MatInt64 i) = VInt64 i
toMatVal (MatData MatBool b) = VBool b
toMatVal (MatData MatChar c) = VChar c
toMatVal (MatData MatCell d) = toMatVal d
toMatVal (MatData (MatStruct (Known fs)) ds) = VStruct (Data.Map.fromList (zip fs (map toMatVal ds)))
toMatVal (MatData (MatArray t (Known d)) xs) = VArray d (map (toMatVal . MatData t) xs)
toMatVal (MatData (MatComplex t) (x :+ y)) = matZipWith (\ r i -> VComplex (r :+ i)) (toMatVal (MatData t x)) (toMatVal (MatData t y))
-- | Push down complex values.
matZipWith :: (MatVal -> MatVal -> MatVal) -> MatVal -> MatVal -> MatVal
matZipWith op (VStruct xs) (VStruct ys) = VStruct (Data.Map.unionWith (matZipWith op) xs ys)
matZipWith op (VArray d xs) (VArray _ ys) = VArray d (zipWith (matZipWith op) xs ys)
matZipWith op x y = op x y
main :: IO ()
main = do
(fp:_) <- getArgs
-- Read an entire MAT file
xs :: [(String, MatData)] <- liftM Data.Map.toList (readMatFile fp)
putStrLn "Variables contained in MAT file:"
-- Print all the contents
mapM_ (\ (n, d) -> putStr (n ++ " ->\n " ++ show (toMatVal d) ++ "\n")) xs
exitSuccess
|
{-# OPTIONS_GHC -Wall #-}
module Numeric.FFT.HMatrix.Vector (
-- * Complex-to-complex transforms
dft
, idft
-- * Real-to-complex transforms
, dftR2C
, dftC2R
-- * Real-to-real transforms
-- ** Discrete cosine transforms
, dct1
, dct2
, dct3
, dct4
-- ** Discrete sine transforms
, dst1
, dst2
, dst3
, dst4
) where
import Foreign.Storable ( Storable )
import Numeric.LinearAlgebra.Data ( Vector, Complex )
import Numeric.LinearAlgebra ( Element )
import qualified Numeric.LinearAlgebra.Data as M
import qualified Numeric.FFT.Vector.Unnormalized as FFT
dft :: Vector (Complex Double) -> Vector (Complex Double)
dft = FFT.run FFT.dft
idft :: Vector (Complex Double) -> Vector (Complex Double)
idft = FFT.run FFT.idft
dftR2C :: Vector Double -> Vector (Complex Double)
dftR2C = FFT.run FFT.dftR2C
dftC2R :: Vector (Complex Double) -> Vector Double
dftC2R = FFT.run FFT.dftC2R
dct1 :: Vector Double -> Vector Double
dct1 = FFT.run FFT.dct1
dct2 :: Vector Double -> Vector Double
dct2 = FFT.run FFT.dct2
dct3 :: Vector Double -> Vector Double
dct3 = FFT.run FFT.dct3
dct4 :: Vector Double -> Vector Double
dct4 = FFT.run FFT.dct4
dst1 :: Vector Double -> Vector Double
dst1 = FFT.run FFT.dst1
dst2 :: Vector Double -> Vector Double
dst2 = FFT.run FFT.dst2
dst3 :: Vector Double -> Vector Double
dst3 = FFT.run FFT.dst3
dst4 :: Vector Double -> Vector Double
dst4 = FFT.run FFT.dst4
|
#define BOOST_TEST_MODULE L4Unittests
#include <boost/test/unit_test.hpp>
|
Coq < Section Easy006b.
Coq < Require Import Classical.
Coq < Load CpdtTactics.
Coq < Variables Y A W: Prop.
Y is assumed
A is assumed
W is assumed
Coq < Goal ~(Y <-> A) /\ ~Y /\ ~A -> (W /\ ~W).
1 subgoal
Y : Prop
A : Prop
W : Prop
============================
~ (Y <-> A) /\ ~ Y /\ ~ A -> W /\ ~ W
Unnamed_thm < intros.
1 subgoal
Y : Prop
A : Prop
W : Prop
H : ~ (Y <-> A) /\ ~ Y /\ ~ A
============================
W /\ ~ W
Unnamed_thm < destruct H.
1 subgoal
Y : Prop
A : Prop
W : Prop
H : ~ (Y <-> A)
H0 : ~ Y /\ ~ A
============================
W /\ ~ W
Unnamed_thm < tauto.
No more subgoals.
Unnamed_thm < Qed.
intros.
destruct H.
auto.
tauto.
Unnamed_thm is defined
|
(** * Convenience Notations for Describing Context Free Grammars *)
Require Import Coq.Strings.String Coq.Lists.List.
Require Import Fiat.Parsers.ContextFreeGrammar.Core.
Require Export Fiat.Parsers.ContextFreeGrammar.Reflective.
Require Export Fiat.Parsers.ContextFreeGrammar.PreNotations.
Require Import Fiat.Common.Notations.
Export Coq.Strings.Ascii.
Export Coq.Strings.String.
Export Fiat.Parsers.ContextFreeGrammar.Core.
(** ** Generic setup *)
(** We have various scopes and helper-functions behind the machinery
of CFG notations. *)
Delimit Scope item_scope with item.
Bind Scope item_scope with item.
Bind Scope item_scope with ritem.
Delimit Scope production_scope with production.
Delimit Scope production_with_action_scope with production_with_action.
Delimit Scope prod_assignment_scope with prod_assignment.
Delimit Scope prod_with_action_assignment_scope with prod_with_action_assignment.
Bind Scope production_scope with production.
Bind Scope production_scope with rproduction.
Bind Scope production_with_action_scope with rproduction_with_action.
Delimit Scope productions_scope with productions.
Delimit Scope productions_assignment_scope with productions_assignment.
Delimit Scope productions_with_actions_scope with productions_with_actions.
Delimit Scope productions_with_actions_assignment_scope with productions_with_actions_assignment.
Bind Scope productions_with_action_scope with rproductions_with_actions.
Bind Scope productions_scope with productions.
Bind Scope productions_scope with rproductions.
Delimit Scope grammar_scope with grammar.
Delimit Scope grammar_with_actions_scope with grammar_with_actions.
Bind Scope grammar_scope with pregrammar.
Bind Scope grammar_scope with grammar.
Bind Scope grammar_with_actions_scope with pregrammar_with_actions.
Module opt'.
Definition map {A B} := Eval compute in @List.map A B.
Definition list_of_string := Eval compute in @StringOperations.list_of_string.
Definition pred := Eval compute in pred.
Definition length := Eval compute in String.length.
Definition substring := Eval compute in substring.
End opt'.
(** single characters are terminals, anything wrapped with "'" is a
string literal, everything else is a nonterminal *)
Coercion rproduction_of_string (s : string) : rproduction Ascii.ascii
:= match s with
| EmptyString => nil
| String.String ch EmptyString => (RTerminal (rbeq ch))::nil
| String.String "'" s'
=> match opt'.substring (opt'.pred (opt'.length s')) 1 s' with
| String.String "'" EmptyString
=> opt'.map (fun ch => RTerminal (rbeq ch))
(opt'.list_of_string (opt'.substring 0 (opt'.pred (opt'.length s')) s'))
| _ => (RNonTerminal s)::nil
end
| _ => (RNonTerminal s)::nil
end.
Global Arguments rproduction_of_string / _.
(** juxtaposition of productions should yield concatenation *)
Definition magic_juxta_append_rproduction {Char} (p ps : rproduction Char) : rproduction Char
:= Eval compute in p ++ ps.
Coercion magic_juxta_append_rproduction : rproduction >-> Funclass.
Definition combine_rproduction_with_action {T Char} (pat : rproduction Char) (act : action_of_rproduction T pat)
: rproduction_with_action Char T
:= existT _ pat act.
Coercion rproductions_of_rproduction {Char} (p : rproduction Char) : rproductions Char
:= p::nil.
Coercion rproductions_with_action_of_rproduction_with_action {Char T} (p : rproduction_with_action Char T) : rproductions_with_actions Char T
:= p::nil.
Definition magic_juxta_append_rproductions {Char} (p ps : rproductions Char) : rproductions Char
:= Eval compute in p ++ ps.
Definition magic_juxta_append_rproductions_with_actions {Char T} (p ps : rproductions_with_actions Char T) : rproductions_with_actions Char T
:= Eval compute in p ++ ps.
Coercion char_to_test_eq (c : Ascii.ascii) : RCharExpr Ascii.ascii
:= rbeq c.
Coercion rproduction_of_RCharExpr {Char} (c : RCharExpr Char) : rproduction Char
:= (RTerminal c :: nil)%list.
Global Arguments char_to_test_eq / _.
Global Arguments rproduction_of_RCharExpr / _ _.
Global Arguments rproduction_of_string / _.
Global Arguments magic_juxta_append_rproduction / _ _ _.
Global Arguments rproductions_of_rproduction / _ _.
Global Arguments rproductions_with_action_of_rproduction_with_action / _ _ _.
Global Arguments magic_juxta_append_rproductions / _ _ _.
Global Arguments magic_juxta_append_rproductions_with_actions / _ _ _ _.
(** ** Notations *)
(** Use [||] to mean a choice, e.g., ["a" || "b"] in [char_scope] or
[production_scope] (not [productions_scope]) means "a character
which is either an 'a' or a 'b'." In [productions_scope], it means
"either one production, or another production". *)
Notation "p || p'" := (ror p%char p'%char) : char_scope.
Notation "p || p'" := ((p || p')%char : rproduction Ascii.ascii) : production_scope.
Notation "p && p'" := (rand p%char p'%char) : char_scope.
Notation "p && p'" := ((p && p')%char : rproduction Ascii.ascii) : production_scope.
Notation "p || p'" := (magic_juxta_append_rproductions p%productions p'%productions) : productions_scope.
Notation "p || p'" := (magic_juxta_append_rproductions_with_actions p%productions_with_actions p'%productions_with_actions) : productions_with_actions_scope.
Notation "p <{< act >}>" := (combine_rproduction_with_action p%production act) : production_with_action_scope.
Notation "p <{< act >}>" := (combine_rproduction_with_action p%production act) : productions_with_actions_scope.
(** Negation of terminals. There's not yet support for inverting the
sense of productions. *)
Notation "~ p" := (rneg p%char) : char_scope.
Notation "¬ p" := ((~p)%char) (at level 75, right associativity) : char_scope.
Notation "~ p" := ((~p)%char : rproduction Ascii.ascii) : productions_scope.
Notation "¬ p" := ((~p)%productions) (at level 75, right associativity) : productions_scope.
Notation "n0 ::== r0" := ((n0 : string)%string, (r0 : rproductions Ascii.ascii)%productions) (at level 100) : prod_assignment_scope.
Notation "n0 ::== r0" := ((n0 : string)%string, (r0 : rproductions_with_actions Ascii.ascii _)%productions_with_actions) (at level 100) : prod_with_action_assignment_scope.
Notation "[[[ x ;; .. ;; y ]]]" :=
(list_to_productions nil (cons x%prod_assignment .. (cons y%prod_assignment nil) .. )) : productions_assignment_scope.
Notation "[[[ x ;; .. ;; y ]]]" :=
(list_to_productions nil (cons x%prod_with_action_assignment .. (cons y%prod_with_action_assignment nil) .. )) : productions_with_actions_assignment_scope.
Notation "[[[ x ;; .. ;; y ]]]" :=
({| pregrammar_rproductions := (cons x%prod_assignment .. (cons y%prod_assignment nil) .. ) |}) : grammar_scope.
Notation "[[[ x ;; .. ;; y ]]]" :=
({| pregrammar_arproductions := (cons x%prod_with_action_assignment .. (cons y%prod_with_action_assignment nil) .. ) |}) : grammar_with_actions_scope.
Local Open Scope string_scope.
Global Open Scope grammar_scope.
Global Open Scope string_scope.
Notation code_in_range ch_low ch_high := (rand (rcode_ge_than (opt.N_of_ascii ch_low)) (rcode_le_than (opt.N_of_ascii ch_high))).
Notation "'[0-9]'" := (RTerminal (code_in_range "0" "9")) : item_scope.
Notation "'[0-9]'" := (([0-9]%item::nil) : rproduction Ascii.ascii) : production_scope.
Notation "'[0-9]'" := ([0-9]%production) : productions_scope.
Notation "'[A-Z]'" := (RTerminal (code_in_range "A" "Z")) : item_scope.
Notation "'[A-Z]'" := (([A-Z]%item::nil) : rproduction Ascii.ascii) : production_scope.
Notation "'[A-Z]'" := ([A-Z]%production) : productions_scope.
Notation "'[a-z]'" := (RTerminal (code_in_range "a" "z")) : item_scope.
Notation "'[a-z]'" := (([a-z]%item::nil) : rproduction Ascii.ascii) : production_scope.
Notation "'[a-z]'" := ([a-z]%production) : productions_scope.
Local Notation LF := (ascii_of_N 10).
Local Notation CR := (ascii_of_N 13).
Local Notation TAB := (ascii_of_N 9).
Local Notation SPACE := " "%char.
(** Notation for whitespace: space, tab, line feed, carriage return *)
Notation "'\n'" := LF : char_scope.
Notation "'\n'" := (String.String \n%char EmptyString) : string_scope.
Notation "'\r'" := CR : char_scope.
Notation "'\r'" := (String.String \r%char EmptyString) : string_scope.
Notation "'\t'" := TAB : char_scope.
Notation "'\t'" := (String.String \t%char EmptyString) : string_scope.
Notation "'[\s]'" := (\n || \r || " " || \t)%char : char_scope.
Notation "'[\s]'" := ([\s])%char : item_scope.
Notation "'[\s]'" := (([\s]%item) : rproduction Ascii.ascii) : production_scope.
Notation "'[\s]'" := [\s]%production : productions_scope.
Notation "'[0-9a-fA-F]'" := (RTerminal (code_in_range "0" "9"
|| code_in_range "a" "f"
|| code_in_range "A" "F")%rchar) : item_scope.
Notation "'[0-9a-fA-F]'" := (([0-9a-fA-F]%item::nil)%list : rproduction Ascii.ascii) : production_scope.
Notation "'[0-9a-fA-F]'" := [0-9a-fA-F]%production : productions_scope.
Notation "'[1-9]'" := (RTerminal (code_in_range "1" "9")) : item_scope.
Notation "'[1-9]'" := (([1-9]%item::nil)%list : rproduction Ascii.ascii) : production_scope.
Notation "'[1-9]'" := ([1-9]%production) : productions_scope.
Global Arguments Equality.ascii_beq !_ !_.
Global Arguments Equality.string_beq !_ !_.
Global Arguments ascii_of_nat !_ / .
Global Arguments ascii_of_N !_ / .
Global Arguments ascii_of_pos !_ / .
Definition parseAscii_as_nat (v : ascii) : nat
:= Nat.modulo (1 + nat_of_ascii v - nat_of_ascii "1"%char) 10.
Declare Reduction grammar_red := cbv beta iota zeta delta [ascii_of_pos rproduction_of_string magic_juxta_append_rproduction magic_juxta_append_rproductions rproductions_of_rproduction list_to_productions char_to_test_eq rproduction_of_RCharExpr ascii_of_nat ascii_of_pos ascii_of_N BinNat.N.of_nat shift BinPos.Pos.of_succ_nat BinPos.Pos.succ one zero opt'.map opt'.list_of_string opt'.pred opt'.length opt'.substring interp_RCharExpr interp_ritem interp_rproduction interp_rproductions irbeq irN_of ascii_interp_RCharExpr_data parseAscii_as_nat magic_juxta_append_rproductions_with_actions combine_rproduction_with_action].
Create HintDb parser_sharpen_db discriminated.
Hint Unfold ascii_of_pos rproduction_of_string magic_juxta_append_rproduction magic_juxta_append_rproductions rproductions_of_rproduction list_to_productions char_to_test_eq rproduction_of_RCharExpr ascii_of_nat ascii_of_pos ascii_of_N BinNat.N.of_nat shift BinPos.Pos.of_succ_nat BinPos.Pos.succ one zero opt'.map opt'.list_of_string opt'.pred opt'.length opt'.substring interp_RCharExpr interp_ritem interp_rproduction interp_rproductions irbeq irN_of ascii_interp_RCharExpr_data parseAscii_as_nat magic_juxta_append_rproductions_with_actions combine_rproduction_with_action : parser_sharpen_db.
|
module _ where
data D (@erased A : Set) : Set
-- The modality should not be repeated here
data D (@erased A) where
mkD : D A
|
Subsets and Splits