text
stringlengths 0
3.34M
|
---|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
_RDFT_CONST := 2.5;
#F TRDFT2D([<m>, <n>], <k>)
Class(TRDFT2D, TaggedNonTerminal, rec(
abbrevs := [
P -> Checked(IsList(P), Length(P) = 2, ForAll(P,i->IsPosInt(i) and IsEvenInt(i)), Product(P) > 1,
[ RemoveOnes(P), 1]),
(P,k) -> Checked(IsList(P), Length(P) = 2, ForAll(P,IsPosInt), IsInt(k), Product(P) > 1,
Gcd(Product(P), k)=1,
[ RemoveOnes(P), k mod Product(P)])
],
dims := self >> let(m := self.params[1][1], n := self.params[1][2], d := [n*(m+2), m*n], When(self.transposed, Reversed(d), d)),
isReal := True,
terminate := self >>
Gath(fTensor(fAdd(self.params[1][1], (self.params[1][1]+2)/2, 0), fId(2*self.params[1][2]))) *
RC(MDDFT(self.params[1], self.params[2]).terminate()) *
Scat(fTensor(fId(Product(self.params[1])), fBase(2, 0))),
normalizedArithCost := (self) >> let(n := Product(self.params[1]), IntDouble(_RDFT_CONST * n * d_log(n) / d_log(2))),
compute := meth(self, data)
local rows, cols, cxrows, m1, m2;
rows := self.params[1][1];
cols := self.params[1][2];
cxrows := Rows(self)/cols;
m1 := List(TransposedMat(List(TransposedMat(data), i->ComplexFFT(i){[1..cxrows/2]})), ComplexFFT);
m2 := Flat(List(Flat(m1), i->[ReComplex(i), ImComplex(i)]));
return List([0..cxrows-1], i->m2{[cols*i+1..cols*(i+1)]});
end
));
#F TIRDFT2D([<m>, <n>], <k>)
Class(TIRDFT2D, TaggedNonTerminal, rec(
abbrevs := [
P -> Checked(IsList(P), Length(P) = 2, ForAll(P,i->IsPosInt(i) and IsEvenInt(i)), Product(P) > 1,
[ RemoveOnes(P), 1]),
(P,k) -> Checked(IsList(P), Length(P) = 2, ForAll(P,IsPosInt), IsInt(k), Product(P) > 1,
Gcd(Product(P), k)=1,
[ RemoveOnes(P), k mod Product(P)])
],
dims := self >> let(m := self.params[1][1], n := self.params[1][2], d := [m*n, n*(m+2)], When(self.transposed, Reversed(d), d)),
isReal := True,
terminate := self >> let(cxrows := (self.params[1][1]+2)/2, rows := self.params[1][1], cols := self.params[1][2], k := self.params[2],
Tensor(PRDFT(rows,k).inverse().terminate(), I(cols)) * Tensor(I(cxrows), L(2*cols, 2)*RC(DFT(cols, -k)))),
normalizedArithCost := (self) >> let(n := Product(self.params[1]), IntDouble(_RDFT_CONST * n * d_log(n) / d_log(2)))
));
#F 2D RDFT Rule
NewRulesFor(TRDFT2D, rec(
TRDFT2D_ColRow_tSPL := rec(
switch := true,
applicable := (self, t) >> true,
children := (self, t) >> let(m := t.params[1][1], n:=t.params[1][2], k:= t.params[2], tags := t.getTags(),
[[
TCompose([
TTensorI(TCompose([TRC(DFT(n, k)), TPrm(L(2*n, n))]), (m+2)/2, APar, APar),
TTensorI(PRDFT1(m, k), n, AVec, AVec)
]).withTags(t.getTags())
]]),
apply := (self, t, C, Nonterms) >> C[1]
)
));
#F 2D IRDFT Rule
NewRulesFor(TIRDFT2D, rec(
TIRDFT2D_RowCol_tSPL := rec(
switch := true,
applicable := (self, t) >> true,
children := (self, t) >> let(m := t.params[1][1], n:=t.params[1][2], k:= t.params[2], tags := t.getTags(),
[[
TCompose([
TTensorI(PRDFT1(m, k).inverse(), n, AVec, AVec),
TTensorI(TCompose([TPrm(L(2*n, 2)), TRC(DFT(n, -k))]), (m+2)/2, APar, APar)
]).withTags(t.getTags())
]]),
apply := (self, t, C, Nonterms) >> C[1]
)
));
|
import chainer
import h5py
import numpy as np
import model
# Create a model object first
model = model.MLP()
def save_parameters_as_npz(model, filename='model.npz'):
# Save the model parameters into a NPZ file
chainer.serializers.save_npz(filename, model)
print('{} saved!\n'.format(filename))
# Load the saved npz from NumPy and show the parameter shapes
print('--- The list of saved params in model.npz ---')
saved_params = np.load('model.npz')
for param_key, param in saved_params.items():
print(param_key, '\t:', param.shape)
print('---------------------------------------------\n')
def save_parameters_as_hdf5(model, filename='model.h5'):
# Save the model parameters into a HDF5 archive
chainer.serializers.save_hdf5(filename, model)
print('model.h5 saved!\n')
# Load the saved HDF5 using h5py
print('--- The list of saved params in model.h5 ---')
f = h5py.File('model.h5', 'r')
for param_key, param in f.items():
msg = '{}:'.format(param_key)
if isinstance(param, h5py.Dataset):
msg += ' {}'.format(param.shape)
print(msg)
if isinstance(param, h5py.Group):
for child_key, child in param.items():
print(' {}:{}'.format(child_key, child.shape))
print('---------------------------------------------\n')
save_parameters_as_npz(model)
save_parameters_as_hdf5(model)
|
header {* The Free Group *}
theory "FreeGroups"
imports
"~~/src/HOL/Algebra/Group"
"Cancelation"
"Generators"
begin
text {*
Based on the work in @{theory Cancelation}, the free group is now easily defined
over the set of fully canceled words with the corresponding operations.
*}
subsection {* Inversion *}
text {*
To define the inverse of a word, we first create a helper function that inverts
a single generator, and show that it is self-inverse.
*}
definition inv1 :: "'a g_i \<Rightarrow> 'a g_i"
where "inv1 = apfst Not"
lemma inv1_inv1: "inv1 \<circ> inv1 = id"
by (simp add: fun_eq_iff comp_def inv1_def)
lemmas inv1_inv1_simp [simp] = inv1_inv1[unfolded id_def]
lemma snd_inv1: "snd \<circ> inv1 = snd"
by(simp add: fun_eq_iff comp_def inv1_def)
text {*
The inverse of a word is obtained by reversing the order of the generators and
inverting each generator using @{term inv1}. Some properties of @{term inv_fg}
are noted.
*}
definition inv_fg :: "'a word_g_i \<Rightarrow> 'a word_g_i"
where "inv_fg l = rev (map inv1 l)"
lemma inv_idemp: "inv_fg (inv_fg l) = l"
by (auto simp add:inv_fg_def rev_map)
lemma inv_fg_cancel: "normalize (l @ inv_fg l) = []"
proof(induct l rule:rev_induct)
case Nil thus ?case
by (auto simp add: inv_fg_def)
next
case (snoc x xs)
have "canceling x (inv1 x)" by (simp add:inv1_def canceling_def)
moreover
let ?i = "length xs"
have "Suc ?i < length xs + 1 + 1 + length xs"
by auto
moreover
have "inv_fg (xs @ [x]) = [inv1 x] @ inv_fg xs"
by (auto simp add:inv_fg_def)
ultimately
have "cancels_to_1_at ?i (xs @ [x] @ (inv_fg (xs @ [x]))) (xs @ inv_fg xs)"
by (auto simp add:cancels_to_1_at_def cancel_at_def nth_append)
hence "cancels_to_1 (xs @ [x] @ (inv_fg (xs @ [x]))) (xs @ inv_fg xs)"
by (auto simp add: cancels_to_1_def)
hence "cancels_to (xs @ [x] @ (inv_fg (xs @ [x]))) (xs @ inv_fg xs)"
by (auto simp add:cancels_to_def)
with `normalize (xs @ (inv_fg xs)) = []`
show "normalize ((xs @ [x]) @ (inv_fg (xs @ [x]))) = []"
by auto
qed
lemma inv_fg_cancel2: "normalize (inv_fg l @ l) = []"
proof-
have "normalize (inv_fg l @ inv_fg (inv_fg l)) = []" by (rule inv_fg_cancel)
thus "normalize (inv_fg l @ l) = []" by (simp add: inv_idemp)
qed
lemma canceled_rev:
assumes "canceled l"
shows "canceled (rev l)"
proof(rule ccontr)
assume "\<not>canceled (rev l)"
hence "DomainP cancels_to_1 (rev l)" by (simp add: canceled_def)
then obtain l' where "cancels_to_1 (rev l) l'" by auto
then obtain i where "cancels_to_1_at i (rev l) l'" by (auto simp add:cancels_to_1_def)
hence "Suc i < length (rev l)"
and "canceling (rev l ! i) (rev l ! Suc i)"
by (auto simp add:cancels_to_1_at_def)
let ?x = "length l - i - 2"
from `Suc i < length (rev l)`
have "Suc ?x < length l" by auto
moreover
from `Suc i < length (rev l)`
have "i < length l" and "length l - Suc i = Suc(length l - Suc (Suc i))" by auto
hence "rev l ! i = l ! Suc ?x" and "rev l ! Suc i = l ! ?x"
by (auto simp add: rev_nth map_nth)
with `canceling (rev l ! i) (rev l ! Suc i)`
have "canceling (l ! Suc ?x) (l ! ?x)" by auto
hence "canceling (l ! ?x) (l ! Suc ?x)" by (rule cancel_sym)
hence "canceling (l ! ?x) (l ! Suc ?x)" by simp
ultimately
have "cancels_to_1_at ?x l (cancel_at ?x l)"
by (auto simp add:cancels_to_1_at_def)
hence "cancels_to_1 l (cancel_at ?x l)"
by (auto simp add:cancels_to_1_def)
hence "\<not>canceled l"
by (auto simp add:canceled_def)
with `canceled l` show False by contradiction
qed
lemma inv_fg_closure1:
assumes "canceled l"
shows "canceled (inv_fg l)"
unfolding inv_fg_def and inv1_def and apfst_def
proof-
have "inj Not" by (auto intro:injI)
moreover
have "inj_on id (snd ` set l)" by auto
ultimately
have "canceled (map (map_prod Not id) l)"
using `canceled l`
by -(rule rename_gens_canceled)
thus "canceled (rev (map (map_prod Not id) l))" by (rule canceled_rev)
qed
subsection {* The definition *}
text {*
Finally, we can define the Free Group over a set of generators, and show that it
is indeed a group.
*}
definition free_group :: "'a set => ((bool * 'a) list) monoid" ("\<F>\<index>")
where
"\<F>\<^bsub>gens\<^esub> \<equiv> \<lparr>
carrier = {l\<in>lists (UNIV \<times> gens). canceled l },
mult = \<lambda> x y. normalize (x @ y),
one = []
\<rparr>"
lemma occuring_gens_in_element:
"x \<in> carrier \<F>\<^bsub>gens\<^esub> \<Longrightarrow> x \<in> lists (UNIV \<times> gens)"
by(auto simp add:free_group_def)
theorem free_group_is_group: "group \<F>\<^bsub>gens\<^esub>"
proof
fix x y
assume "x \<in> carrier \<F>\<^bsub>gens\<^esub>" hence x: "x \<in> lists (UNIV \<times> gens)" by
(rule occuring_gens_in_element)
assume "y \<in> carrier \<F>\<^bsub>gens\<^esub>" hence y: "y \<in> lists (UNIV \<times> gens)" by
(rule occuring_gens_in_element)
from x and y
have "x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> y \<in> lists (UNIV \<times> gens)"
by (auto intro!: normalize_preserves_generators simp add:free_group_def append_in_lists_conv)
thus "x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> y \<in> carrier \<F>\<^bsub>gens\<^esub>"
by (auto simp add:free_group_def)
next
fix x y z
have "cancels_to (x @ y) (normalize (x @ (y::'a word_g_i)))"
and "cancels_to z (z::'a word_g_i)"
by auto
hence "normalize (normalize (x @ y) @ z) = normalize ((x @ y) @ z)"
by (rule normalize_append_cancel_to[THEN sym])
also
have "\<dots> = normalize (x @ (y @ z))" by auto
also
have "cancels_to (y @ z) (normalize (y @ (z::'a word_g_i)))"
and "cancels_to x (x::'a word_g_i)"
by auto
hence "normalize (x @ (y @ z)) = normalize (x @ normalize (y @ z))"
by -(rule normalize_append_cancel_to)
finally
show "x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> y \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> z =
x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> (y \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> z)"
by (auto simp add:free_group_def)
next
show "\<one>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> \<in> carrier \<F>\<^bsub>gens\<^esub>"
by (auto simp add:free_group_def)
next
fix x
assume "x \<in> carrier \<F>\<^bsub>gens\<^esub>"
thus "\<one>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> x = x"
by (auto simp add:free_group_def)
next
fix x
assume "x \<in> carrier \<F>\<^bsub>gens\<^esub>"
thus "x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> \<one>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> = x"
by (auto simp add:free_group_def)
next
show "carrier \<F>\<^bsub>gens\<^esub> \<subseteq> Units \<F>\<^bsub>gens\<^esub>"
proof (simp add:free_group_def Units_def, rule subsetI)
fix x :: "'a word_g_i"
let ?x' = "inv_fg x"
assume "x \<in> {y\<in>lists(UNIV\<times>gens). canceled y}"
hence "?x' \<in> lists(UNIV\<times>gens) \<and> canceled ?x'"
by (auto elim:inv_fg_closure1 simp add:inv_fg_closure2)
moreover
have "normalize (?x' @ x) = []"
and "normalize (x @ ?x') = []"
by (auto simp add:inv_fg_cancel inv_fg_cancel2)
ultimately
have "\<exists>y. y \<in> lists (UNIV \<times> gens) \<and>
canceled y \<and>
normalize (y @ x) = [] \<and> normalize (x @ y) = []"
by auto
with `x \<in> {y\<in>lists(UNIV\<times>gens). canceled y}`
show "x \<in> {y \<in> lists (UNIV \<times> gens). canceled y \<and>
(\<exists>x. x \<in> lists (UNIV \<times> gens) \<and>
canceled x \<and>
normalize (x @ y) = [] \<and> normalize (y @ x) = [])}"
by auto
qed
qed
lemma inv_is_inv_fg[simp]:
"x \<in> carrier \<F>\<^bsub>gens\<^esub> \<Longrightarrow> inv\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> x = inv_fg x"
by (rule group.inv_equality,auto simp add:free_group_is_group,auto simp add: free_group_def inv_fg_cancel inv_fg_cancel2 inv_fg_closure1 inv_fg_closure2)
subsection {* The universal property *}
text {* Free Groups are important due to their universal property: Every map of
the set of generators to another group can be extended uniquely to an
homomorphism from the Free Group. *}
definition insert ("\<iota>")
where "\<iota> g = [(False, g)]"
lemma insert_closed:
"g \<in> gens \<Longrightarrow> \<iota> g \<in> carrier \<F>\<^bsub>gens\<^esub>"
by (auto simp add:insert_def free_group_def)
definition (in group) lift_gi
where "lift_gi f gi = (if fst gi then inv (f (snd gi)) else f (snd gi))"
lemma (in group) lift_gi_closed:
assumes cl: "f \<in> gens \<rightarrow> carrier G"
and "snd gi \<in> gens"
shows "lift_gi f gi \<in> carrier G"
using assms by (auto simp add:lift_gi_def)
definition (in group) lift
where "lift f w = m_concat (map (lift_gi f) w)"
lemma (in group) lift_nil[simp]: "lift f [] = \<one>"
by (auto simp add:lift_def)
lemma (in group) lift_closed[simp]:
assumes cl: "f \<in> gens \<rightarrow> carrier G"
and "x \<in> lists (UNIV \<times> gens)"
shows "lift f x \<in> carrier G"
proof-
have "set (map (lift_gi f) x) \<subseteq> carrier G"
using `x \<in> lists (UNIV \<times> gens)`
by (auto simp add:lift_gi_closed[OF cl])
thus "lift f x \<in> carrier G"
by (auto simp add:lift_def)
qed
lemma (in group) lift_append[simp]:
assumes cl: "f \<in> gens \<rightarrow> carrier G"
and "x \<in> lists (UNIV \<times> gens)"
and "y \<in> lists (UNIV \<times> gens)"
shows "lift f (x @ y) = lift f x \<otimes> lift f y"
proof-
from `x \<in> lists (UNIV \<times> gens)`
have "set (map snd x) \<subseteq> gens" by auto
hence "set (map (lift_gi f) x) \<subseteq> carrier G"
by (induct x)(auto simp add:lift_gi_closed[OF cl])
moreover
from `y \<in> lists (UNIV \<times> gens)`
have "set (map snd y) \<subseteq> gens" by auto
hence "set (map (lift_gi f) y) \<subseteq> carrier G"
by (induct y)(auto simp add:lift_gi_closed[OF cl])
ultimately
show "lift f (x @ y) = lift f x \<otimes> lift f y"
by (auto simp add:lift_def m_assoc simp del:set_map foldr_append)
qed
lemma (in group) lift_cancels_to:
assumes "cancels_to x y"
and "x \<in> lists (UNIV \<times> gens)"
and cl: "f \<in> gens \<rightarrow> carrier G"
shows "lift f x = lift f y"
using assms
unfolding cancels_to_def
proof(induct rule:rtranclp_induct)
case (step y z)
from `cancels_to_1\<^sup>*\<^sup>* x y`
and `x \<in> lists (UNIV \<times> gens)`
have "y \<in> lists (UNIV \<times> gens)"
by -(rule cancels_to_preserves_generators, simp add:cancels_to_def)
hence "lift f x = lift f y"
using step by auto
also
from `cancels_to_1 y z`
obtain ys1 y1 y2 ys2
where y: "y = ys1 @ y1 # y2 # ys2"
and "z = ys1 @ ys2"
and "canceling y1 y2"
by (rule cancels_to_1_unfold)
have "lift f y = lift f (ys1 @ [y1] @ [y2] @ ys2)"
using y by simp
also
from y and cl and `y \<in> lists (UNIV \<times> gens)`
have "lift f (ys1 @ [y1] @ [y2] @ ys2)
= lift f ys1 \<otimes> (lift f [y1] \<otimes> lift f [y2]) \<otimes> lift f ys2"
by (auto intro:lift_append[OF cl] simp del: append_Cons simp add:m_assoc iff:lists_eq_set)
also
from cl[THEN funcset_image]
and y and `y \<in> lists (UNIV \<times> gens)`
and `canceling y1 y2`
have "(lift f [y1] \<otimes> lift f [y2]) = \<one>"
by (auto simp add:lift_def lift_gi_def canceling_def iff:lists_eq_set)
hence "lift f ys1 \<otimes> (lift f [y1] \<otimes> lift f [y2]) \<otimes> lift f ys2
= lift f ys1 \<otimes> \<one> \<otimes> lift f ys2"
by simp
also
from y and `y \<in> lists (UNIV \<times> gens)`
and cl
have "lift f ys1 \<otimes> \<one> \<otimes> lift f ys2 = lift f (ys1 @ ys2)"
by (auto intro:lift_append iff:lists_eq_set)
also
from `z = ys1 @ ys2`
have "lift f (ys1 @ ys2) = lift f z" by simp
finally show "lift f x = lift f z" .
qed auto
lemma (in group) lift_is_hom:
assumes cl: "f \<in> gens \<rightarrow> carrier G"
shows "lift f \<in> hom \<F>\<^bsub>gens\<^esub> G"
proof-
{
fix x
assume "x \<in> carrier \<F>\<^bsub>gens\<^esub>"
hence "x \<in> lists (UNIV \<times> gens)"
unfolding free_group_def by simp
hence "lift f x \<in> carrier G"
by (induct x, auto simp add:lift_def lift_gi_closed[OF cl])
}
moreover
{ fix x
assume "x \<in> carrier \<F>\<^bsub>gens\<^esub>"
fix y
assume "y \<in> carrier \<F>\<^bsub>gens\<^esub>"
from `x \<in> carrier \<F>\<^bsub>gens\<^esub>` and `y \<in> carrier \<F>\<^bsub>gens\<^esub>`
have "x \<in> lists (UNIV \<times> gens)" and "y \<in> lists (UNIV \<times> gens)"
by (auto simp add:free_group_def)
have "cancels_to (x @ y) (normalize (x @ y))" by simp
from `x \<in> lists (UNIV \<times> gens)` and `y \<in> lists (UNIV \<times> gens)`
and lift_cancels_to[THEN sym, OF `cancels_to (x @ y) (normalize (x @ y))`] and cl
have "lift f (x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> y) = lift f (x @ y)"
by (auto simp add:free_group_def iff:lists_eq_set)
also
from `x \<in> lists (UNIV \<times> gens)` and `y \<in> lists (UNIV \<times> gens)` and cl
have "lift f (x @ y) = lift f x \<otimes> lift f y"
by simp
finally
have "lift f (x \<otimes>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> y) = lift f x \<otimes> lift f y" .
}
ultimately
show "lift f \<in> hom \<F>\<^bsub>gens\<^esub> G"
by auto
qed
lemma gens_span_free_group:
shows "\<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> = carrier \<F>\<^bsub>gens\<^esub>"
proof
interpret group "\<F>\<^bsub>gens\<^esub>" by (rule free_group_is_group)
show "\<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> \<subseteq> carrier \<F>\<^bsub>gens\<^esub>"
by(rule gen_span_closed, auto simp add:insert_def free_group_def)
show "carrier \<F>\<^bsub>gens\<^esub> \<subseteq> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
proof
fix x
show "x \<in> carrier \<F>\<^bsub>gens\<^esub> \<Longrightarrow> x \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
proof(induct x)
case Nil
have "one \<F>\<^bsub>gens\<^esub> \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by simp
thus "[] \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by (simp add:free_group_def)
next
case (Cons a x)
from `a # x \<in> carrier \<F>\<^bsub>gens\<^esub>`
have "x \<in> carrier \<F>\<^bsub>gens\<^esub>"
by (auto intro:cons_canceled simp add:free_group_def)
hence "x \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
using Cons by simp
moreover
from `a # x \<in> carrier \<F>\<^bsub>gens\<^esub>`
have "snd a \<in> gens"
by (auto simp add:free_group_def)
hence isa: "\<iota> (snd a) \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by (auto simp add:insert_def intro:gen_gens)
have "[a] \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
proof(cases "fst a")
case False
hence "[a] = \<iota> (snd a)" by (cases a, auto simp add:insert_def)
with isa show "[a] \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>" by simp
next
case True
from `snd a \<in> gens`
have "\<iota> (snd a) \<in> carrier \<F>\<^bsub>gens\<^esub>"
by (auto simp add:free_group_def insert_def)
with True
have "[a] = inv\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> (\<iota> (snd a))"
by (cases a, auto simp add:insert_def inv_fg_def inv1_def)
moreover
from isa
have "inv\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub> (\<iota> (snd a)) \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by (auto intro:gen_inv)
ultimately
show "[a] \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by simp
qed
ultimately
have "mult \<F>\<^bsub>gens\<^esub> [a] x \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>"
by (auto intro:gen_mult)
with
`a # x \<in> carrier \<F>\<^bsub>gens\<^esub>`
show "a # x \<in> \<langle>\<iota> ` gens\<rangle>\<^bsub>\<F>\<^bsub>gens\<^esub>\<^esub>" by (simp add:free_group_def)
qed
qed
qed
lemma (in group) lift_is_unique:
assumes "group G"
and cl: "f \<in> gens \<rightarrow> carrier G"
and "h \<in> hom \<F>\<^bsub>gens\<^esub> G"
and "\<forall> g \<in> gens. h (\<iota> g) = f g"
shows "\<forall>x \<in> carrier \<F>\<^bsub>gens\<^esub>. h x = lift f x"
unfolding gens_span_free_group[THEN sym]
proof(rule hom_unique_on_span[of "\<F>\<^bsub>gens\<^esub>" G])
show "group \<F>\<^bsub>gens\<^esub>" by (rule free_group_is_group)
next
show "group G" by fact
next
show "\<iota> ` gens \<subseteq> carrier \<F>\<^bsub>gens\<^esub>"
by(auto intro:insert_closed)
next
show "h \<in> hom \<F>\<^bsub>gens\<^esub> G" by fact
next
show "lift f \<in> hom \<F>\<^bsub>gens\<^esub> G" by (rule lift_is_hom[OF cl])
next
from `\<forall>g\<in> gens. h (\<iota> g) = f g` and cl[THEN funcset_image]
show "\<forall>g\<in> \<iota> ` gens. h g = lift f g"
by(auto simp add:insert_def lift_def lift_gi_def)
qed
end
|
Polish culture during World War II was suppressed by the occupying powers of Nazi Germany and the Soviet Union , both of whom were hostile to Poland 's people and cultural heritage . Policies aimed at cultural genocide resulted in the deaths of thousands of scholars and artists , and the theft and destruction of innumerable cultural artifacts . The " maltreatment of the Poles was one of many ways in which the Nazi and Soviet regimes had grown to resemble one another " , wrote British historian Niall Ferguson .
|
module Language.LSP.Metavars
import Core.Context
import Core.Core
import Core.Directory
import Core.Env
import Core.TT
import Core.Name
import Idris.IDEMode.Holes
import Idris.Pretty
import Idris.Pretty.Render
import Idris.REPL.Opts
import Idris.Resugar
import Idris.Syntax
import Language.JSON
import Language.LSP.Message
import Language.LSP.Definition
import Server.Configuration
import Server.Log
import Server.Utils
import System.File
import System.Path
import Language.Reflection
import Libraries.Text.PrettyPrint.Prettyprinter.Symbols
%language ElabReflection
%hide Language.Reflection.TT.FC
%hide Language.Reflection.TT.Name
-- Non-exported functions are temporary changes to functions in the module Idris.IDEMode.Holes.
-- TODO: upstream changes to the compiler when stability is reached.
public export
record Premise where
constructor MkPremise
name : String
location : Maybe Location
type : String
multiplicity : String
isImplicit : Bool
%runElab deriveJSON defaultOpts `{Metavars.Premise}
public export
record Metavar where
constructor MkMetavar
name : String
location : Maybe Location
type : String
premises : List Metavars.Premise
%runElab deriveJSON defaultOpts `{Metavars.Metavar}
showName : Name -> Bool
showName (UN Underscore) = False
showName (MN _ _) = False
showName _ = True
getUserHolesData : Ref Ctxt Defs
=> Ref Syn SyntaxInfo
=> Core (List (Holes.Data, FC))
getUserHolesData = do
defs <- get Ctxt
ms <- getUserHoles
globs <- concat <$> traverse (flip lookupCtxtName defs.gamma) ms
let holesWithArgs = mapMaybe (\(n, i, gdef) => pure (n, gdef, !(isHole gdef))) globs
traverse (\(n, gdef, args) => (, gdef.location) <$> holeData defs [] n args gdef.type) holesWithArgs
||| Returns the list of metavariables visible in the current context with their location.
||| JSON schema for a single metavariable:
||| {
||| location: Location | null;
||| name: string;
||| type: string;
||| premises: Premise[]
||| }
||| JSON schema for a single premise:
||| {
||| location: Location | null;
||| name: string;
||| type: string;
||| multiplicity: string;
||| isImplicit: bool;
||| }
export
metavarsCmd : Ref Ctxt Defs
=> Ref Syn SyntaxInfo
=> Ref ROpts REPLOpts
=> Ref LSPConf LSPConfiguration
=> Core (List Metavar)
metavarsCmd = do
logI Metavars "Fetching metavars"
c <- getColor
setColor False
holes <- Metavars.getUserHolesData
logI Metavars "Metavars fetched, found \{show $ length holes}"
res <- for holes $ \(h, fc) => do
loc <- mkLocation fc
let name = show h.name
type <- render (reAnnotate Syntax $ prettyTerm h.type)
premises <- for h.context $ \p => do
loc <- mkLocation replFC
let name = show p.name
type <- render (reAnnotate Syntax $ prettyTerm p.type)
pure $ MkPremise { location = loc, name = name, type = type, isImplicit = p.isImplicit, multiplicity = show p.multiplicity }
pure $ MkMetavar { location = loc, name = name, type = type, premises = premises }
setColor c
pure res
|
/-
Copyright (c) 2021 Yourong Zang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yourong Zang
-/
import analysis.complex.isometry
import analysis.normed_space.conformal_linear_map
/-!
# Conformal maps between complex vector spaces
We prove the sufficient and necessary conditions for a real-linear map between complex vector spaces
to be conformal.
## Main results
* `is_conformal_map_complex_linear`: a nonzero complex linear map into an arbitrary complex
normed space is conformal.
* `is_conformal_map_complex_linear_conj`: the composition of a nonzero complex linear map with
`conj` is complex linear.
* `is_conformal_map_iff_is_complex_or_conj_linear`: a real linear map between the complex
plane is conformal iff it's complex
linear or the composition of
some complex linear map and `conj`.
## Warning
Antiholomorphic functions such as the complex conjugate are considered as conformal functions in
this file.
-/
noncomputable theory
open complex continuous_linear_map
open_locale complex_conjugate
lemma is_conformal_map_conj : is_conformal_map (conj_lie : ℂ →L[ℝ] ℂ) :=
conj_lie.to_linear_isometry.is_conformal_map
section conformal_into_complex_normed
variables {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space ℂ E]
{z : ℂ} {g : ℂ →L[ℝ] E} {f : ℂ → E}
lemma is_conformal_map_complex_linear {map : ℂ →L[ℂ] E} (nonzero : map ≠ 0) :
is_conformal_map (map.restrict_scalars ℝ) :=
begin
have minor₁ : ∥map 1∥ ≠ 0,
{ simpa [ext_ring_iff] using nonzero },
refine ⟨∥map 1∥, minor₁, ⟨∥map 1∥⁻¹ • map, _⟩, _⟩,
{ intros x,
simp only [linear_map.smul_apply],
have : x = x • 1 := by rw [smul_eq_mul, mul_one],
nth_rewrite 0 [this],
rw [_root_.coe_coe map, linear_map.coe_coe_is_scalar_tower],
simp only [map.coe_coe, map.map_smul, norm_smul, norm_inv, norm_norm],
field_simp [minor₁], },
{ ext1,
simp [minor₁] },
end
lemma is_conformal_map_complex_linear_conj
{map : ℂ →L[ℂ] E} (nonzero : map ≠ 0) :
is_conformal_map ((map.restrict_scalars ℝ).comp (conj_cle : ℂ →L[ℝ] ℂ)) :=
(is_conformal_map_complex_linear nonzero).comp is_conformal_map_conj
end conformal_into_complex_normed
section conformal_into_complex_plane
open continuous_linear_map
variables {f : ℂ → ℂ} {z : ℂ} {g : ℂ →L[ℝ] ℂ}
lemma is_conformal_map.is_complex_or_conj_linear (h : is_conformal_map g) :
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g ∘L ↑conj_cle) :=
begin
rcases h with ⟨c, hc, li, rfl⟩,
obtain ⟨li, rfl⟩ : ∃ li' : ℂ ≃ₗᵢ[ℝ] ℂ, li'.to_linear_isometry = li,
from ⟨li.to_linear_isometry_equiv rfl, by { ext1, refl }⟩,
rcases linear_isometry_complex li with ⟨a, rfl|rfl⟩,
-- let rot := c • (a : ℂ) • continuous_linear_map.id ℂ ℂ,
{ refine or.inl ⟨c • (a : ℂ) • continuous_linear_map.id ℂ ℂ, _⟩,
ext1,
simp only [coe_restrict_scalars', smul_apply, linear_isometry.coe_to_continuous_linear_map,
linear_isometry_equiv.coe_to_linear_isometry, rotation_apply, id_apply, smul_eq_mul] },
{ refine or.inr ⟨c • (a : ℂ) • continuous_linear_map.id ℂ ℂ, _⟩,
ext1,
simp only [coe_restrict_scalars', smul_apply, linear_isometry.coe_to_continuous_linear_map,
linear_isometry_equiv.coe_to_linear_isometry, rotation_apply, id_apply, smul_eq_mul,
comp_apply, linear_isometry_equiv.trans_apply, continuous_linear_equiv.coe_coe,
conj_cle_apply, conj_lie_apply, conj_conj] },
end
/-- A real continuous linear map on the complex plane is conformal if and only if the map or its
conjugate is complex linear, and the map is nonvanishing. -/
lemma is_conformal_map_iff_is_complex_or_conj_linear:
is_conformal_map g ↔
((∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨
(∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g ∘L ↑conj_cle)) ∧ g ≠ 0 :=
begin
split,
{ exact λ h, ⟨h.is_complex_or_conj_linear, h.ne_zero⟩, },
{ rintros ⟨⟨map, rfl⟩ | ⟨map, hmap⟩, h₂⟩,
{ refine is_conformal_map_complex_linear _,
contrapose! h₂ with w,
simp [w] },
{ have minor₁ : g = (map.restrict_scalars ℝ) ∘L ↑conj_cle,
{ ext1,
simp [hmap] },
rw minor₁ at ⊢ h₂,
refine is_conformal_map_complex_linear_conj _,
contrapose! h₂ with w,
simp [w] } }
end
end conformal_into_complex_plane
|
import Data.Either
import Data.List
import Data.List1
import Data.Maybe
import Data.String
import System.File
data BingoNum = M Nat | U Nat
Show BingoNum where
show (M k) = "m " ++ show k
show (U k) = "u " ++ show k
Card : Type
Card = List (List BingoNum)
parseLines : (String -> Maybe a) -> String -> List a
parseLines f s = catMaybes $ f <$> lines s
getNumbers : List String -> Maybe (List Nat, List String)
getNumbers [] = Nothing
getNumbers (x :: xs) = Just (catMaybes $ parsePositive <$> (forget $ split (== ',') x), xs)
parseCard : List String -> Card
parseCard l = (\s => U <$> (catMaybes $ parsePositive <$> (forget $ split (== ' ') s))) <$> l
parseCards : List String -> List Card
parseCards [] = []
parseCards (_ :: xs) = parseCard (take 5 xs) :: parseCards (drop 5 xs)
isMarked : BingoNum -> Bool
isMarked (M _) = True
isMarked (U _) = False
winRow : Card -> Bool
winRow [] = False
winRow (x :: xs) = all isMarked x || winRow xs
winColumn : Card -> Bool
winColumn c = any id $ foldl (\a => \bs => (\(b1, b2) => b1 && b2) <$> zip a (isMarked <$> bs)) (replicate 5 True) c
wins : Card -> Bool
wins c = winRow c || winColumn c
drawNumber : Nat -> Card -> Card
drawNumber n [] = []
drawNumber n (x :: xs) = ((\d => case d of
M m => M m
U u => if u == n
then M u
else U u) <$> x) :: drawNumber n xs
drawNumbers : List Nat -> List Card -> Maybe (Card, Nat)
drawNumbers [] cs = Nothing
drawNumbers (x :: xs) [] = Nothing
drawNumbers (x :: xs) (c :: []) = let nc = drawNumber x c in
if wins nc
then Just (nc, x)
else drawNumbers xs (nc :: [])
drawNumbers (x :: xs) cs = let ncs = drawNumber x <$> cs
losing = filter (not . wins) ncs in
drawNumbers xs losing
scoreOf : Card -> Nat
scoreOf [] = 0
scoreOf (x :: xs) = (foldl (\a => \b => case b of
M n => a
U n => n + a) 0 x) + scoreOf xs
run : String -> IO ()
run s = do let lines = lines s
Just (ns, lines) <- pure $ getNumbers lines
| Nothing => putStrLn $ "err"
let cards = parseCards lines
Just (win, n) <- pure $ drawNumbers ns cards
| Nothing => putStrLn $ "no win"
let score = n * scoreOf win
putStrLn $ show $ score
main : IO ()
main = do Right s <- readFile "input.txt"
| Left err => putStrLn $ show err
run s
|
*Board Designated allows the Foundation to identify and support a few efforts each year that do not fall within the Synergy Initiative or Activation Fund guidelines but complement the grant portfolio and mission. Organizations cannot apply for Board Designated grants.
Click on the following images to see the impact of our grantmaking. |
If you have received a building violation and are required to attend a hearing at the ECB, be advised that a proper defense should be created by a licensed attorney. We have several that we can recommend. In addition to this, you must comply with what the building violation states. There are many types of building violations. Below is a table of the many types of violations, and what you must do to cure the violations, so that you don’t receive second and third offenses, as the fines tend to go up drastically.
If you have received a violation, and do not see it above, please contact us for guidance. |
Lactarius indigo , commonly known as the indigo milk cap , the indigo ( or blue ) lactarius , or the blue milk mushroom , is a species of agaric fungus in the family Russulaceae . A widely distributed species , it grows naturally in eastern North America , East Asia , and Central America ; it has also been reported in southern France . L. indigo grows on the ground in both deciduous and coniferous forests , where it forms mycorrhizal associations with a broad range of trees . The fruit body color ranges from dark blue in fresh specimens to pale blue @-@ gray in older ones . The milk , or latex , that oozes when the mushroom tissue is cut or broken — a feature common to all members of the Lactarius genus — is also indigo blue , but slowly turns green upon exposure to air . The cap has a diameter of 5 to 15 cm ( 2 to 6 in ) , and the stem is 2 to 8 cm ( 0 @.@ 8 to 3 in ) tall and 1 to 2 @.@ 5 cm ( 0 @.@ 4 to 1 @.@ 0 in ) thick . It is an edible mushroom , and is sold in rural markets in China , Guatemala , and Mexico .
|
Require Import init.
Require Export category_functor.
Class NatTransformation `{C1 : Category, C2 : Category}
`(F : @Functor C1 C2, G : @Functor C1 C2) :=
{
nat_trans_f : ∀ A,
cat_morphism C2 (F A) (G A);
nat_trans_commute : ∀ {A B} (f : cat_morphism C1 A B),
nat_trans_f B ∘ (⌈F⌉ f) = (⌈G⌉ f) ∘ nat_trans_f A;
}.
Arguments nat_trans_f {C1 C2 F G} NatTransformation.
Arguments nat_trans_commute {C1 C2 F G} NatTransformation {A B}.
Coercion nat_trans_f : NatTransformation >-> Funclass.
(** So nat_trans_commute says:
[(α B) ∘ (⌈F⌉ f) = (⌈G⌉ f) ∘ (α A)]
*)
(* begin show *)
Local Program Instance id_nat_transformation `{C1 : Category, C2 : Category}
`(F : @Functor C1 C2) : NatTransformation F F :=
{
nat_trans_f A := 𝟙
}.
(* end show *)
Next Obligation.
rewrite cat_lid.
rewrite cat_rid.
reflexivity.
Qed.
Notation "'𝕀'" := (id_nat_transformation _).
(* begin show *)
Local Program Instance vcompose_nat_transformation `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2, H : @Functor C1 C2}
`(α : @NatTransformation C1 C2 G H, β : @NatTransformation C1 C2 F G)
: NatTransformation F H :=
{
nat_trans_f A := α A ∘ β A
}.
(* end show *)
Next Obligation.
rewrite cat_assoc.
rewrite <- cat_assoc.
rewrite nat_trans_commute.
rewrite cat_assoc.
rewrite nat_trans_commute.
reflexivity.
Qed.
(* begin show *)
Local Program Instance hcompose_nat_transformation
`{C1 : Category, C2 : Category, C3 : Category}
`{F' : @Functor C2 C3, G' : @Functor C2 C3}
`{F : @Functor C1 C2, G : @Functor C1 C2}
`(β : @NatTransformation C2 C3 F' G', α : @NatTransformation C1 C2 F G)
: NatTransformation (F' ○ F) (G' ○ G) :=
{
nat_trans_f A := β (G A) ∘ (⌈F'⌉ (α A))
}.
(* end show *)
Next Obligation.
rewrite nat_trans_commute.
rewrite <- cat_assoc.
rewrite nat_trans_commute.
rewrite cat_assoc.
rewrite <- functor_compose.
rewrite nat_trans_commute.
rewrite functor_compose.
rewrite <- cat_assoc.
rewrite nat_trans_commute.
reflexivity.
Qed.
Notation "α □ β" := (vcompose_nat_transformation α β) (at level 20, left associativity).
Notation "α ⊡ β" := (hcompose_nat_transformation α β) (at level 20, left associativity).
Global Remove Hints id_nat_transformation vcompose_nat_transformation hcompose_nat_transformation : typeclass_instances.
Theorem nat_trans_compose_eq `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2, H : @Functor C1 C2} :
∀ (α : NatTransformation G H) (β : NatTransformation F G),
∀ A, (α □ β) A = α A ∘ β A.
Proof.
intros α β A.
cbn.
reflexivity.
Qed.
Theorem nat_trans_eq `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2} :
∀ (α β : NatTransformation F G), (∀ A, α A = β A) → α = β.
Proof.
intros [f1 commute1] [f2 commute2] H.
cbn in *.
assert (f1 = f2) as eq.
{
apply functional_ext.
exact H.
}
subst f2; clear H.
rewrite (proof_irrelevance commute2 commute1).
reflexivity.
Qed.
Theorem nat_trans_interchange `{C1 : Category, C2 : Category, C3 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2, H : @Functor C1 C2}
`{F' : @Functor C2 C3, G' : @Functor C2 C3, H' : @Functor C2 C3} :
∀ (α : NatTransformation F G ) (β : NatTransformation G H)
(α' : NatTransformation F' G') (β' : NatTransformation G' H'),
(β' □ α') ⊡ (β □ α) = (β' ⊡ β) □ (α' ⊡ α).
Proof.
intros α β α' β'.
apply nat_trans_eq.
intros A.
cbn.
do 2 rewrite <- cat_assoc.
apply lcompose.
rewrite functor_compose.
do 2 rewrite cat_assoc.
apply rcompose.
apply nat_trans_commute.
Qed.
Theorem nat_trans_id_interchange `{C1 : Category, C2 : Category, C3 : Category}
`{F : @Functor C2 C3, G : @Functor C1 C2} :
(id_nat_transformation F) ⊡ (id_nat_transformation G) =
id_nat_transformation (F ○ G).
Proof.
apply nat_trans_eq.
intros A.
cbn.
rewrite cat_lid.
apply functor_id.
Qed.
Theorem nat_trans_lid `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2} :
∀ (α : NatTransformation F G), 𝕀 □ α = α.
Proof.
intros α.
apply nat_trans_eq.
intros A.
cbn.
apply cat_lid.
Qed.
Theorem nat_trans_rid `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2} :
∀ (α : NatTransformation F G), α □ 𝕀 = α.
Proof.
intros α.
apply nat_trans_eq.
intros A.
cbn.
apply cat_rid.
Qed.
Theorem nat_trans_assoc `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2,
H : @Functor C1 C2, I : @Functor C1 C2} :
∀ (α : NatTransformation H I)
(β : NatTransformation G H)
(γ : NatTransformation F G),
α □ (β □ γ) = (α □ β) □ γ.
Proof.
intros α β γ.
apply nat_trans_eq.
intros A.
cbn.
apply cat_assoc.
Qed.
(* begin show *)
Local Program Instance FUNCTOR `(C1 : Category, C2 : Category) : Category := {
cat_U := Functor C1 C2;
cat_morphism F G := NatTransformation F G;
cat_compose {A B C} α β := α □ β;
cat_id F := id_nat_transformation F;
}.
(* end show *)
Next Obligation.
apply nat_trans_assoc.
Qed.
Next Obligation.
apply nat_trans_lid.
Qed.
Next Obligation.
apply nat_trans_rid.
Qed.
Global Remove Hints FUNCTOR : typeclass_instances.
Definition nat_isomorphism `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2} `(α : @NatTransformation C1 C2 F G)
:= isomorphism (C0 := FUNCTOR C1 C2) α.
Theorem nat_isomorphism_A `{C1 : Category, C2 : Category}
`{F : @Functor C1 C2, G : @Functor C1 C2} : ∀ α : NatTransformation F G,
nat_isomorphism α ↔ (∀ A, isomorphism (α A)).
Proof.
intros α.
split.
- intros α_iso A.
destruct α_iso as [β [β_eq1 β_eq2]].
cbn in *.
exists (β A).
do 2 rewrite <- nat_trans_compose_eq.
rewrite β_eq1, β_eq2.
cbn.
split; reflexivity.
- intros all_iso.
pose (β_f A := ex_val (all_iso A)).
assert (∀ {A B} (f : cat_morphism C1 A B),
β_f B ∘ (⌈G⌉ f) = (⌈F⌉ f) ∘ β_f A) as β_commute.
{
intros A B f.
unfold β_f.
rewrite_ex_val A' [A'_eq1 A'_eq2].
rewrite_ex_val B' [B'_eq1 B'_eq2].
apply rcompose with (⌈F⌉ f) in A'_eq2.
rewrite cat_lid in A'_eq2.
rewrite <- cat_assoc in A'_eq2.
rewrite nat_trans_commute in A'_eq2.
apply rcompose with B' in A'_eq2.
do 2 rewrite <- cat_assoc in A'_eq2.
rewrite B'_eq1 in A'_eq2.
rewrite cat_rid in A'_eq2.
exact A'_eq2.
}
pose (β := {|nat_trans_commute := β_commute|}).
exists β.
cbn.
split.
+ apply nat_trans_eq.
intros A.
cbn.
unfold β_f.
rewrite_ex_val B [B_eq1 B_eq2].
exact B_eq1.
+ apply nat_trans_eq.
intros A.
cbn.
unfold β_f.
rewrite_ex_val B [B_eq1 B_eq2].
exact B_eq2.
Qed.
Definition nat_isomorphic `{C1 : Category, C2 : Category}
`(F : @Functor C1 C2, G : @Functor C1 C2)
:= isomorphic (C0 := FUNCTOR C1 C2) F G.
Theorem nat_isomorphic_wd `{C1 : Category, C2 : Category, C3 : Category} :
∀ (F G : Functor C2 C3) (H I : Functor C1 C2),
nat_isomorphic F G → nat_isomorphic H I →
nat_isomorphic (F ○ H) (G ○ I).
Proof.
intros F G H I [α [α' [α_eq1 α_eq2]]] [β [β' [β_eq1 β_eq2]]].
cbn in *.
exists (α ⊡ β).
exists (α' ⊡ β').
cbn.
split.
- rewrite <- nat_trans_interchange.
rewrite α_eq1, β_eq1.
apply nat_trans_id_interchange.
- rewrite <- nat_trans_interchange.
rewrite α_eq2, β_eq2.
apply nat_trans_id_interchange.
Qed.
Theorem lnat_iso `{C1 : Category, C2 : Category, C3 : Category} :
∀ {F G : Functor C1 C2} (H : Functor C2 C3),
isomorphic (C0 := FUNCTOR C1 C2) F G →
isomorphic (C0 := FUNCTOR C1 C3) (H ○ F) (H ○ G).
Proof.
intros F G H eq.
pose proof (isomorphic_refl (C0:= FUNCTOR C2 C3) H) as eq2.
exact (nat_isomorphic_wd _ _ _ _ eq2 eq).
Qed.
Theorem rnat_iso `{C1 : Category, C2 : Category, C3 : Category} :
∀ {F G : Functor C2 C3} (H : Functor C1 C2),
isomorphic (C0 := FUNCTOR C2 C3) F G →
isomorphic (C0 := FUNCTOR C1 C3) (F ○ H) (G ○ H).
Proof.
intros F G H eq.
pose proof (isomorphic_refl (C0:= FUNCTOR C1 C2) H) as eq2.
exact (nat_isomorphic_wd _ _ _ _ eq eq2).
Qed.
|
module _ where
open import Prelude
open import Numeric.Nat.Prime
2^44+7 2^46+15 2^48+21 : Nat
2^44+7 = 17592186044423
2^46+15 = 70368744177679
2^48+21 = 281474976710677
main : IO ⊤
main = print $ isPrime! 2^48+21
|
# A simple example script to install the packages provided by the command line arguments
install.packages(commandArgs(trailingOnly = TRUE), repos = "https://cran.rstudio.com")
|
Require Import Classical Peano_dec Setoid PeanoNat.
From hahn Require Import Hahn.
Require Import Omega.
Require Import Events.
Require Import Execution.
Require Import imm_s.
Require Import TraversalConfig.
Require Import Traversal.
Require Import SimTraversal.
Require Import SimTraversalProperties.
Set Implicit Arguments.
Remove Hints plus_n_O.
Definition countP (f: actid -> Prop) l :=
length (filterP f l).
Add Parametric Morphism : countP with signature
set_subset ==> eq ==> le as countP_mori.
Proof using.
ins. unfold countP.
induction y0.
{ simpls. }
ins. desf; simpls.
1,3: omega.
exfalso. apply n. by apply H.
Qed.
Add Parametric Morphism : countP with signature
set_equiv ==> eq ==> eq as countP_more.
Proof using.
ins. unfold countP.
erewrite filterP_set_equiv; eauto.
Qed.
Section TraversalCounting.
Variable G : execution.
Variable sc : relation actid.
Variable WF : Wf G.
Notation "'E'" := G.(acts_set).
Notation "'lab'" := G.(lab).
Notation "'W'" := (fun x => is_true (is_w lab x)).
Notation "'Rel'" := (fun x => is_true (is_rel lab x)).
Notation "'rmw'" := G.(rmw).
Definition trav_steps_left (T : trav_config) :=
countP (set_compl (covered T)) G.(acts) +
countP (W ∩₁ set_compl (issued T)) G.(acts).
Lemma trav_steps_left_decrease (T T' : trav_config)
(STEP : trav_step G sc T T') :
trav_steps_left T > trav_steps_left T'.
Proof using.
red in STEP. desc. red in STEP.
desf.
{ unfold trav_steps_left.
rewrite ISSEQ.
assert (countP (set_compl (covered T)) (acts G) >
countP (set_compl (covered T')) (acts G)) as HH.
2: omega.
rewrite COVEQ.
unfold countP.
assert (List.In e (acts G)) as LL.
{ apply COV. }
induction (acts G).
{ done. }
destruct l as [|h l].
{ assert (a = e); subst.
{ inv LL. }
simpls. desf.
exfalso. apply s0. by right. }
destruct LL as [|H]; subst.
2: { apply IHl in H. clear IHl.
simpls. desf; simpls; try omega.
all: try by (exfalso; apply s0; left; apply NNPP).
by exfalso; apply s; left; apply NNPP. }
clear IHl.
assert (exists l', l' = h :: l) as [l' HH] by eauto.
rewrite <- HH. clear h l HH.
simpls. desf; simpls.
{ exfalso. apply s0. by right. }
assert (length (filterP (set_compl (covered T ∪₁ eq e)) l') <=
length (filterP (set_compl (covered T)) l')).
2: omega.
eapply countP_mori; auto.
basic_solver. }
unfold trav_steps_left.
rewrite COVEQ.
assert (countP (W ∩₁ set_compl (issued T )) (acts G) >
countP (W ∩₁ set_compl (issued T')) (acts G)) as HH.
2: omega.
rewrite ISSEQ.
unfold countP.
assert (List.In e (acts G)) as LL.
{ apply ISS. }
assert (W e) as WE.
{ apply ISS. }
induction (acts G).
{ done. }
destruct l as [|h l].
{ assert (a = e); subst.
{ inv LL. }
simpls. desf.
{ exfalso. apply s0. by right. }
all: by exfalso; apply n; split. }
destruct LL as [|H]; subst.
2: { apply IHl in H. clear IHl.
simpls. desf; simpls; try omega.
1-2: by exfalso; apply n; destruct s0 as [H1 H2];
split; auto; intros HH; apply H2; left.
all: by exfalso; apply n; destruct s as [H1 H2];
split; auto; intros HH; apply H2; left. }
clear IHl.
assert (exists l', l' = h :: l) as [l' HH] by eauto.
rewrite <- HH. clear h l HH.
simpls. desf; simpls.
{ exfalso. apply s0. by right. }
2: { exfalso. apply s. by right. }
2: { exfalso. apply n. by split. }
assert (length (filterP (W ∩₁ set_compl (issued T ∪₁ eq e)) l') <=
length (filterP (W ∩₁ set_compl (issued T)) l')).
2: omega.
eapply countP_mori; auto.
basic_solver.
Qed.
Lemma trav_steps_left_decrease_sim (T T' : trav_config)
(STEP : sim_trav_step G sc T T') :
trav_steps_left T > trav_steps_left T'.
Proof using.
red in STEP. desc.
destruct STEP.
1-4: by apply trav_steps_left_decrease; red; eauto.
{ eapply lt_trans.
all: apply trav_steps_left_decrease; red; eauto. }
{ eapply lt_trans.
all: apply trav_steps_left_decrease; red; eauto. }
eapply lt_trans.
eapply lt_trans.
all: apply trav_steps_left_decrease; red; eauto.
Qed.
Lemma trav_steps_left_null_cov (T : trav_config)
(NULL : trav_steps_left T = 0) :
E ⊆₁ covered T.
Proof using.
unfold trav_steps_left in *.
assert (countP (set_compl (covered T)) (acts G) = 0) as HH by omega.
clear NULL.
unfold countP in *.
apply length_zero_iff_nil in HH.
intros x EX.
destruct (classic (covered T x)) as [|NN]; auto.
exfalso.
assert (In x (filterP (set_compl (covered T)) (acts G))) as UU.
2: { rewrite HH in UU. inv UU. }
apply in_filterP_iff. by split.
Qed.
Lemma trav_steps_left_ncov_nnull (T : trav_config) e
(EE : E e) (NCOV : ~ covered T e):
trav_steps_left T <> 0.
Proof using.
destruct (classic (trav_steps_left T = 0)) as [EQ|NEQ]; auto.
exfalso. apply NCOV. apply trav_steps_left_null_cov; auto.
Qed.
Lemma trav_steps_left_nnull_ncov (T : trav_config) (TCCOH : tc_coherent G sc T)
(NNULL : trav_steps_left T > 0):
exists e, E e /\ ~ covered T e.
Proof using.
unfold trav_steps_left in *.
assert (countP (set_compl (covered T)) (acts G) > 0 \/
countP (W ∩₁ set_compl (issued T)) (acts G) > 0) as YY by omega.
assert (countP (set_compl (covered T)) (acts G) > 0) as HH.
{ destruct YY as [|YY]; auto.
assert (countP (set_compl (covered T)) (acts G) >=
countP (W ∩₁ set_compl (issued T)) (acts G)).
2: omega.
apply countP_mori; auto.
intros x [WX NN] COV.
apply NN. eapply w_covered_issued; eauto. by split. }
clear YY.
unfold countP in HH.
assert (exists h l, filterP (set_compl (covered T)) (acts G) = h :: l) as YY.
{ destruct (filterP (set_compl (covered T)) (acts G)); eauto.
inv HH. }
desc. exists h.
assert (In h (filterP (set_compl (covered T)) (acts G))) as GG.
{ rewrite YY. red. by left. }
apply in_filterP_iff in GG. simpls.
Qed.
Lemma trav_steps_left_decrease_sim_trans (T T' : trav_config)
(STEPS : (sim_trav_step G sc)⁺ T T') :
trav_steps_left T > trav_steps_left T'.
Proof using.
induction STEPS.
{ by apply trav_steps_left_decrease_sim. }
eapply lt_trans; eauto.
Qed.
Theorem nat_ind_lt (P : nat -> Prop)
(HPi : forall n, (forall m, m < n -> P m) -> P n) :
forall n, P n.
Proof using.
set (Q n := forall m, m <= n -> P m).
assert (forall n, Q n) as HH.
2: { ins. apply (HH n). omega. }
ins. induction n.
{ unfold Q. ins. inv H. apply HPi. ins. inv H0. }
unfold Q in *. ins.
apply le_lt_eq_dec in H.
destruct H as [Hl | Heq].
{ unfold lt in Hl. apply le_S_n in Hl. by apply IHn. }
rewrite Heq. apply HPi. ins.
apply le_S_n in H. by apply IHn.
Qed.
Lemma sim_traversal_helper T
(IMMCON : imm_consistent G sc)
(TCCOH : tc_coherent G sc T)
(RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)
(RMWCOV : forall r w (RMW : rmw r w), covered T r <-> covered T w) :
exists T', (sim_trav_step G sc)* T T' /\ (G.(acts_set) ⊆₁ covered T').
Proof using WF.
assert
(exists T' : trav_config, (sim_trav_step G sc)* T T' /\ trav_steps_left T' = 0).
2: { desc. eexists. splits; eauto. by apply trav_steps_left_null_cov. }
assert (exists n, n = trav_steps_left T) as [n NN] by eauto.
generalize dependent T. generalize dependent n.
set (P n :=
forall T,
tc_coherent G sc T ->
W ∩₁ Rel ∩₁ issued T ⊆₁ covered T ->
(forall r w, rmw r w -> covered T r <-> covered T w) ->
n = trav_steps_left T ->
exists T', (sim_trav_step G sc)* T T' /\ trav_steps_left T' = 0).
assert (forall n, P n) as YY.
2: by apply YY.
apply nat_ind_lt. unfold P.
ins.
destruct (classic (trav_steps_left T = 0)) as [EQ|NEQ].
{ eexists. splits; eauto. apply rt_refl. }
assert (trav_steps_left T > 0) as HH by omega.
eapply trav_steps_left_nnull_ncov in HH; auto.
desc. eapply exists_next in HH0; eauto. desc.
eapply exists_trav_step in HH1; eauto.
desc.
apply exists_sim_trav_step in HH1; eauto. desc.
clear T'. subst.
specialize (H (trav_steps_left T'')).
edestruct H as [T' [II OO]].
{ by apply trav_steps_left_decrease_sim. }
{ eapply sim_trav_step_coherence; eauto. }
{ eapply sim_trav_step_rel_covered; eauto. }
{ eapply sim_trav_step_rmw_covered; eauto. }
{ done. }
exists T'. splits; auto. apply rt_begin.
right. eexists. eauto.
Qed.
Lemma sim_traversal (IMMCON : imm_consistent G sc) :
exists T, (sim_trav_step G sc)* (init_trav G) T /\ (G.(acts_set) ⊆₁ covered T).
Proof using WF.
apply sim_traversal_helper; auto.
{ by apply init_trav_coherent. }
{ unfold init_trav. simpls. basic_solver. }
ins. split; intros [HH AA].
{ apply WF.(init_w) in HH.
apply (dom_l WF.(wf_rmwD)) in RMW. apply seq_eqv_l in RMW.
type_solver. }
apply WF.(rmw_in_sb) in RMW. apply no_sb_to_init in RMW.
apply seq_eqv_r in RMW. desf.
Qed.
Notation "'NTid_' t" := (fun x => tid x <> t) (at level 1).
Notation "'Tid_' t" := (fun x => tid x = t) (at level 1).
Lemma sim_step_cov_full_thread T T' thread thread'
(TCCOH : tc_coherent G sc T)
(TS : isim_trav_step G sc thread' T T')
(NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ covered T) :
thread' = thread.
Proof using.
destruct (classic (thread' = thread)) as [|NEQ]; [by subst|].
exfalso.
apply sim_trav_step_to_step in TS; auto. desf.
red in TS. desf.
{ apply NEXT. apply NCOV. split; eauto. apply COV. }
apply NISS. eapply w_covered_issued; eauto.
split; auto.
{ apply ISS. }
apply NCOV. split; auto. apply ISS.
Qed.
Lemma sim_step_cov_full_traversal T thread
(IMMCON : imm_consistent G sc)
(TCCOH : tc_coherent G sc T) (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ covered T)
(RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)
(RMWCOV : forall r w : actid, rmw r w -> covered T r <-> covered T w) :
exists T', (isim_trav_step G sc thread)* T T' /\ (G.(acts_set) ⊆₁ covered T').
Proof using WF.
edestruct sim_traversal_helper as [T']; eauto.
desc. exists T'. splits; auto.
clear H0.
induction H.
2: ins; apply rt_refl.
{ ins. apply rt_step. destruct H as [thread' H].
assert (thread' = thread); [|by subst].
eapply sim_step_cov_full_thread; eauto. }
ins.
set (NCOV' := NCOV).
apply IHclos_refl_trans1 in NCOV'; auto.
eapply rt_trans; eauto.
eapply IHclos_refl_trans2.
{ eapply sim_trav_steps_coherence; eauto. }
{ etransitivity; eauto.
eapply sim_trav_steps_covered_le; eauto. }
{ eapply sim_trav_steps_rel_covered; eauto. }
eapply sim_trav_steps_rmw_covered; eauto.
Qed.
End TraversalCounting.
|
Subroutine CalcH20u8pProperties(fPerm, fPorosity, fPoreA, fKs, fKf, fap, faXw, faSw, faQInv, faPermeability)
Implicit None
Real, Intent(IN) :: fPerm, fPorosity, fPoreA, fKs, fKf, fap(8)
Real, Intent(OUT) :: faXw(8), faSw(8), faQInv(8), faPermeability(8)
! Main routine
faXw = 1.
faSw = 1.
faQInv = 0. + fPorosity * faSw / fKf + (fPoreA - fPorosity) * faXw / fKs
faPermeability = fPerm
End Subroutine
! ******************************************
! Integer function CalcOnlyKHexa8()
!
! IN:
! iElemNo(integer): Position in the elements matrix
! of the element that the stiffness
! matrix will be calculated.
!
! OUT:
! ---
!
! RETURNS:
! (integer): Number of nodes per element
!
! UPDATES:
! ---
!
! PURPOSE:
! Calculate the element stiffness matrix
!
! NOTES:
! ---
! ******************************************
Subroutine CalcH20u8pGaussMatrices(iInt, faXYZ, faWeight20, faS20, faDS20, faJ20, faDetJ20, faB20, &
faDetJ8, faB8, faWeight8, faS8, faDS8)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pGaussMatrices
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: faXYZ(3, 20)
Real, Intent(OUT) :: faDS20(60, iInt ** 3), faS20(20, iInt ** 3), faS8(8, iInt ** 3), &
faB20(6, 60, iInt ** 3), faB8(6, 24, iInt ** 3), faDetJ20(iInt ** 3), faJ20(3, 3, iInt ** 3), &
faWeight20(iInt ** 3), faWeight8(iInt ** 3), faDetJ8(iInt ** 3), faDS8(24, iInt ** 3)
Real fXi, fEta, fZeta, faXYZ8(3, 8), faJ8(3, 3, iInt ** 3), fWt
Integer M, iX, iY, iZ, iErr, CalcH20JDetJ, CalcH8JDetJ, I, J
Real GP(4, 4), GW(4, 4)
! GP Matrix stores Gauss - Legendre sampling points
Data GP/ &
0.D0, 0.D0, 0.D0, 0.D0, -.5773502691896D0, &
.5773502691896D0, 0.D0, 0.D0, -.7745966692415D0, 0.D0, &
.7745966692415D0, 0.D0, -.8611363115941D0, &
-.3399810435849D0, .3399810435849D0, .8611363115941D0 /
! GW Matrix stores Gauss - Legendre weighting factors
Data GW/ &
2.D0, 0.D0, 0.D0, 0.D0, 1.D0, 1.D0, &
0.D0, 0.D0, .5555555555556D0, .8888888888889D0, &
.5555555555556D0, 0.D0, .3478548451375D0, .6521451548625D0, &
.6521451548625D0, .3478548451375D0 /
! Main routine
faXYZ8(1, 1) = faXYZ(1, 1)
faXYZ8(1, 2) = faXYZ(1, 2)
faXYZ8(1, 3) = faXYZ(1, 3)
faXYZ8(1, 4) = faXYZ(1, 4)
faXYZ8(1, 5) = faXYZ(1, 5)
faXYZ8(1, 6) = faXYZ(1, 6)
faXYZ8(1, 7) = faXYZ(1, 7)
faXYZ8(1, 8) = faXYZ(1, 8)
faXYZ8(2, 1) = faXYZ(2, 1)
faXYZ8(2, 2) = faXYZ(2, 2)
faXYZ8(2, 3) = faXYZ(2, 3)
faXYZ8(2, 4) = faXYZ(2, 4)
faXYZ8(2, 5) = faXYZ(2, 5)
faXYZ8(2, 6) = faXYZ(2, 6)
faXYZ8(2, 7) = faXYZ(2, 7)
faXYZ8(2, 8) = faXYZ(2, 8)
faXYZ8(3, 1) = faXYZ(3, 1)
faXYZ8(3, 2) = faXYZ(3, 2)
faXYZ8(3, 3) = faXYZ(3, 3)
faXYZ8(3, 4) = faXYZ(3, 4)
faXYZ8(3, 5) = faXYZ(3, 5)
faXYZ8(3, 6) = faXYZ(3, 6)
faXYZ8(3, 7) = faXYZ(3, 7)
faXYZ8(3, 8) = faXYZ(3, 8)
M = 0
Do iX = 1, iInt
fXi = GP(iX, iInt)
Do iY = 1, iInt
fEta = GP(iY, iInt)
Do iZ = 1, iInt
fZeta = GP(iZ, iInt)
fWt = GW(iX, iInt) * GW(iY, iInt) * GW(iZ, iInt)
M = M + 1
Call CalcH20NablaShape(fXi, fEta, fZeta, faDS20(1, M))
Call CalcH20Shape(fXi, fEta, fZeta, faS20(1, M))
iErr = CalcH20JDetJ(faXYZ, faDS20(1, M), faJ20(1, 1, M), faDetJ20(M))
Call CalcH20B(faDetJ20(M), faJ20(1, 1, M), faDS20(1, M), faB20(1, 1, M))
faWeight20(M) = fWt * faDetJ20(M)
Call CalcH8NablaShape(fXi, fEta, fZeta, faDS8(1, M))
Call CalcH8Shape(fXi, fEta, fZeta, faS8(1, M))
iErr = CalcH8JDetJ(faXYZ8, faDS8(1, M), faJ8(1, 1, M), faDetJ8(M))
Call CalcH8B(faDetJ8(M), faJ8(1, 1, M), faDS8(1, M), faB8(1, 1, M))
faWeight8(M) = fWt * faDetJ8(M)
EndDo
EndDo
EndDo
End Subroutine
! ******************************************
! Integer function CalcOnlyMHexa8(iElemNo)
!
! IN:
! iElemNo(integer): Position in the elements matrix
! of the element that the stiffness
! matrix will be calculated.
!
! OUT:
! ---
!
! RETURNS:
! (integer): Number of nodes per element
!
! UPDATES:
! ---
!
! PURPOSE:
! Calculate the element stiffness matrix
!
! NOTES:
! ---
! ******************************************
Subroutine CalcH20u8pH(iInt, faPermeability, faS, faB, faWeight, faH)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pH
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: faWeight(iInt ** 3), faS(8, iInt ** 3), faB(6, 24, iInt ** 3), faPermeability(8)
Real, Intent(OUT) :: faH(36)
Real :: fStiff, fTerm, fPermeability
Integer :: I, J, K, M, KS, iX, iY, iZ, iR1, iR2, iR3, iC
! Main routine
! Calculate Stress-Strain equations
! Calculate stiffness matrix
M = 0
Do I = 1, 36
faH(I) = 0D0
EndDo
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
! Add contribution to element stiffness
fPermeability = 0.
Do J = 1, 8
fPermeability = fPermeability + faPermeability(J) * faS(J, M)
End Do
KS = 0
fTerm = faWeight(M) * fPermeability
Do I = 1, 8
iR1 = 3 * (I - 1) + 1
iR2 = iR1 + 1
iR3 = iR1 + 2
Do J = I, 8
KS = KS + 1
iC = 3 * (J - 1) + 1
fStiff = faB(1, iC, M) * faB(1, iR1, M) + faB(2, iC + 1, M) * faB(2, iR2, M) + &
faB(3, iC + 2, M) * faB(3, iR3, M)
faH(KS) = faH(KS) + fStiff * fTerm
EndDo
EndDo
EndDo
EndDo
EndDo
End Subroutine
! ******************************************
! Integer function CalcOnlyMHexa8(iElemNo)
!
! IN:
! iElemNo(integer): Position in the elements matrix
! of the element that the stiffness
! matrix will be calculated.
!
! OUT:
! ---
!
! RETURNS:
! (integer): Number of nodes per element
!
! UPDATES:
! ---
!
! PURPOSE:
! Calculate the element stiffness matrix
!
! NOTES:
! ---
! ******************************************
Subroutine CalcH20u8pS(iInt, faXwDivQ, faS, faWeight, faM)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pS
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: faXwDivQ(8), faWeight(iInt ** 3), faS(8, iInt ** 3)
Real, Intent(OUT) :: faM(36)
Integer :: I, J, M, KS, iX, iY, iZ
Real :: fTerm, fXwDivQ
! Main routine
M = 0
Do I = 1, 36
faM(I) = 0D0
EndDo
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
! Add contribution to element stiffness
fXwDivQ = 0.
Do J = 1, 8
fXwDivQ = fXwDivQ + faXwDivQ(J) * faS(J, M)
End Do
KS = 0
fTerm = faWeight(M) * fXwDivQ
Do I = 1, 8
Do J = I, 8
KS = KS + 1
faM(KS) = faM(KS) + fTerm * faS(I, M) * faS(J, M)
EndDo
EndDo
EndDo
EndDo
EndDo
! Open(100, FILE = 'D:\GAnal\GAnalF\Mass3.txt', STATUS = 'NEW')
! Do I = 1, 300
! Write(100, 999) (I), faM(I)
! EndDo
! Close(100)
999 FORMAT (I5, F10.5)
End Subroutine
! ******************************************
! Integer function CalcOnlyMHexa8(iElemNo)
!
! IN:
! iElemNo(integer): Position in the elements matrix
! of the element that the stiffness
! matrix will be calculated.
!
! OUT:
! ---
!
! RETURNS:
! (integer): Number of nodes per element
!
! UPDATES:
! ---
!
! PURPOSE:
! Calculate the element stiffness matrix
!
! NOTES:
! ---
! ******************************************
!Subroutine CalcH20u8pQTildeQ(iInt, fPoreA, fXw, faB20, faS8, faWeight20, faQ, faQTilde)
Subroutine CalcH20u8pQMinus(iInt, fPoreA, faXw, faB20, faS8, faWeight20, faQTilde)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pQMinus
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: fPoreA, faXw(8), faWeight20(iInt ** 3), &
faB20(6, 60, iInt ** 3), faS8(8, iInt ** 3)
Real, Intent(OUT) :: faQTilde(60, 8)
Integer :: I, J, K, M, KS, iX, iY, iZ, iWidth
Real :: fWeight, fWeightShape, fXw
! Main routine
M = 0
Do J = 1, 8
Do I = 1, 60
faQTilde(I, J) = 0.
EndDo
EndDo
! Compute QTilde
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
fXw = 0.
Do J = 1, 8
fXw = fXw + faXw(J) * faS8(J, M)
End Do
fWeight = faWeight20(M) * fPoreA * fXw
Do J = 1, 8
fWeightShape = fWeight * faS8(J, M)
Do I = 1, 60
! faQTilde(I, J) = faQTilde(I, J) + faB20(mod(I - 1, 3) + 1, I, M) * fWeightShape
faQTilde(I, J) = faQTilde(I, J) - fWeightShape * &
(faB20(1, I, M) + faB20(2, I, M) + faB20(3, I, M))
End Do
End Do
EndDo
EndDo
EndDo
! faQTilde = fXw * faQTilde
! Compute Q
! Do J = 1, 8
! Do I = 1, 60
! faQ(I, J) = faQTilde(I, J) * fXw
! EndDo
! EndDo
! Open(100, FILE = 'D:\GAnal\GAnalF\Mass3.txt', STATUS = 'NEW')
! Do I = 1, 300
! Write(100, 999) (I), faM(I)
! EndDo
! Close(100)
999 FORMAT (I5, F10.5)
End Subroutine
! ******************************************
! Integer function CalcOnlyMHexa8(iElemNo)
!
! IN:
! iElemNo(integer): Position in the elements matrix
! of the element that the stiffness
! matrix will be calculated.
!
! OUT:
! ---
!
! RETURNS:
! (integer): Number of nodes per element
!
! UPDATES:
! ---
!
! PURPOSE:
! Calculate the element stiffness matrix
!
! NOTES:
! ---
! ******************************************
!Subroutine CalcH20u8pQTildeQ(iInt, fPoreA, fXw, faB20, faS8, faWeight20, faQ, faQTilde)
Subroutine CalcH8u8pQMinus(iInt, fPoreA, faXw, faB20, faS8, faWeight20, faQTilde)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH8u8pQMinus
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: fPoreA, faXw(8), faWeight20(iInt ** 3), &
faB20(6, 24, iInt ** 3), faS8(8, iInt ** 3)
Real, Intent(OUT) :: faQTilde(24, 8)
Integer :: I, J, K, M, KS, iX, iY, iZ, iWidth
Real :: fWeight, fWeightShape, fXw
! Main routine
M = 0
Do J = 1, 8
Do I = 1, 24
faQTilde(I, J) = 0.
EndDo
EndDo
! Compute QTilde
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
fXw = 0.
Do J = 1, 8
fXw = fXw + faXw(J) * faS8(J, M)
End Do
fWeight = faWeight20(M) * fPoreA * fXw
Do J = 1, 8
fWeightShape = fWeight * faS8(J, M)
Do I = 1, 24
! faQTilde(I, J) = faQTilde(I, J) + faB20(mod(I - 1, 3) + 1, I, M) * fWeightShape
faQTilde(I, J) = faQTilde(I, J) - fWeightShape * &
(faB20(1, I, M) + faB20(2, I, M) + faB20(3, I, M))
End Do
End Do
EndDo
EndDo
EndDo
999 FORMAT (I5, F10.5)
End Subroutine
Subroutine CalcH20u8pQTilde(iInt, fPoreA, faB20, faS8, faWeight20, faQTilde)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pQTilde
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: fPoreA, faWeight20(iInt ** 3), &
faB20(6, 60, iInt ** 3), faS8(8, iInt ** 3)
Real, Intent(OUT) :: faQTilde(60, 8)
Integer :: I, J, K, M, KS, iX, iY, iZ, iWidth
Real :: fWeight, fWeightShape
! Main routine
M = 0
Do J = 1, 8
Do I = 1, 60
faQTilde(I, J) = 0.
EndDo
EndDo
! Compute QTilde
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
fWeight = faWeight20(M) * fPoreA
Do J = 1, 8
fWeightShape = fWeight * faS8(J, M)
Do I = 1, 60
faQTilde(I, J) = faQTilde(I, J) + fWeightShape * &
(faB20(1, I, M) + faB20(2, I, M) + faB20(3, I, M))
End Do
End Do
EndDo
EndDo
EndDo
End Subroutine
Subroutine CalcH8u8pQTilde(iInt, fPoreA, faB20, faS8, faWeight20, faQTilde)
!DEC$ ATTRIBUTES DLLEXPORT::CalcH8u8pQTilde
Implicit None
Integer, Intent(IN) :: iInt
Real, Intent(IN) :: fPoreA, faWeight20(iInt ** 3), &
faB20(6, 24, iInt ** 3), faS8(8, iInt ** 3)
Real, Intent(OUT) :: faQTilde(24, 8)
Integer :: I, J, K, M, KS, iX, iY, iZ, iWidth
Real :: fWeight, fWeightShape
! Main routine
M = 0
Do J = 1, 8
Do I = 1, 24
faQTilde(I, J) = 0.
EndDo
EndDo
! Compute QTilde
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
M = M + 1
fWeight = faWeight20(M) * fPoreA
Do J = 1, 8
fWeightShape = fWeight * faS8(J, M)
Do I = 1, 24
faQTilde(I, J) = faQTilde(I, J) + fWeightShape * &
(faB20(1, I, M) + faB20(2, I, M) + faB20(3, I, M))
End Do
End Do
EndDo
EndDo
EndDo
End Subroutine
Subroutine CalcH20u8pForcesFromPoresQ(piEqLM, pfElementQ, pfP, pfGlobalForces)
Implicit None
Integer, Intent(IN) :: piEqLM(1)
Real, Intent(IN) :: pfElementQ(60, 8), pfP(8)
Real, Intent(OUT) :: pfGlobalForces(1)
Integer :: I, J, iTemp
Real :: fLocalForces(60)
! Main function
! Initialize local forces vector
fLocalForces(1) = 0D0
fLocalForces(2) = 0D0
fLocalForces(3) = 0D0
fLocalForces(4) = 0D0
fLocalForces(5) = 0D0
fLocalForces(6) = 0D0
fLocalForces(7) = 0D0
fLocalForces(8) = 0D0
fLocalForces(9) = 0D0
fLocalForces(10) = 0D0
fLocalForces(11) = 0D0
fLocalForces(12) = 0D0
fLocalForces(13) = 0D0
fLocalForces(14) = 0D0
fLocalForces(15) = 0D0
fLocalForces(16) = 0D0
fLocalForces(17) = 0D0
fLocalForces(18) = 0D0
fLocalForces(19) = 0D0
fLocalForces(20) = 0D0
fLocalForces(21) = 0D0
fLocalForces(22) = 0D0
fLocalForces(23) = 0D0
fLocalForces(24) = 0D0
fLocalForces(25) = 0D0
fLocalForces(26) = 0D0
fLocalForces(27) = 0D0
fLocalForces(28) = 0D0
fLocalForces(29) = 0D0
fLocalForces(30) = 0D0
fLocalForces(31) = 0D0
fLocalForces(32) = 0D0
fLocalForces(33) = 0D0
fLocalForces(34) = 0D0
fLocalForces(35) = 0D0
fLocalForces(36) = 0D0
fLocalForces(37) = 0D0
fLocalForces(38) = 0D0
fLocalForces(39) = 0D0
fLocalForces(40) = 0D0
fLocalForces(41) = 0D0
fLocalForces(42) = 0D0
fLocalForces(43) = 0D0
fLocalForces(44) = 0D0
fLocalForces(45) = 0D0
fLocalForces(46) = 0D0
fLocalForces(47) = 0D0
fLocalForces(48) = 0D0
fLocalForces(49) = 0D0
fLocalForces(50) = 0D0
fLocalForces(51) = 0D0
fLocalForces(52) = 0D0
fLocalForces(53) = 0D0
fLocalForces(54) = 0D0
fLocalForces(55) = 0D0
fLocalForces(56) = 0D0
fLocalForces(57) = 0D0
fLocalForces(58) = 0D0
fLocalForces(59) = 0D0
fLocalForces(60) = 0D0
! Multiply element Q with vector pfP and store to fLocalForces
Do J = 1, 8
Do I = 1, 60
fLocalForces(I) = fLocalForces(I) + pfElementQ(I, J) * pfP(J)
End Do
End Do
! Update the global loads vector (pfGlobalForces)
iTemp = piEqLM(1)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(1)
iTemp = piEqLM(2)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(2)
iTemp = piEqLM(3)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(3)
iTemp = piEqLM(4)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(4)
iTemp = piEqLM(5)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(5)
iTemp = piEqLM(6)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(6)
iTemp = piEqLM(7)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(7)
iTemp = piEqLM(8)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(8)
iTemp = piEqLM(9)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(9)
iTemp = piEqLM(10)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(10)
iTemp = piEqLM(11)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(11)
iTemp = piEqLM(12)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(12)
iTemp = piEqLM(13)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(13)
iTemp = piEqLM(14)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(14)
iTemp = piEqLM(15)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(15)
iTemp = piEqLM(16)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(16)
iTemp = piEqLM(17)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(17)
iTemp = piEqLM(18)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(18)
iTemp = piEqLM(19)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(19)
iTemp = piEqLM(20)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(20)
iTemp = piEqLM(21)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(21)
iTemp = piEqLM(22)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(22)
iTemp = piEqLM(23)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(23)
iTemp = piEqLM(24)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(24)
iTemp = piEqLM(25)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(25)
iTemp = piEqLM(26)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(26)
iTemp = piEqLM(27)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(27)
iTemp = piEqLM(28)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(28)
iTemp = piEqLM(29)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(29)
iTemp = piEqLM(30)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(30)
iTemp = piEqLM(31)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(31)
iTemp = piEqLM(32)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(32)
iTemp = piEqLM(33)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(33)
iTemp = piEqLM(34)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(34)
iTemp = piEqLM(35)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(35)
iTemp = piEqLM(36)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(36)
iTemp = piEqLM(37)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(37)
iTemp = piEqLM(38)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(38)
iTemp = piEqLM(39)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(39)
iTemp = piEqLM(40)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(40)
iTemp = piEqLM(41)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(41)
iTemp = piEqLM(42)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(42)
iTemp = piEqLM(43)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(43)
iTemp = piEqLM(44)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(44)
iTemp = piEqLM(45)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(45)
iTemp = piEqLM(46)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(46)
iTemp = piEqLM(47)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(47)
iTemp = piEqLM(48)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(48)
iTemp = piEqLM(49)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(49)
iTemp = piEqLM(50)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(50)
iTemp = piEqLM(51)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(51)
iTemp = piEqLM(52)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(52)
iTemp = piEqLM(53)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(53)
iTemp = piEqLM(54)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(54)
iTemp = piEqLM(55)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(55)
iTemp = piEqLM(56)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(56)
iTemp = piEqLM(57)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(57)
iTemp = piEqLM(58)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(58)
iTemp = piEqLM(59)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(59)
iTemp = piEqLM(60)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(60)
End Subroutine
Subroutine CalcH20u8pForcesFromPoresH(piEqLM, pfElementH, pfP, pfGlobalForces)
Implicit None
Integer, Intent(IN) :: piEqLM(1)
Real, Intent(IN) :: pfElementH(36), pfP(8)
Real, Intent(OUT) :: pfGlobalForces(1)
Integer :: I, J, iRow, iAccR, iTemp, iDataPos
Real :: fLocalForces(8)
! Main function
! Initialize local forces vector
fLocalForces(1) = 0D0
fLocalForces(2) = 0D0
fLocalForces(3) = 0D0
fLocalForces(4) = 0D0
fLocalForces(5) = 0D0
fLocalForces(6) = 0D0
fLocalForces(7) = 0D0
fLocalForces(8) = 0D0
! Multiply SKYLINE Element H with vector pfP and store to fLocalForces
iDataPos = 1
Do I = 1, 8
fLocalForces(I) = fLocalForces(I) + pfElementH(iDataPos) * pfP(I)
iDataPos = iDataPos + 1
Do J = I + 1, 8
fLocalForces(I) = fLocalForces(I) + pfElementH(iDataPos) * pfP(J)
fLocalForces(J) = fLocalForces(J) + pfElementH(iDataPos) * pfP(I)
iDataPos = iDataPos + 1
End Do
End Do
! Update the global loads vector (pfGlobalForces)
iTemp = piEqLM(1)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(1)
iTemp = piEqLM(2)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(2)
iTemp = piEqLM(3)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(3)
iTemp = piEqLM(4)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(4)
iTemp = piEqLM(5)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(5)
iTemp = piEqLM(6)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(6)
iTemp = piEqLM(7)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(7)
iTemp = piEqLM(8)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(8)
End Subroutine
Subroutine CalcH20u8pForcesFromAccWater(iInt, iImpermeable, piImpermeableIDs, piEqLM, &
piEqIDs, fDPS, pfElementB, pfAcc, pfWeights, pfGlobalForces)
Implicit None
Integer, Intent(IN) :: iInt, iImpermeable, piEqLM(1), piEqIDs(4, 1), piImpermeableIDs(1)
Real, Intent(IN) :: fDPS, pfElementB(1), pfAcc(3), pfWeights(1)
Real, Intent(OUT) :: pfGlobalForces(1)
Integer :: I, iX, iY, iZ, iRow, iAccR, iTemp, iDataPos, iWPos, piEqs(8)
Real :: fLocalForces(8), fAccDPS(3), fWeight, fTerm
! Main function
! Initialize local forces vector
fLocalForces(1) = 0D0
fLocalForces(2) = 0D0
fLocalForces(3) = 0D0
fLocalForces(4) = 0D0
fLocalForces(5) = 0D0
fLocalForces(6) = 0D0
fLocalForces(7) = 0D0
fLocalForces(8) = 0D0
piEqs(1) = piEqLM(1)
piEqs(2) = piEqLM(2)
piEqs(3) = piEqLM(3)
piEqs(4) = piEqLM(4)
piEqs(5) = piEqLM(5)
piEqs(6) = piEqLM(6)
piEqs(7) = piEqLM(7)
piEqs(8) = piEqLM(8)
! Multiply body forces with saturation, permeability and density
fAccDPS(1) = fDPS * pfAcc(1)
fAccDPS(2) = fDPS * pfAcc(2)
fAccDPS(3) = fDPS * pfAcc(3)
! Multiply Element B with vector pfAcc and store to fLocalForces
iDataPos = 1
iWPos = 0
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
iWPos = iWPos + 1
fWeight = pfWeights(iWPos)
Do I = 1, 8
fTerm = pfElementB(iDataPos) * fAccDPS(1) + &
pfElementB(iDataPos + 1) * fAccDPS(2) + &
pfElementB(iDataPos + 2) * fAccDPS(3)
fLocalForces(I) = fLocalForces(I) + fTerm * fWeight
! fLocalForces(I) = fLocalForces(I) + pfElementB(iDataPos) * fAccDPS(1) * &
! fTemp
iDataPos = iDataPos + 3
End Do
End Do
End Do
End Do
! Update the global loads vector (pfGlobalForces)
Do I = 1, iImpermeable
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(1)) piEqs(1) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(2)) piEqs(2) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(3)) piEqs(3) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(4)) piEqs(4) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(5)) piEqs(5) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(6)) piEqs(6) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(7)) piEqs(7) = 0
! if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(8)) piEqs(8) = 0
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(1)) fLocalForces(1) = fLocalForces(1) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(2)) fLocalForces(2) = fLocalForces(2) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(3)) fLocalForces(3) = fLocalForces(3) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(4)) fLocalForces(4) = fLocalForces(4) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(5)) fLocalForces(5) = fLocalForces(5) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(6)) fLocalForces(6) = fLocalForces(6) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(7)) fLocalForces(7) = fLocalForces(7) / 1D11
if (piEqIDs(4, piImpermeableIDs(I)).EQ.piEqs(8)) fLocalForces(8) = fLocalForces(8) / 1D11
End Do
iTemp = piEqs(1)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(1)
iTemp = piEqs(2)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(2)
iTemp = piEqs(3)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(3)
iTemp = piEqs(4)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(4)
iTemp = piEqs(5)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(5)
iTemp = piEqs(6)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(6)
iTemp = piEqs(7)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(7)
iTemp = piEqs(8)
If (iTemp.GT.0) pfGlobalForces(iTemp) = pfGlobalForces(iTemp) + fLocalForces(8)
End Subroutine
!DEC$ ATTRIBUTES DLLEXPORT::CalcH20u8pForcesWaterAcc
Subroutine CalcH20u8pForcesWaterAcc(iInt, alImpermeable, ffDensity, afPermeability, afXw, afSw, afAcc, afS, afB, &
afWeights, afLocalForces)
Implicit None
Integer, Intent(IN) :: iInt
Logical, Intent(IN) :: alImpermeable(8)
Real, Intent(IN) :: ffDensity, afPermeability(8), afXw(8), afSw(8), afS(8, iInt ** 3), &
afB(6, 24, iInt ** 3), afAcc(3), afWeights(*)
Real, Intent(OUT) :: afLocalForces(8)
Integer :: I, iX, iY, iZ, iDataPos, iWPos
Real :: afAccDPS(3), fWeight, fTerm
! Main function
! Initialize local forces vector
afLocalForces(1) = 0D0
afLocalForces(2) = 0D0
afLocalForces(3) = 0D0
afLocalForces(4) = 0D0
afLocalForces(5) = 0D0
afLocalForces(6) = 0D0
afLocalForces(7) = 0D0
afLocalForces(8) = 0D0
! Multiply Element B with vector pfAcc and store to fLocalForces
iDataPos = 1
iWPos = 0
Do iX = 1, iInt
Do iY = 1, iInt
Do iZ = 1, iInt
iWPos = iWPos + 1
fTerm = 0.
Do I = 1, 8
fTerm = fTerm + afPermeability(I) * afXw(I) * afSw(I) * afS(I, iWPos)
End Do
afAccDPS = afAcc * ffDensity * fTerm
fWeight = afWeights(iWPos)
Do I = 0, 7
fTerm = afB(1, (I * 3) + 1, iWPos) * afAccDPS(1) + &
afB(2, (I * 3) + 2, iWPos) * afAccDPS(2) + &
afB(3, (I * 3) + 3, iWPos) * afAccDPS(3)
! fTerm = afElementB(iDataPos) * afAccDPS(1) + &
! afElementB(iDataPos + 1) * afAccDPS(2) + &
! afElementB(iDataPos + 2) * afAccDPS(3)
afLocalForces(I + 1) = afLocalForces(I + 1) + fTerm * fWeight
! fLocalForces(I) = fLocalForces(I) + pfElementB(iDataPos) * fAccDPS(1) * fTemp
iDataPos = iDataPos + 3
End Do
End Do
End Do
End Do
! If impermeable, nullify force
Do I = 1, 8
If (alImpermeable(I)) afLocalForces(I) = 0.
End Do
End Subroutine
|
PROGRAM TSETER
C
C This test program demonstrates minimal functioning of the error-
C handling package used by NCAR Graphics. It first produces a single
C frame showing what output print lines to expect and then steps
C through a simple set of tests that should produce those print lines.
C
C Define the error file, the Fortran unit number, the workstation type,
C and the workstation ID to be used in calls to GKS routines.
C
C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=1, IWKID=1) ! NCGM
C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=8, IWKID=1) ! X Windows
C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=11, IWKID=1) ! PDF
C PARAMETER (IERRF=6, LUNIT=2, IWTYPE=20, IWKID=1) ! PostScript
C
PARAMETER (IERRF=6, LUNIT=2, IWTYPE=1, IWKID=1)
C
C Make required character-variable declarations. ERMSG receives the
C error message returned by the character function SEMESS.
C
CHARACTER*113 ERMSG,SEMESS
C
C The contents of the array LINE defines the lines of print that this
C program should produce.
C
CHARACTER*60 LINE(40)
C
DATA (LINE(I),I=1,10) /
+ ' ' ,
+ 'PROGRAM TSETER EXECUTING' ,
+ ' ' ,
+ 'TSETER - CALL ENTSR TO ENTER RECOVERY MODE' ,
+ ' ' ,
+ 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 1' ,
+ ' ' ,
+ 'TSETER - CALL ERROF TO TURN OFF INTERNAL ERROR FLAG' ,
+ ' ' ,
+ 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 2' /
C
DATA (LINE(I),I=11,20) /
+ ' ' ,
+ 'TSETER - EXECUTE STATEMENT ''IERRO=NERRO(JERRO)''' ,
+ 'TSETER - RESULTING IERRO: 2' ,
+ 'TSETER - RESULTING JERRO: 2' ,
+ ' ' ,
+ 'TSETER - EXECUTE STATEMENT ''ERMSG=SEMESS(0)''' ,
+ 'TSETER - RESULTING ERMSG: ROUTINE_NAME_2 - ERROR_MESSAGE_2' ,
+ 'TSETER - (PRINTING ABOVE LINE ALSO TESTED ICLOEM)' ,
+ ' ' ,
+ 'TSETER - CALL EPRIN TO PRINT CURRENT ERROR MESSAGE' /
C
DATA (LINE(I),I=21,30) /
+ 'ERROR 2 IN ROUTINE_NAME_2 - ERROR_MESSAGE_2' ,
+ 'TSETER - (AN ERROR MESSAGE SHOULD HAVE BEEN PRINTED)' ,
+ ' ' ,
+ 'TSETER - CALL ERROF TO TURN OFF INTERNAL ERROR FLAG' ,
+ ' ' ,
+ 'TSETER - CALL EPRIN TO PRINT CURRENT ERROR MESSAGE' ,
+ 'TSETER - (NOTHING SHOULD HAVE BEEN PRINTED)' ,
+ ' ' ,
+ 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 3' ,
+ ' ' /
C
DATA (LINE(I),I=31,40) /
+ 'TSETER - TEST THE USE OF ICFELL' ,
+ ' ' ,
+ 'TSETER - CALL RETSR TO LEAVE RECOVERY MODE - BECAUSE' ,
+ 'TSETER - THE LAST RECOVERABLE ERROR WAS NOT CLEARED,' ,
+ 'TSETER - THIS WILL CAUSE A FATAL-ERROR CALL TO SETER' ,
+ 'ERROR 3 IN SETER - AN UNCLEARED PRIOR ERROR EXISTS' ,
+ '... MESSAGE FOR UNCLEARED PRIOR ERROR IS AS FOLLOWS:' ,
+ '... ERROR 6 IN SETER/ROUTINE_NAME_3 - ERROR_MESSAGE_3' ,
+ '... MESSAGE FOR CURRENT CALL TO SETER IS AS FOLLOWS:' ,
+ '... ERROR 2 IN RETSR - PRIOR ERROR IS NOW UNRECOVERABLE' /
C
C Open GKS.
C
CALL GOPKS (IERRF, ISZDM)
CALL GOPWK (IWKID, LUNIT, IWTYPE)
CALL GACWK (IWKID)
C
C Produce a single frame of output, detailing what the program ought to
C print.
C
CALL SET (0.,1.,0.,1.,0.,1.,0.,1.,1)
C
CALL PCSETC ('FC - FUNCTION CODE SIGNAL',CHAR(0))
C
CALL PCSETI ('FN - FONT NUMBER',26)
C
CALL PLCHHQ (.5,.975,'SETER TEST "tseter"',.025,0.,0.)
C
CALL PCSETI ('FN - FONT NUMBER',1)
C
CALL PLCHHQ (.5,.925,'See the print output; it should consist of
+ the following lines:',.011,0.,0.)
C
DO 101 I=1,40
CALL PLCHHQ (.15,.9-REAL(I-1)*.022,LINE(I),.011,0.,-1.)
101 CONTINUE
C
C Advance the frame.
C
CALL FRAME
C
C Close GKS.
C
CALL GDAWK (IWKID)
CALL GCLWK (IWKID)
CALL GCLKS
C
C Enter recovery mode.
C
PRINT * , ' '
PRINT * , 'PROGRAM TSETER EXECUTING'
PRINT * , ' '
PRINT * , 'TSETER - CALL ENTSR TO ENTER RECOVERY MODE'
C
CALL ENTSR (IROLD,1)
C
C Log a recoverable error. Nothing should be printed, but the internal
C error flag should be set and the message should be remembered.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 1'
C
CALL SETER ('ROUTINE_NAME_1 - ERROR_MESSAGE_1',1,1)
C
C Clear the internal error flag.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL ERROF TO TURN OFF INTERNAL ERROR FLAG'
C
CALL ERROF
C
C Log another recoverable error. Again, nothing should be printed, but
C the internal error flag should be set and the message should be
C remembered.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 2'
C
CALL SETER ('ROUTINE_NAME_2 - ERROR_MESSAGE_2',2,1)
C
C Pick up and print the error flag, as returned in each of two
C ways by the function NERRO.
C
PRINT * , ' '
PRINT * , 'TSETER - EXECUTE STATEMENT ''IERRO=NERRO(JERRO)'''
C
IERRO=NERRO(JERRO)
C
PRINT * , 'TSETER - RESULTING IERRO: ',IERRO
PRINT * , 'TSETER - RESULTING JERRO: ',JERRO
C
C Pick up and print the error message, as returned by the function
C SEMESS. This also tests proper functioning of the function ICLOEM.
C
PRINT * , ' '
PRINT * , 'TSETER - EXECUTE STATEMENT ''ERMSG=SEMESS(0)'''
C
ERMSG=SEMESS(0)
C
PRINT * , 'TSETER - RESULTING ERMSG: ',ERMSG(1:ICLOEM(ERMSG))
PRINT * , 'TSETER - (PRINTING ABOVE LINE ALSO TESTED ICLOEM)'
C
C Print the current error message.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL EPRIN TO PRINT CURRENT ERROR MESSAGE'
C
CALL EPRIN
C
PRINT * , 'TSETER - (AN ERROR MESSAGE SHOULD HAVE BEEN PRINTED)'
C
C Clear the internal error flag again.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL ERROF TO TURN OFF INTERNAL ERROR FLAG'
C
CALL ERROF
C
C Try to print the error message again. Nothing should be printed.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL EPRIN TO PRINT CURRENT ERROR MESSAGE'
C
CALL EPRIN
C
PRINT * , 'TSETER - (NOTHING SHOULD HAVE BEEN PRINTED)'
C
C Log another recoverable error.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL SETER TO REPORT RECOVERABLE ERROR 3'
C
CALL SETER ('ROUTINE_NAME_3 - ERROR_MESSAGE_3',5,1)
C
C Test the use of ICFELL.
C
PRINT * , ' '
PRINT * , 'TSETER - TEST THE USE OF ICFELL'
C
IF (ICFELL('TSETER',6).NE.5) THEN
PRINT * , ' '
PRINT * , 'TSETER - ICFELL MALFUNCTIONED - SOMETHING''S WRONG'
STOP
END IF
C
C Turn recovery mode off without clearing the internal error flag,
C which should be treated as a fatal error.
C
PRINT * , ' '
PRINT * , 'TSETER - CALL RETSR TO LEAVE RECOVERY MODE - BECAUSE'
PRINT * , 'TSETER - THE LAST RECOVERABLE ERROR WAS NOT CLEARED,'
PRINT * , 'TSETER - THIS WILL CAUSE A FATAL-ERROR CALL TO SETER'
C
CALL RETSR (IROLD)
C
C Control should never get to the next statement, but just in case ...
C
PRINT * , ' '
PRINT * , 'TSETER - GOT CONTROL BACK - SOMETHING''S WRONG'
C
STOP
C
END
|
module FreeVarPresheaves where
open import Data.Nat as Nat
import Level
open import Categories.Category
open import Categories.Presheaf
open import Relation.Binary.Core
open import Relation.Binary
open import Function using (flip)
module DTO = DecTotalOrder Nat.decTotalOrder
data ℕ-≤-eq {n m : ℕ} : Rel (n ≤ m) Level.zero where
triv-eq : ∀ {p q} → ℕ-≤-eq p q
ℕ-≤-eq-equivRel : ∀ {n m} → IsEquivalence (ℕ-≤-eq {n} {m})
ℕ-≤-eq-equivRel = record
{ refl = triv-eq
; sym = λ _ → triv-eq
; trans = λ _ _ → triv-eq
}
{-
trans-assoc : ∀ {a ℓ} {A : Set a} →
{_<_ : Rel A ℓ} →
{trans : Transitive _<_} →
∀ {w x y z : A} → ∀{p : w < x} → ∀{q : x < y} → ∀{r : y < z} →
(trans p (trans q r)) ≡ (trans (trans p q) r)
trans-assoc = {!!}
-}
ℕ-≤-eq-assoc : {m n k i : ℕ} {p : m ≤ n} {q : n ≤ k} {r : k ≤ i} →
ℕ-≤-eq (DTO.trans p (DTO.trans q r)) (DTO.trans (DTO.trans p q) r)
ℕ-≤-eq-assoc = triv-eq
trans-resp-ℕ-≤-eq : {m n k : ℕ} {p r : n ≤ k} {q s : m ≤ n} →
ℕ-≤-eq p r → ℕ-≤-eq q s → ℕ-≤-eq (DTO.trans q p) (DTO.trans s r)
trans-resp-ℕ-≤-eq _ _ = triv-eq
op : Category Level.zero Level.zero Level.zero
op = record
{ Obj = ℕ
; _⇒_ = Nat._≤_
; _≡_ = ℕ-≤-eq
; _∘_ = flip DTO.trans
; id = DTO.refl
; assoc = ℕ-≤-eq-assoc
; identityˡ = triv-eq
; identityʳ = triv-eq
; equiv = ℕ-≤-eq-equivRel
; ∘-resp-≡ = trans-resp-ℕ-≤-eq
}
Ctx a = List (Var a)
data Var : (Γ : Ctx) → Set where
zero : ∀{Γ} → TyVar (Γ + 1)
succ : ∀{Γ} (x : TyVar Γ) → TyVar (Γ + 1)
|
[STATEMENT]
lemma keys_bulkload [simp]: "keys (bulkload xs) = {0..<length xs}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. keys (bulkload xs) = {0..<length xs}
[PROOF STEP]
by (simp add: bulkload_tabulate) |
lemma (in semiring_of_sets) generated_ring_Inter: assumes "finite A" "A \<noteq> {}" shows "A \<subseteq> generated_ring \<Longrightarrow> \<Inter>A \<in> generated_ring" |
=begin
# sample-polynomial02.rb
require "algebra"
P = Polynomial(Integer, "x", "y", "z")
x, y, z = P.vars
p((-x + y + z)*(x + y - z)*(x - y + z))
#=> -z^3 + (y + x)z^2 + (y^2 - 2xy + x^2)z - y^3 + xy^2 + x^2y - x^3
((<_|CONTENTS>))
=end
|
lemma algebraic_int_abs_real [simp]: "algebraic_int \<bar>x :: real\<bar> \<longleftrightarrow> algebraic_int x" |
/-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales
-/
import data.real.basic
import data.real.sqrt
import data.nat.prime
import number_theory.primes_congruent_one
import number_theory.quadratic_reciprocity
/-!
# IMO 2008 Q3
Prove that there exist infinitely many positive integers `n` such that `n^2 + 1` has a prime
divisor which is greater than `2n + √(2n)`.
# Solution
We first prove the following lemma: for every prime `p > 20`, satisfying `p ≡ 1 [MOD 4]`,
there exists `n ∈ ℕ` such that `p ∣ n^2 + 1` and `p > 2n + √(2n)`. Then the statement of the
problem follows from the fact that there exist infinitely many primes `p ≡ 1 [MOD 4]`.
To prove the lemma, notice that `p ≡ 1 [MOD 4]` implies `∃ n ∈ ℕ` such that `n^2 ≡ -1 [MOD p]`
and we can take this `n` such that `n ≤ p/2`. Let `k = p - 2n ≥ 0`. Then we have:
`k^2 + 4 = (p - 2n)^2 + 4 ≣ 4n^2 + 4 ≡ 0 [MOD p]`. Then `k^2 + 4 ≥ p` and so `k ≥ √(p - 4) > 4`.
Then `p = 2n + k ≥ 2n + √(p - 4) = 2n + √(2n + k - 4) > √(2n)` and we are done.
-/
open real
lemma p_lemma (p : ℕ) (hpp : nat.prime p) (hp_mod_4_eq_1 : p ≡ 1 [MOD 4]) (hp_gt_20 : p > 20) :
∃ n : ℕ, p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) :=
begin
haveI := fact.mk hpp,
have hp_mod_4_ne_3 : p % 4 ≠ 3, { linarith [(show p % 4 = 1, by exact hp_mod_4_eq_1)] },
obtain ⟨y, hy⟩ := (zmod.exists_sq_eq_neg_one_iff_mod_four_ne_three p).mpr hp_mod_4_ne_3,
let m := zmod.val_min_abs y,
let n := int.nat_abs m,
have hnat₁ : p ∣ n ^ 2 + 1,
{ refine int.coe_nat_dvd.mp _,
simp only [int.nat_abs_sq, int.coe_nat_pow, int.coe_nat_succ, int.coe_nat_dvd.mp],
refine (zmod.int_coe_zmod_eq_zero_iff_dvd (m ^ 2 + 1) p).mp _,
simp only [int.cast_pow, int.cast_add, int.cast_one, zmod.coe_val_min_abs],
rw hy, exact add_left_neg 1 },
have hnat₂ : n ≤ p / 2 := zmod.nat_abs_val_min_abs_le y,
have hnat₃ : p ≥ 2 * n, { linarith [nat.div_mul_le_self p 2] },
set k : ℕ := p - 2 * n with hnat₄,
have hnat₅ : p ∣ k ^ 2 + 4,
{ cases hnat₁ with x hx,
let p₁ := (p : ℤ), let n₁ := (n : ℤ), let k₁ := (k : ℤ), let x₁ := (x : ℤ),
have : p₁ ∣ k₁ ^ 2 + 4,
{ use p₁ - 4 * n₁ + 4 * x₁,
have hcast₁ : k₁ = p₁ - 2 * n₁, { assumption_mod_cast },
have hcast₂ : n₁ ^ 2 + 1 = p₁ * x₁, { assumption_mod_cast },
calc k₁ ^ 2 + 4
= (p₁ - 2 * n₁) ^ 2 + 4 : by rw hcast₁
... = p₁ ^ 2 - 4 * p₁ * n₁ + 4 * (n₁ ^ 2 + 1) : by ring
... = p₁ ^ 2 - 4 * p₁ * n₁ + 4 * (p₁ * x₁) : by rw hcast₂
... = p₁ * (p₁ - 4 * n₁ + 4 * x₁) : by ring },
assumption_mod_cast },
have hnat₆ : k ^ 2 + 4 ≥ p := nat.le_of_dvd (k ^ 2 + 3).succ_pos hnat₅,
let p₀ := (p : ℝ), let n₀ := (n : ℝ), let k₀ := (k : ℝ),
have hreal₁ : p₀ = 2 * n₀ + k₀, { linarith [(show k₀ = p₀ - 2 * n₀, by assumption_mod_cast)] },
have hreal₂ : p₀ > 20, { assumption_mod_cast },
have hreal₃ : k₀ ^ 2 + 4 ≥ p₀, { assumption_mod_cast },
have hreal₄ : k₀ ≥ sqrt(p₀ - 4),
{ calc k₀ = sqrt(k₀ ^ 2) : eq.symm (sqrt_sq (nat.cast_nonneg k))
... ≥ sqrt(p₀ - 4) : sqrt_le_sqrt (by linarith [hreal₃]) },
have hreal₅ : k₀ > 4,
{ calc k₀ ≥ sqrt(p₀ - 4) : hreal₄
... > sqrt(4 ^ 2) : (sqrt_lt (by linarith)).mpr (by linarith [hreal₂])
... = 4 : sqrt_sq (by linarith) },
have hreal₆ : p₀ > 2 * n₀ + sqrt(2 * n),
{ calc p₀ = 2 * n₀ + k₀ : hreal₁
... ≥ 2 * n₀ + sqrt(p₀ - 4) : by linarith [hreal₄]
... = 2 * n₀ + sqrt(2 * n₀ + k₀ - 4) : by rw hreal₁
... > 2 * n₀ + sqrt(2 * n₀) : by { refine add_lt_add_left _ (2 * n₀),
refine (sqrt_lt _).mpr _,
refine mul_nonneg zero_le_two (nat.cast_nonneg n),
linarith [hreal₅] } },
exact ⟨n, hnat₁, hreal₆⟩,
end
theorem imo2008_q3 : ∀ N : ℕ, ∃ n : ℕ, n ≥ N ∧
∃ p : ℕ, nat.prime p ∧ p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) :=
begin
intro N,
obtain ⟨p, hpp, hineq₁, hpmod4⟩ := nat.exists_prime_ge_modeq_one 4 (N ^ 2 + 21) zero_lt_four,
obtain ⟨n, hnat, hreal⟩ := p_lemma p hpp hpmod4 (by linarith [hineq₁, nat.zero_le (N ^ 2)]),
have hineq₂ : n ^ 2 + 1 ≥ p := nat.le_of_dvd (n ^ 2).succ_pos hnat,
have hineq₃ : n * n ≥ N * N, { linarith [hineq₁, hineq₂, (sq n), (sq N)] },
have hn_ge_N : n ≥ N := nat.mul_self_le_mul_self_iff.mpr hineq₃,
exact ⟨n, hn_ge_N, p, hpp, hnat, hreal⟩,
end
|
The questions were the usual sort of demographic-gathering thing for the time–how much money do you spend on DC comics each week, what are your other interests, what’s your age range, etc. But here’s the one that lept out at me. Prepare, depending on whether you were alive in 1978, to feel either totally mystified or REALLY OLD.
I’m gonna go lie down. |
------------- Example 1 ----------------
natInjective : (x, y : Nat) -> S x === S y -> x === y
natInjective x x Refl = Refl
succNotZero : (x : Nat) -> Not (S x === Z)
succNotZero x Refl impossible
peanoNat : (a : Type
** n0 : a
** ns : a -> a
** inj : ((x, y : a) -> ns x === ns y -> x === y)
** (x : a) -> Not (ns x === n0))
peanoNat = MkDPair
Nat
$ MkDPair
Z
$ MkDPair -- {a = Nat -> Nat}
S
$ MkDPair
natInjective
succNotZero
------------- Example 2 ----------------
ac : forall r. ((x : a) -> (y : b ** r x y)) -> (f : a -> b ** (x : a) -> r x (f x))
ac g = (\x => fst (g x) ** \x => snd (g x))
------------- Example 3 ----------------
idid1 : forall A. (f : A -> A ** (x : A) -> f x = x)
idid1 = MkDPair id (\x => Refl)
|
classdef GradientVariationWithRadiusExperiment < handle
properties (Access = private)
iMesh
gExperiment
end
properties (Access = private)
nameCase
inputFiles
outputFolder
levelSetParams
end
methods (Access = public)
function obj = GradientVariationWithRadiusExperiment(s)
obj.init(s);
end
function compute(obj)
for im = 1:numel(obj.inputFiles)
obj.iMesh = im;
obj.createGradientVariationExperiment();
obj.computeGradientVariationWithRadius();
end
end
end
methods (Access = private)
function init(obj,cParams)
obj.nameCase = cParams.nameCase;
obj.inputFiles = cParams.inputFiles;
obj.outputFolder = cParams.outputFolder;
obj.levelSetParams = cParams.levelSetParams;
end
function createGradientVariationExperiment(obj)
s.inputFile = obj.inputFiles{obj.iMesh};
s.iMesh = obj.iMesh;
s.levelSetParams = obj.levelSetParams;
g = GradientVariationExperiment(s);
obj.gExperiment = g;
end
function computeGradientVariationWithRadius(obj)
s.mesh = obj.gExperiment.backgroundMesh;
s.regularizedPerimeter = obj.gExperiment.regularizedPerimeter;
s.inputFile = obj.inputFiles{obj.iMesh};
s.nameCase = obj.nameCase;
s.outputFolder = obj.outputFolder;
s.domainLength = obj.gExperiment.domainLength();
gComputer = GradientVariationWithRadiusComputer(s);
gComputer.compute();
end
end
end |
lemma complex_i_not_zero [simp]: "\<i> \<noteq> 0" |
module LexicalSort
! This module was made available to the comp.lang.fortran newsgroup
! Author unkown
implicit none
public :: sort
private :: partition, quicksort, swap, stringComp, UpperCase
integer, dimension (:), allocatable, private :: indexarray
logical, private :: CaseSensitive
contains
! Subroutine sort uses the quicksort algorithm.
! On input, StringArray is a one-dimensional array of character strings
! to be sorted in ascending lexical order.
! On output, StringArray is the sorted array.
! If the optional argument CaseInsensitive is present and .true.,
! the sort is case-insensitive. If CaseInsensitive is absent or
! if it is .false., the sort is case-sensitive.
! The characters of the elements of the string array are not modified,
! so that if blanks or punctuation characters are to be ignored,
! for instance, this needs to be done before calling sort.
subroutine sort (StringArrayIn, iSortIndexArray, CaseInsensitive)
character (len = *), dimension (:), intent (in out) :: StringArrayIn
integer, dimension (:), intent (out) :: iSortIndexArray
logical, intent (in), optional :: CaseInsensitive
! Local variables
integer :: low, high, ios, k, i
character (len = 50), dimension (:), allocatable :: StringArray
if (present(CaseInsensitive)) then
CaseSensitive = .not. CaseInsensitive
else
CaseSensitive = .true.
end if
low = 1
high = size(StringArrayIn)
allocate(StringArray(high), stat = ios)
StringArray = ' '
StringArray = StringArrayIn
allocate(indexarray(high), stat = ios)
if (ios /= 0) then
write(*, *) "Error allocating indexarray in LexicalSort::sort"
! stop
end if
indexarray = (/ (k, k = low, high) /)
call quicksort(StringArray, low, high)
do i=low, high
StringArrayIn(i) = StringArray(indexarray(i))
iSortIndexArray(i) = indexarray(i)
end do
deallocate(indexarray, stat = ios)
if (ios /= 0) then
write(*, *) "Error deallocating indexarray in LexicalSort::sort"
! stop ! Fortran's Stop is not the best exit for Windows programming !
end if
return
end subroutine sort
recursive subroutine quicksort(StringArray, low, high)
character (len = *), dimension (:), intent (in out) :: StringArray
integer, intent (in) :: low, high
integer :: pivotlocation
if (low < high) then
call partition(StringArray, low, high, pivotlocation)
call quicksort(StringArray, low, pivotlocation - 1)
call quicksort(StringArray, pivotlocation + 1, high)
end if
return
end subroutine quicksort
subroutine partition(StringArray, low, high, pivotlocation)
character (len = *), dimension (:), intent (in out) :: StringArray
integer, intent (in) :: low, high
integer, intent (out) :: pivotlocation
integer :: k, lastsmall
call swap(indexarray(low), indexarray((low + high)/2))
lastsmall = low
do k = low + 1, high
if (stringComp(StringArray(indexarray(k)), StringArray(indexarray(low)))) then
lastsmall = lastsmall + 1
call swap(indexarray(lastsmall), indexarray(k))
end if
end do
call swap(indexarray(low), indexarray(lastsmall))
pivotlocation = lastsmall
return
end subroutine partition
subroutine swap(m, n)
integer, intent (in out) :: m, n
integer :: temp
temp = m
m = n
n = temp
return
end subroutine swap
function stringComp(p, q) result(lexicalLess)
character (len = *), intent (in) :: p, q
logical :: lexicalLess
integer :: kq, k
if (CaseSensitive) then
lexicalLess = p < q
else
kq = 1
do k = 1, max(len_trim(p), len_trim(q))
if (UpperCase(p(k:k)) == UpperCase(q(k:k)) ) then
cycle
else
kq = k
exit
end if
end do
lexicalLess = UpperCase(p(kq:kq)) < UpperCase(q(kq:kq))
end if
return
end function stringComp
function UpperCase(letter) result(L)
character (len = *), intent (in) :: letter
character (len = 1) :: L
character (len = 27), parameter :: Lower = "_abcdefghijklmnopqrstuvwxyz", &
Upper = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
integer :: k
k = index(Lower, letter)
if (k > 0) then
L = Upper(k:k)
else
L = letter
end if
return
end function UpperCase
end module LexicalSort
|
import tactic.ring
-- Lemma 1.52, 2022-10-02 version, "Automatic complexity: a measure of irregularity"
lemma lemma_1_52 (r x y:ℤ)(hr:0<r)(hy:0 ≤ y)(hx:0 ≤ x) :
2 * r^2 = (x+y)*r+(y+1) ↔ (x,y) = (r,r-1) :=
-- General facts:
have hyy: 0 < y+1, from calc
0 ≤ y: hy
... < y+1: lt_add_one y,
have hle: 0 ≤ y+1, from le_of_lt hyy,
have hrn: r ≠ 0, from norm_num.ne_zero_of_pos r hr,
have hlt1: 0 < r+1, from calc
0 < r: hr
... < r+1: lt_add_one r,
have hltr: 0 ≤ r, from le_of_lt hr,
have hr1: 0 ≤ r+1, from le_of_lt hlt1,
have h5:y ≤ x + y, from calc
y = 0+y: by ring
... ≤ x+y: add_le_add hx (le_refl y),
have hzxy: 0 ≤ x+y, from calc
0 ≤ y: hy
...≤ x+y:h5,
have h6:y*r ≤ (x+y)*r, from mul_le_mul h5 (le_refl r) hltr hzxy,
-- Easy direction, just plugging in:
have h2: (x,y) = (r,r-1) → 2* r^2 = (x+y)*r+(y+1) , from λ h,
have hx: x=r, from congr_arg (λ p:ℤ×ℤ, p.1) h,
have hy: y=r-1, from congr_arg (λ p:ℤ×ℤ, p.2) h,
calc 2*r^2 = (r+(r-1)) * r + ((r-1)+1): by ring
... = (x+y) * r + (y+1): by {rw hx,rw hy},
-- Hard direction:
have h1: 2 * r^2 = (x+y)*r+(y+1) → (x,y) = (r,r-1), from
λ h:2 * r^2 = (x+y)*r+(y+1),
have hz3: 0 = y+1 - r * ((y+1)/r), from calc
0 = ((2*r)*r) % r:(int.mul_mod_left (2*r) r).symm
... = (2 * r^2) % r:by ring_nf
... = ((x+y)*r+(y+1)) % r: by rw h
... = ((y+1)+(x+y)*r) % r: by ring_nf
... = (y+1)%r: int.add_mul_mod_self
... = y+1 - r * ((y+1)/r): int.mod_def (y+1) r,
have hy1: y+1 = r * ((y+1)/r), from calc
y+1 = (y+1-r*((y+1)/r)) + r*((y+1)/r): by ring
... = 0 + r*((y+1)/r): by rw hz3
... = r*((y+1)/r): by ring,
have r ∣ (y+1), from exists.intro ((y+1)/r) hy1, -- note it's \ mid not just |
have hQ: 0 < (y+1)/r, from int.div_pos_of_pos_of_dvd hyy hltr this,
have h_Q:0 ≤ (y+1)/r, from le_of_lt hQ,
have hone: 1 ≤ (y+1)/r, from int.add_one_le_of_lt hQ,
have 1 = (y+1)/r ∨ 2 ≤ (y+1)/r, from eq_or_lt_of_le hone,
-- First OR statement
have r = y+1 ∨ r*2 ≤ y+1, from or.elim this (
λ h11: 1 = (y+1)/r,
or.inl (calc r = r * 1 : by ring
... = r * ((y+1)/r): congr_arg _ h11
... = y+1: hy1.symm)) (
λ h2: 2 ≤ (y+1)/r,
or.inr (calc r*2 = 2*r: by ring
... ≤ ((y+1)/r) * r: mul_le_mul h2 (le_refl r) hltr h_Q
... = r * ((y+1)/r): by ring
... = y+1: hy1.symm)
),
-- Second OR statement
have y = r-1 ∨ 2*r-1 ≤ y, from or.elim this (
λ H: r = y+1, or.inl (calc y = (y+1)-1: by ring
... = r-1: by rw H)) (
λ H: r*2 ≤ y+1, or.inr (calc
2*r-1 = (r*2) + (-1): by ring
... ≤ (y+1) + (-1): int.add_le_add_right H (-1)
... = y: by ring)
), -- Now finish the proof
or.elim this (-- Easy case
λ hyr : y = r - 1,
have hurr: r*r = x*r, from calc
r*r = (2*r^2) - r*r : by ring
... = x*r : by {rw h,rw hyr,ring,},
have hrx: r = x, from (mul_left_inj' hrn).mp hurr,
congr_arg2 (λ (x y : ℤ), (x, y)) hrx.symm hyr
)
(λ hry:2*r-1≤ y,-- Contradiction case
have hok:(2*r-1)* (r+1) ≤ y*(r+1), from mul_le_mul hry (le_refl (r+1)) hr1 hy,
have 2 * r^2 < 2 * r^2, from calc
2 * r^2 < 2 * r^2 + r: lt_add_of_pos_right (2 * r^2) hr
... = (2*r-1)* (r+1)+1: by ring
... ≤ y * (r+1)+1: add_le_add hok (le_refl 1)
... = y * r + (y + 1): by ring
... ≤ (x+y)*r+(y+1): add_le_add h6 (le_refl (y+1))
... = 2 * r^2: h.symm,
false.elim ((lt_self_iff_false (2*r^2)).mp this)),
iff.intro h1 h2 |
import numpy as np
import time
from numba import jit, prange
import matplotlib.pyplot as plt
from matplotlib import gridspec
from ..util import (
f_SRM,
eta_SRM,
eta_SRM_no_vector,
kappa_interaction,
h_exp_update,
h_erlang_update,
)
from ..QR import find_cutoff
def quasi_renewal_pde(
time_end,
dt,
Lambda,
Gamma,
c=1,
Delta=1,
theta=0,
interaction=0,
lambda_kappa=20,
base_I=0,
I_ext_time=0,
I_ext=0,
epsilon_c=1e-2,
use_LambdaGamma=False,
a_cutoff=5,
A_t0=0,
rho0=0,
h_t0=0,
kappa_type="exp",
):
""""""
# Check if model will not explode
if np.sum(Gamma) > 0:
print(f"Model will explode with {Gamma=}. Cannot performe QR.")
return [], [], 0
Gamma = np.array(Gamma)
Lambda = np.array(Lambda)
if use_LambdaGamma:
Gamma = Gamma * Lambda
# Find cutoff tau_c
tau_c = find_cutoff(0, 100, dt, Lambda, Gamma, epsilon_c)
tau_c = np.round(tau_c, decimals=int(-np.log10(dt)))
# print(f"Calculated tau_c: {tau_c}")
tau_c = a_cutoff
# Need dt = da
a_grid_size = int(tau_c / dt)
a_grid = np.linspace(0, tau_c, a_grid_size)
steps = int(time_end / dt)
dim = Gamma.shape[0]
# Init vectors
ts = np.linspace(0, time_end, steps)
rho_t = np.zeros((steps, a_grid_size))
A_t = np.zeros(steps)
h_t = np.zeros(steps)
k_t = np.zeros(steps)
rho_t[0, 0] = 1 / dt
h_t[0] = h_t0
# A_t[0] = rho_t[0, 0]
# if A_t0:
# A_t[0] = A_t0
if isinstance(rho0, np.ndarray):
rho_t[0] = rho0
K = a_grid_size
da = dt
J = interaction
c = (c * 1.0) * np.exp(-theta / Delta)
@jit(nopython=True, cache=True)
def optimized(rho_t, h_t, k_t, A_t):
Ks = np.arange(K)
exp_eta = np.exp(1 / Delta * eta_SRM(dt * Ks, Gamma, Lambda))
y = np.exp(1 / Delta * eta_SRM(np.linspace(0, 2 * tau_c, 2 * (K + 1)), Gamma, Lambda)) - 1
# x = eta_SRM(np.linspace(0, 2 * tau_c, 2 * K), Gamma, Lambda)
for n in range(0, steps - 1):
x_fixed = I_ext + base_I if I_ext_time < dt * (n + 1) else base_I
# Calculate f~(t|t - a)
# f[0] = f~(t_n|t_n), f[1] = f~(t_n | t_{n-1}), ..
f = np.zeros(K)
t_n = n * dt
sup = n - Ks
inf = n - Ks - K
integral = np.zeros(K)
# int2 = np.zeros(K)
for k in range(K):
t_s_idx = np.arange(max(0, inf[k]), sup[k])
idx = k + np.arange(len(t_s_idx))
integral[k] = np.sum(y[idx][::-1] * A_t[t_s_idx] * dt)
f = c * exp_eta * np.exp(1 / Delta * h_t[n] + integral)
# firing_prob = np.clip(f * da, 0, 1)
firing_prob = 1 - np.exp(-f * da)
A_t[n] = np.sum(firing_prob * rho_t[n])
h_t[n + 1] = h_t[n] + lambda_kappa * dt * (J * A_t[n] + x_fixed - h_t[n])
# Next step
# h_t[n + 1] = h_t[n] + dt * lambda_kappa * (-h_t[n] + (A_t[n] * J + x_fixed))
# Mass loss
mass_transfer = rho_t[n] * firing_prob
# rho_t[n + 1] -= mass_transfer
lass_cell_mass = rho_t[n, -1] # Last cell necessarely spikes
# Linear transport
rho_t[n + 1, 1:] = rho_t[n, :-1] - mass_transfer[:-1]
# Mass insertion
rho_t[n + 1, 0] = np.sum(mass_transfer) + lass_cell_mass
return rho_t, h_t, A_t
rho_t, h_t, A_t = optimized(rho_t, h_t, k_t, A_t)
mass_conservation = np.sum(rho_t * dt, axis=-1)
activity = rho_t[:, 0]
return ts, a_grid, rho_t, h_t, mass_conservation, activity |
function out = spm_dicom_convert(Headers,opts,RootDirectory,format,OutputDirectory,meta)
% Convert DICOM images into something that SPM can use (e.g. NIfTI)
% FORMAT out = spm_dicom_convert(Headers,opts,RootDirectory,format,OutputDirectory)
% Inputs:
% Headers - a cell array of DICOM headers from spm_dicom_headers
% opts - options:
% 'all' - all DICOM files [default]
% 'mosaic' - the mosaic images
% 'standard' - standard DICOM files
% 'spect' - SIEMENS Spectroscopy DICOMs (some formats only)
% This will write out a 5D NIFTI containing real
% and imaginary part of the spectroscopy time
% points at the position of spectroscopy voxel(s)
% 'raw' - convert raw FIDs (not implemented)
% RootDirectory - 'flat' - do not produce file tree [default]
% With all other options, files will be sorted into
% directories according to their sequence/protocol names:
% 'date_time' - Place files under ./<StudyDate-StudyTime>
% 'patid' - Place files under ./<PatID>
% 'patid_date' - Place files under ./<PatID-StudyDate>
% 'series' - Place files in series folders, without
% creating patient folders
% format - output format:
% 'nii' - Single file NIfTI format [default]
% 'img' - Two file (Headers+img) NIfTI format
% All images will contain a single 3D dataset, 4D images will
% not be created.
% OutputDirectory - output directory name [default: pwd]
% meta - save metadata as sidecar JSON file [default: false]
%
% Output:
% out - a struct with a single field .files. out.files contains a
% cellstring with filenames of created files. If no files are
% created, a cell with an empty string {''} is returned.
%__________________________________________________________________________
% Copyright (C) 2002-2019 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dicom_convert.m 7714 2019-11-26 11:25:50Z spm $
%-Input parameters
%--------------------------------------------------------------------------
if nargin<2, opts = 'all'; end
if nargin<3, RootDirectory = 'flat'; end
if nargin<4, format = spm_get_defaults('images.format'); end
if nargin<5, OutputDirectory = pwd; end
if nargin<6, meta = false; end
%-Select files
%--------------------------------------------------------------------------
[images, other] = SelectTomographicImages(Headers);
[multiframe,images] = SelectMultiframe(images);
[spect, guff] = SelectSpectroscopyImages(other);
[mosaic, standard] = SelectMosaicImages(images);
[standard, guff] = SelectLastGuff(standard, guff);
if ~isempty(guff)
warning('spm:dicom','%d files could not be converted from DICOM.', numel(guff));
end
%-Convert files
%--------------------------------------------------------------------------
fmos = {};
fstd = {};
fspe = {};
fmul = {};
if (strcmp(opts,'all') || strcmp(opts,'mosaic')) && ~isempty(mosaic)
fmos = ConvertMosaic(mosaic,RootDirectory,format,OutputDirectory,meta);
end
if (strcmp(opts,'all') || strcmp(opts,'standard')) && ~isempty(standard)
fstd = ConvertStandard(standard,RootDirectory,format,OutputDirectory,meta);
end
if (strcmp(opts,'all') || strcmp(opts,'spect')) && ~isempty(spect)
fspe = ConvertSpectroscopy(spect,RootDirectory,format,OutputDirectory,meta);
end
if (strcmp(opts,'all') || strcmp(opts,'multiframe')) && ~isempty(multiframe)
fmul = ConvertMultiframes(multiframe,RootDirectory,format,OutputDirectory,meta);
end
out.files = [fmos(:); fstd(:); fspe(:); fmul(:)];
if isempty(out.files)
out.files = {''};
end
%==========================================================================
% function fnames = ConvertMosaic(Headers,RootDirectory,format,OutputDirectory,meta)
%==========================================================================
function fnames = ConvertMosaic(Headers,RootDirectory,format,OutputDirectory,meta)
spm_progress_bar('Init',length(Headers),'Writing Mosaic', 'Files written');
fnames = cell(length(Headers),1);
for i=1:length(Headers)
% Output filename
%----------------------------------------------------------------------
fnames{i} = getfilelocation(Headers{i}, RootDirectory, 'f', format, OutputDirectory);
% Image dimensions and data
%----------------------------------------------------------------------
nc = Headers{i}.Columns;
nr = Headers{i}.Rows;
dim = [0 0 0];
dim(3) = ReadNumberOfImagesInMosaic(Headers{i});
np = [nc nr]/ceil(sqrt(dim(3)));
dim(1:2) = np;
if ~all(np==floor(np))
warning('spm:dicom','%s: dimension problem [Num Images=%d, Num Cols=%d, Num Rows=%d].',...
Headers{i}.Filename,dim(3), nc,nr);
continue
end
% Apparently, this is not the right way of doing it.
%np = ReadAcquisitionMatrixText(Headers{i});
%if rem(nc, np(1)) || rem(nr, np(2)),
% warning('spm:dicom','%s: %dx%d wont fit into %dx%d.',Headers{i}.Filename,...
% np(1), np(2), nc,nr);
% return;
%end;
%dim = [np ReadNumberOfImagesInMosaic(Headers{i})];
mosaic = ReadImageData(Headers{i});
volume = zeros(dim);
snnz = zeros(dim(3), 1);
for j=1:dim(3)
img = mosaic((1:np(1))+np(1)*rem(j-1,nc/np(1)), (np(2):-1:1)+np(2)*floor((j-1)/(nc/np(1))));
snnz(j) = nnz(img) > 0;
volume(:,:,j) = img;
end
d3 = find(snnz, 1, 'last');
if ~isempty(d3)
dim(3) = d3;
volume = volume(:,:,1:dim(3));
end
dt = DetermineDatatype(Headers{1});
% Orientation information
%----------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
AnalyzeToDicom = [diag([1 -1 1]) [0 (dim(2)-1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];
vox = [Headers{i}.PixelSpacing(:); Headers{i}.SpacingBetweenSlices];
pos = Headers{i}.ImagePositionPatient(:);
orient = reshape(Headers{i}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
% The image position vector is not correct. In dicom this vector points to
% the upper left corner of the image. Perhaps it is unlucky that this is
% calculated in the syngo software from the vector pointing to the center of
% the slice (keep in mind: upper left slice) with the enlarged FoV.
DicomToPatient = [orient*diag(vox) pos ; 0 0 0 1];
truepos = DicomToPatient *[(size(mosaic)-dim(1:2))/2 0 1]';
DicomToPatient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];
PatientToTal = diag([-1 -1 1 1]);
mat = PatientToTal*DicomToPatient*AnalyzeToDicom;
% Maybe flip the image depending on SliceNormalVector from 0029,1010
%----------------------------------------------------------------------
SliceNormalVector = ReadSliceNormalVector(Headers{i});
if det([reshape(Headers{i}.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0
volume = volume(:,:,end:-1:1);
mat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];
end
% Possibly useful information
%----------------------------------------------------------------------
if CheckFields(Headers{i},'AcquisitionTime','MagneticFieldStrength',...
'MRAcquisitionType','ScanningSequence','RepetitionTime',...
'EchoTime','FlipAngle','AcquisitionDate')
tim = datevec(Headers{i}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g Mosaic',...
Headers{i}.MagneticFieldStrength, Headers{i}.MRAcquisitionType,...
deblank(Headers{i}.ScanningSequence),...
Headers{i}.RepetitionTime,Headers{i}.EchoTime,Headers{i}.FlipAngle,...
datestr(Headers{i}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = Headers{1}.Modality;
end
if ~true % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
volume = flipud(volume);
end
% Note that data are no longer scaled by the maximum amount.
% This may lead to rounding errors in smoothed data, but it
% will get around other problems.
RescaleSlope = 1;
RescaleIntercept = 0;
if isfield(Headers{i},'RescaleSlope')
RescaleSlope = Headers{i}.RescaleSlope;
end
if isfield(Headers{i},'RescaleIntercept')
RescaleIntercept = Headers{i}.RescaleIntercept;
end
Nii = nifti;
Nii.dat = file_array(fnames{i},dim,dt,0,RescaleSlope,RescaleIntercept);
Nii.mat = mat;
Nii.mat0 = mat;
Nii.mat_intent = 'Scanner';
Nii.mat0_intent = 'Scanner';
Nii.descrip = descrip;
create(Nii);
if meta
Nii = spm_dicom_metadata(Nii,Headers{i});
end
% Write the data unscaled
dat = Nii.dat;
dat.scl_slope = [];
dat.scl_inter = [];
% write out volume at once - see spm_write_plane.m for performance comments
dat(:,:,:) = volume;
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
%==========================================================================
% function fnames = ConvertStandard(Headers,RootDirectory,format,OutputDirectory,meta)
%==========================================================================
function fnames = ConvertStandard(Headers,RootDirectory,format,OutputDirectory,meta)
[Headers,dist] = SortIntoVolumes(Headers);
fnames = cell(length(Headers),1);
for i=1:length(Headers)
fnames{i} = WriteVolume(Headers{i},RootDirectory,format,OutputDirectory,dist{i},meta);
end
%==========================================================================
% function [SortedHeaders,dist] = SortIntoVolumes(Headers)
%==========================================================================
function [SortedHeaders,dist] = SortIntoVolumes(Headers)
%
% First of all, sort into volumes based on relevant
% fields in the header.
%
SortedHeaders{1}{1} = Headers{1};
for i=2:length(Headers)
%orient = reshape(Headers{i}.ImageOrientationPatient,[3 2]);
%xy1 = Headers{i}.ImagePositionPatient(:)*orient;
match = 0;
if isfield(Headers{i},'CSAImageHeaderInfo') && isfield(Headers{i}.CSAImageHeaderInfo,'name')
ice1 = sscanf( ...
strrep(GetNumaris4Val(Headers{i}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
dimsel = logical([1 1 1 1 1 1 0 0 1]);
else
ice1 = [];
end
for j=1:length(SortedHeaders)
%orient = reshape(SortedHeaders{j}{1}.ImageOrientationPatient,[3 2]);
%xy2 = SortedHeaders{j}{1}.ImagePositionPatient(:)*orient;
% This line is a fudge because of some problematic data that Bogdan,
% Cynthia and Stefan were trying to convert. I hope it won't cause
% problems for others -JA
% dist2 = sum((xy1-xy2).^2);
dist2 = 0;
if strcmp(Headers{i}.Modality,'CT') && ...
strcmp(SortedHeaders{j}{1}.Modality,'CT') % Our CT seems to have shears in slice positions
dist2 = 0;
end
if ~isempty(ice1) && isfield(SortedHeaders{j}{1},'CSAImageHeaderInfo') && numel(SortedHeaders{j}{1}.CSAImageHeaderInfo)>=1 && isfield(SortedHeaders{j}{1}.CSAImageHeaderInfo(1),'name')
% Replace 'X' in ICE_Dims by '-1'
ice2 = sscanf( ...
strrep(GetNumaris4Val(SortedHeaders{j}{1}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
if ~isempty(ice2)
identical_ice_dims=all(ice1(dimsel)==ice2(dimsel));
else
identical_ice_dims = 0; % have ice1 but not ice2, ->
% something must be different
end
else
identical_ice_dims = 1; % No way of knowing if there is no CSAImageHeaderInfo
end
try
match = Headers{i}.SeriesNumber == SortedHeaders{j}{1}.SeriesNumber &&...
Headers{i}.Rows == SortedHeaders{j}{1}.Rows &&...
Headers{i}.Columns == SortedHeaders{j}{1}.Columns &&...
sum((Headers{i}.ImageOrientationPatient - SortedHeaders{j}{1}.ImageOrientationPatient).^2)<1e-4 &&...
sum((Headers{i}.PixelSpacing - SortedHeaders{j}{1}.PixelSpacing).^2)<1e-4 && ...
identical_ice_dims && dist2<1e-3;
%if (Headers{i}.AcquisitionNumber ~= Headers{i}.InstanceNumber) || ...
% (SortedHeaders{j}{1}.AcquisitionNumber ~= SortedHeaders{j}{1}.InstanceNumber)
% match = match && (Headers{i}.AcquisitionNumber == SortedHeaders{j}{1}.AcquisitionNumber)
%end
% For raw image data, tell apart real/complex or phase/magnitude
if isfield(Headers{i},'ImageType') && isfield(SortedHeaders{j}{1}, 'ImageType')
match = match && strcmp(Headers{i}.ImageType, SortedHeaders{j}{1}.ImageType);
end
if isfield(Headers{i},'SequenceName') && isfield(SortedHeaders{j}{1}, 'SequenceName')
match = match && strcmp(Headers{i}.SequenceName, SortedHeaders{j}{1}.SequenceName);
end
if isfield(Headers{i},'SeriesInstanceUID') && isfield(SortedHeaders{j}{1}, 'SeriesInstanceUID')
match = match && strcmp(Headers{i}.SeriesInstanceUID, SortedHeaders{j}{1}.SeriesInstanceUID);
end
if isfield(Headers{i},'EchoNumbers') && isfield(SortedHeaders{j}{1}, 'EchoNumbers')
match = match && Headers{i}.EchoNumbers == SortedHeaders{j}{1}.EchoNumbers;
end
if isfield(Headers{i}, 'GE_ImageType') && numel( Headers{i}.GE_ImageType)==1 && ...
isfield(SortedHeaders{j}{1}, 'GE_ImageType') && numel(SortedHeaders{j}{1}.GE_ImageType)==1
match = match && Headers{i}.GE_ImageType == SortedHeaders{j}{1}.GE_ImageType;
end
catch
match = 0;
end
if match
SortedHeaders{j}{end+1} = Headers{i};
break;
end
end
if ~match
SortedHeaders{end+1}{1} = Headers{i};
end
end
%
% Secondly, sort volumes into ascending/descending
% slices depending on .ImageOrientationPatient field.
%
SortedHeaders2 = {};
for j=1:length(SortedHeaders)
orient = reshape(SortedHeaders{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end
z = zeros(length(SortedHeaders{j}),1);
for i=1:length(SortedHeaders{j})
z(i) = SortedHeaders{j}{i}.ImagePositionPatient(:)'*proj;
end
[z,index] = sort(z);
SortedHeaders{j} = SortedHeaders{j}(index);
if length(SortedHeaders{j})>1
% dist = diff(z);
if any(diff(z)==0)
tmp = SortIntoVolumesAgain(SortedHeaders{j});
SortedHeaders{j} = tmp{1};
SortedHeaders2 = {SortedHeaders2{:} tmp{2:end}};
end
end
end
SortedHeaders = {SortedHeaders{:} SortedHeaders2{:}};
dist = cell(length(SortedHeaders),1);
for j=1:length(SortedHeaders)
if length(SortedHeaders{j})>1
orient = reshape(SortedHeaders{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end
z = zeros(length(SortedHeaders{j}),1);
for i=1:length(SortedHeaders{j})
z(i) = SortedHeaders{j}{i}.ImagePositionPatient(:)'*proj;
end
dist{j} = diff(sort(z));
if sum((dist{j}-mean(dist{j})).^2)/length(dist{j})>1e-4
fprintf('***************************************************\n');
fprintf('* VARIABLE SLICE SPACING *\n');
fprintf('* This may be due to missing DICOM files. *\n');
PatientID = 'anon';
if CheckFields(SortedHeaders{j}{1}, 'PatientID'), PatientID = deblank(SortedHeaders{j}{1}.PatientID); end
if CheckFields(SortedHeaders{j}{1}, 'SeriesNumber', 'AcquisitionNumber', 'InstanceNumber')
fprintf('* %s / %d / %d / %d \n',...
PatientID, SortedHeaders{j}{1}.SeriesNumber, ...
SortedHeaders{j}{1}.AcquisitionNumber, SortedHeaders{j}{1}.InstanceNumber);
fprintf('* *\n');
end
fprintf('* %20.4g *\n', dist{j});
fprintf('***************************************************\n');
end
end
end
%==========================================================================
% function SortedHeaders = SortIntoVolumesAgain(Headers)
%==========================================================================
function SortedHeaders = SortIntoVolumesAgain(Headers)
if ~isfield(Headers{1},'InstanceNumber')
fprintf('***************************************************\n');
fprintf('* The slices may be all mixed up and the data *\n');
fprintf('* not really usable. Talk to your physicists *\n');
fprintf('* about this. *\n');
fprintf('***************************************************\n');
SortedHeaders = {Headers};
return;
end
fprintf('***************************************************\n');
fprintf('* The AcquisitionNumber counter does not appear *\n');
fprintf('* to be changing from one volume to another. *\n');
fprintf('* Another possible explanation is that the same *\n');
fprintf('* DICOM slices are used multiple times. *\n');
%fprintf('* Talk to your MR sequence developers or scanner *\n');
%fprintf('* supplier to have this fixed. *\n');
fprintf('* The conversion is having to guess how slices *\n');
fprintf('* should be arranged into volumes. *\n');
PatientID = 'anon';
if CheckFields(Headers{1},'PatientID'), PatientID = deblank(Headers{1}.PatientID); end
if CheckFields(Headers{1},'SeriesNumber','AcquisitionNumber')
fprintf('* %s / %d / %d\n',...
PatientID, Headers{1}.SeriesNumber, ...
Headers{1}.AcquisitionNumber);
end
fprintf('***************************************************\n');
z = zeros(length(Headers),1);
t = zeros(length(Headers),1);
d = zeros(length(Headers),1);
orient = reshape(Headers{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end
for i=1:length(Headers)
z(i) = Headers{i}.ImagePositionPatient(:)'*proj;
t(i) = Headers{i}.InstanceNumber;
end
% msg = 0;
[t,index] = sort(t);
Headers = Headers(index);
z = z(index);
msk = find(diff(t)==0);
if any(msk)
% fprintf('***************************************************\n');
% fprintf('* These files have the same InstanceNumber: *\n');
% for i=1:length(msk),
% [tmp,nam1,ext1] = fileparts(Headers{msk(i)}.Filename);
% [tmp,nam2,ext2] = fileparts(Headers{msk(i)+1}.Filename);
% fprintf('* %s%s = %s%s (%d)\n', nam1,ext1,nam2,ext2, Headers{msk(i)}.InstanceNumber);
% end;
% fprintf('***************************************************\n');
index = [true ; diff(t)~=0];
t = t(index);
z = z(index);
d = d(index);
Headers = Headers(index);
end
%if any(diff(sort(t))~=1), msg = 1; end;
[z,index] = sort(z);
Headers = Headers(index);
t = t(index);
SortedHeaders = {};
while ~all(d)
i = find(~d);
i = i(1);
i = find(z==z(i));
[t(i),si] = sort(t(i));
Headers(i) = Headers(i(si));
for i1=1:length(i)
if length(SortedHeaders)<i1, SortedHeaders{i1} = {}; end
SortedHeaders{i1} = {SortedHeaders{i1}{:} Headers{i(i1)}};
end
d(i) = 1;
end
msg = 0;
len = length(SortedHeaders{1});
for i=2:length(SortedHeaders)
if length(SortedHeaders{i}) ~= len
msg = 1;
break;
end
end
if msg
fprintf('***************************************************\n');
fprintf('* There are missing DICOM files, so the the *\n');
fprintf('* resulting volumes may be messed up. *\n');
PatientID = 'anon';
if CheckFields(Headers{1},'PatientID'), PatientID = deblank(Headers{1}.PatientID); end
if CheckFields(Headers{1},'SeriesNumber','AcquisitionNumber')
fprintf('* %s / %d / %d\n',...
PatientID, Headers{1}.SeriesNumber, ...
Headers{1}.AcquisitionNumber);
end
fprintf('***************************************************\n');
end
%==========================================================================
% function fname = WriteVolume(Headers, RootDirectory, format, OutputDirectory, dist, meta)
%==========================================================================
function fname = WriteVolume(Headers, RootDirectory, format, OutputDirectory, dist, meta)
% Output filename
%--------------------------------------------------------------------------
fname = getfilelocation(Headers{1}, RootDirectory,'s',format,OutputDirectory);
% Image dimensions
%--------------------------------------------------------------------------
nc = Headers{1}.Columns;
nr = Headers{1}.Rows;
if length(Headers) == 1 && isfield(Headers{1},'NumberOfFrames') && Headers{1}.NumberOfFrames > 1
if isfield(Headers{1},'ImagePositionPatient') &&...
isfield(Headers{1},'ImageOrientationPatient') &&...
isfield(Headers{1},'SliceThickness') &&...
isfield(Headers{1},'StartOfPixelData') &&...
isfield(Headers{1},'SizeOfPixelData')
orient = reshape(Headers{1}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
slicevec = orient(:,3);
Headers_temp = cell(1,Headers{1}.NumberOfFrames); % alternative: NumberofSlices
Headers_temp{1} = Headers{1};
Headers_temp{1}.SizeOfPixelData = Headers{1}.SizeOfPixelData / Headers{1}.NumberOfFrames;
for sn = 2 : Headers{1}.NumberOfFrames
Headers_temp{sn} = Headers{1};
Headers_temp{sn}.ImagePositionPatient = Headers{1}.ImagePositionPatient + (sn-1) * Headers{1}.SliceThickness * slicevec;
Headers_temp{sn}.SizeOfPixelData = Headers_temp{1}.SizeOfPixelData;
Headers_temp{sn}.StartOfPixelData = Headers{1}.StartOfPixelData + (sn-1) * Headers_temp{1}.SizeOfPixelData;
end
Headers = Headers_temp;
else
error('spm_dicom_convert:WriteVolume','TAGS missing in DICOM file.');
end
end
dim = [nc nr length(Headers)];
dt = DetermineDatatype(Headers{1});
% Orientation information
%--------------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
AnalyzeToDicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
PatientToTal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
R = [reshape(Headers{1}.ImageOrientationPatient,3,2)*diag(Headers{1}.PixelSpacing); 0 0];
x1 = [1;1;1;1];
y1 = [Headers{1}.ImagePositionPatient(:); 1];
if length(Headers)>1
x2 = [1;1;dim(3); 1];
y2 = [Headers{end}.ImagePositionPatient(:); 1];
else
orient = reshape(Headers{1}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
if CheckFields(Headers{1},'SliceThickness')
z = Headers{1}.SliceThickness;
else
z = 1;
end
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
DicomToPatient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = PatientToTal*DicomToPatient*AnalyzeToDicom;
% Possibly useful information
%--------------------------------------------------------------------------
if CheckFields(Headers{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate')
if isfield(Headers{1},'ScanOptions')
ScanOptions = Headers{1}.ScanOptions;
else
ScanOptions = 'no';
end
tim = datevec(Headers{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg/SO=%s %s %d:%d:%.5g',...
Headers{1}.MagneticFieldStrength, Headers{1}.MRAcquisitionType,...
deblank(Headers{1}.ScanningSequence),...
Headers{1}.RepetitionTime,Headers{1}.EchoTime,Headers{1}.FlipAngle,...
ScanOptions,...
datestr(Headers{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = Headers{1}.Modality;
end
if ~true % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end
% Write the image volume
%--------------------------------------------------------------------------
spm_progress_bar('Init',length(Headers),['Writing ' fname], 'Planes written');
pinfos = [ones(length(Headers),1) zeros(length(Headers),1)];
for i=1:length(Headers)
if isfield(Headers{i},'RescaleSlope'), pinfos(i,1) = Headers{i}.RescaleSlope; end
if isfield(Headers{i},'RescaleIntercept'), pinfos(i,2) = Headers{i}.RescaleIntercept; end
% Philips do things differently. The following is for using their scales instead.
% Chenevert, Thomas L., et al. "Errors in quantitative image analysis due to
% platform-dependent image scaling." Translational oncology 7.1 (2014): 65-71.
if isfield(Headers{i},'MRScaleSlope'), pinfos(i,1) = 1/Headers{i}.MRScaleSlope; end
if isfield(Headers{i},'MRScaleIntercept'), pinfos(i,2) = -Headers{i}.MRScaleIntercept*pinfos(i,1); end
end
if any(any(diff(pinfos,1)))
% Ensure random numbers are reproducible (see later)
% when intensities are dithered to prevent aliasing effects.
rand('state',0);
end
volume = zeros(dim);
for i=1:length(Headers)
plane = ReadImageData(Headers{i});
if any(any(diff(pinfos,1)))
% This is to prevent aliasing effects in any subsequent histograms
% of the data (eg for mutual information coregistration).
% It's a bit inelegant, but probably necessary for when slices are
% individually rescaled.
plane = double(plane) + rand(size(plane)) - 0.5;
end
if pinfos(i,1)~=1, plane = plane*pinfos(i,1); end
if pinfos(i,2)~=0, plane = plane+pinfos(i,2); end
plane = fliplr(plane);
if ~true, plane = flipud(plane); end % LEFT-HANDED STORAGE
volume(:,:,i) = plane;
spm_progress_bar('Set',i);
end
if ~any(any(diff(pinfos,1)))
% Same slopes and intercepts for all slices
pinfo = pinfos(1,:);
else
% Variable slopes and intercept (maybe PET/SPECT)
mx = max(volume(:));
mn = min(volume(:));
% Slope and Intercept
% 32767*pinfo(1) + pinfo(2) = mx
% -32768*pinfo(1) + pinfo(2) = mn
% pinfo = ([32767 1; -32768 1]\[mx; mn])';
% Slope only
dt = 'int16-be';
pinfo = [max(mx/32767,-mn/32768) 0];
end
Nii = nifti;
Nii.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
Nii.mat = mat;
Nii.mat0 = mat;
Nii.mat_intent = 'Scanner';
Nii.mat0_intent = 'Scanner';
Nii.descrip = descrip;
create(Nii);
if meta
Nii = spm_dicom_metadata(Nii, Headers{1});
end
Nii.dat(:,:,:) = volume;
spm_progress_bar('Clear');
if sum((dist-mean(dist)).^2)/length(dist)>1e-4
% Adjusting for variable slice thickness
% This is sometimes required for CT data because these scans are often
% acquired with a gantry tilt and thinner slices near the brain stem.
% If uncorrected, the resulting NIfTI image can appear distorted. Here,
% the image is resampled to compensate for this effect.
%----------------------------------------------------------------------
fprintf('***************************************************\n');
fprintf('* Adjusting for variable slice thickness. *\n');
fprintf('***************************************************\n');
ovx = sqrt(sum(mat(1:3,1:3).^2));
nvx = [ovx(1:2) max(min(dist),1)]; % Set new slice thickness in thick-slice direction to minimum of dist
Nii = nifti(fname);
img = Nii.dat(:,:,:);
d = size(img);
csdist = cumsum(dist);
csdist = [1; 1 + csdist];
x = zeros([d(1:3) 3],'single');
[x1,x2] = meshgrid(single(1:d(2)),single(1:d(1)));
for i=1:d(3)
x(:,:,i,1) = x1;
x(:,:,i,2) = x2;
x(:,:,i,3) = csdist(i);
end
X = x(:,:,:,1);
Y = x(:,:,:,2);
Z = x(:,:,:,3);
clear x
if ~(csdist(end) == floor(csdist(end)))
[Xq,Yq,Zq] = meshgrid(single(1:d(2)),single(1:d(1)),single([1:nvx(3):csdist(end) csdist(end)]));
else
[Xq,Yq,Zq] = meshgrid(single(1:d(2)),single(1:d(1)),single(1:nvx(3):csdist(end)));
end
img = interp3(X,Y,Z,img,Xq,Yq,Zq,'linear');
ndim = size(img);
% Adjust orientation matrix
D = diag([ovx./nvx 1]);
mat = mat/D;
N = nifti;
N.dat = file_array(fname,ndim,dt,0,pinfo(1),pinfo(2));
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
create(N);
N.dat(:,:,:) = img;
end
%==========================================================================
% function fnames = ConvertSpectroscopy(Headers, RootDirectory, format, OutputDirectory, meta)
%==========================================================================
function fnames = ConvertSpectroscopy(Headers, RootDirectory, format, OutputDirectory, meta)
fnames = cell(length(Headers),1);
for i=1:length(Headers)
fnames{i} = WriteSpectroscopyVolume(Headers(i), RootDirectory, format, OutputDirectory, meta);
end
%==========================================================================
% function fname = WriteSpectroscopyVolume(Headers, RootDirectory, format, OutputDirectory, meta)
%==========================================================================
function fname = WriteSpectroscopyVolume(Headers, RootDirectory, format, OutputDirectory, meta)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(Headers{1}, RootDirectory,'S',format,OutputDirectory);
% private field to use - depends on SIEMENS software version
if isfield(Headers{1}, 'CSANonImageHeaderInfoVA')
privdat = Headers{1}.CSANonImageHeaderInfoVA;
elseif isfield(Headers{1}, 'CSANonImageHeaderInfoVB')
privdat = Headers{1}.CSANonImageHeaderInfoVB;
else
disp('Don''t know how to handle these spectroscopy data');
fname = '';
return;
end
% Image dimensions
%--------------------------------------------------------------------------
nc = GetNumaris4NumVal(privdat,'Columns');
nr = GetNumaris4NumVal(privdat,'Rows');
% Guess number of timepoints in file - I don't know for sure whether this should be
% 'DataPointRows'-by-'DataPointColumns', 'SpectroscopyAcquisitionDataColumns'
% or sSpecPara.lVectorSize from SIEMENS ASCII header
% ntp = GetNumaris4NumVal(privdat,'DataPointRows')*GetNumaris4NumVal(privdat,'DataPointColumns');
ac = ReadAscconv(Headers{1});
try
ntp = ac.sSpecPara.lVectorSize;
catch
disp('Don''t know how to handle these spectroscopy data');
fname = '';
return;
end
dim = [nc nr numel(Headers) 2 ntp];
dt = spm_type('float32'); % Fixed datatype
% Orientation information
%--------------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
AnalyzeToDicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
PatientToTal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
shift_vx = [eye(4,3) [.5; .5; 0; 1]];
orient = reshape(GetNumaris4NumVal(privdat, 'ImageOrientationPatient'), [3 2]);
ps = GetNumaris4NumVal(privdat, 'PixelSpacing');
if nc*nr == 1
% Single Voxel Spectroscopy (based on the following information from SIEMENS)
%----------------------------------------------------------------------
% NOTE: Internally the position vector of the CSI matrix shows to the
% outer border of the first voxel. Therefore the position vector has to
% be corrected. (Note: The convention of Siemens spectroscopy raw data
% is in contrast to the DICOM standard where the position vector points
% to the center of the first voxel.)
%----------------------------------------------------------------------
% SIEMENS decides which definition to use based on the contents of the
% 'PixelSpacing' internal header field. If it has non-zero values,
% assume DICOM convention. If any value is zero, assume SIEMENS
% internal convention for this direction.
% Note that in SIEMENS code, there is a shift when PixelSpacing is
% zero. Here, the shift seems to be necessary when PixelSpacing is
% non-zero. This may indicate more fundamental problems with
% orientation decoding.
if ps(1) == 0 % row
ps(1) = GetNumaris4NumVal(privdat, 'VoiPhaseFoV');
shift_vx(1,4) = 0;
end
if ps(2) == 0 % col
ps(2) = GetNumaris4NumVal(privdat, 'VoiReadoutFoV');
shift_vx(2,4) = 0;
end
end
pos = GetNumaris4NumVal(privdat, 'ImagePositionPatient');
% for some reason, pixel spacing needs to be swapped
R = [orient*diag(ps([2 1])); 0 0];
x1 = [1;1;1;1];
y1 = [pos; 1];
if length(Headers)>1
error('spm_dicom_convert:spectroscopy',...
'Don''t know how to handle multislice spectroscopy data.');
else
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
z = GetNumaris4NumVal(privdat,...
'VoiThickness');
if isempty(z)
z = GetNumaris4NumVal(privdat,...
'SliceThickness');
end
if isempty(z)
warning('spm_dicom_convert:spectroscopy',...
'Can not determine voxel thickness.');
z = 1;
end
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
DicomToPatient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = patient_to_tal*DicomToPatient*shift_vx*AnalyzeToDicom;
% Possibly useful information
%--------------------------------------------------------------------------
if CheckFields(Headers{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate')
tim = datevec(Headers{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g',...
Headers{1}.MagneticFieldStrength, Headers{1}.MRAcquisitionType,...
deblank(Headers{1}.ScanningSequence),...
Headers{1}.RepetitionTime,Headers{1}.EchoTime,Headers{1}.FlipAngle,...
datestr(Headers{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = Headers{1}.Modality;
end
if ~true % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end
% Write the image volume
%--------------------------------------------------------------------------
Nii = nifti;
pinfo = [1 0];
if isfield(Headers{1},'RescaleSlope'), pinfo(1) = Headers{1}.RescaleSlope; end
if isfield(Headers{1},'RescaleIntercept'), pinfo(2) = Headers{1}.RescaleIntercept; end
% Philips do things differently. The following is for using their scales instead.
% Chenevert, Thomas L., et al. "Errors in quantitative image analysis due to
% platform-dependent image scaling." Translational oncology 7.1 (2014): 65-71.
if isfield(Headers{1},'MRScaleSlope'), pinfo(1) = 1/Headers{1}.MRScaleSlope; end
if isfield(Headers{1},'MRScaleIntercept'), pinfo(2) = -Headers{1}.MRScaleIntercept*pinfo(1); end
Nii.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
Nii.mat = mat;
Nii.mat0 = mat;
Nii.mat_intent = 'Scanner';
Nii.mat0_intent = 'Scanner';
Nii.descrip = descrip;
% Store LCMODEL control/raw info in Nii.extras
Nii.extras = struct('MagneticFieldStrength', GetNumaris4NumVal(privdat,'MagneticFieldStrength'),...
'TransmitterReferenceAmplitude', GetNumaris4NumVal(privdat,'TransmitterReferenceAmplitude'),...
'ImagingFrequency', GetNumaris4NumVal(privdat,'ImagingFrequency'),...
'EchoTime', GetNumaris4NumVal(privdat,'EchoTime'),...
'RealDwellTime', GetNumaris4NumVal(privdat,'RealDwellTime'));
create(Nii);
if meta
Nii = spm_dicom_metadata(Nii,Headers{1});
end
% Read data, swap dimensions
data = permute(reshape(ReadSpectData(Headers{1},ntp),dim([4 5 1 2 3])), ...
[3 4 5 1 2]);
% plane = fliplr(plane);
Nii.dat(:,:,:,:,:) = data;
%==========================================================================
% function [images,guff] = SelectTomographicImages(Headers)
%==========================================================================
function [images,guff] = SelectTomographicImages(Headers)
images = {};
guff = {};
for i=1:length(Headers)
if ~CheckFields(Headers{i},'Modality') || ...
~(strcmp(Headers{i}.Modality,'MR') || ...
strcmp(Headers{i}.Modality,'PT') || ...
strcmp(Headers{i}.Modality,'NM') || ...
strcmp(Headers{i}.Modality,'CT'))
if CheckFields(Headers{i},'Modality')
fprintf('File "%s" can not be converted because it is of type "%s", which is not MRI, CT, NM or PET.\n', ...
Headers{i}.Filename, Headers{i}.Modality);
else
fprintf('File "%s" can not be converted because it does not encode an image.\n', Headers{i}.Filename);
end
guff = [guff(:)',Headers(i)];
elseif ~CheckFields(Headers{i},'StartOfPixelData','SamplesPerPixel',...
'Rows','Columns','BitsAllocated','BitsStored','HighBit','PixelRepresentation')
fprintf('Cant find "Image Pixel" information for "%s".\n',Headers{i}.Filename);
guff = [guff(:)',Headers(i)];
elseif ~(CheckFields(Headers{i},'PixelSpacing','ImagePositionPatient','ImageOrientationPatient') ...
|| isfield(Headers{i},'CSANonImageHeaderInfoVA') || isfield(Headers{i},'CSANonImageHeaderInfoVB'))
if isfield(Headers{i},'SharedFunctionalGroupsSequence') || isfield(Headers{i},'PerFrameFunctionalGroupsSequence')
fprintf(['\n"%s" appears to be multi-frame DICOM.\n'...
'Converting these data is still experimental and has only been tested on a very small number of\n'...
'multiframe DICOM files. Feedback about problems would be appreciated - particularly if you can\n'...
'give us examples of problematic data (providing there are no subject confidentiality issues).\n\n'], Headers{i}.Filename);
images = [images(:)',Headers(i)];
else
fprintf('No "Image Plane" information for "%s".\n',Headers{i}.Filename);
guff = [guff(:)',Headers(i)];
end
elseif ~CheckFields(Headers{i},'SeriesNumber','AcquisitionNumber','InstanceNumber')
%disp(['Cant find suitable filename info for "' Headers{i}.Filename '".']);
if ~isfield(Headers{i},'SeriesNumber')
fprintf('Setting SeriesNumber to 1.\n');
Headers{i}.SeriesNumber = 1;
images = [images(:)',Headers(i)];
end
if ~isfield(Headers{i},'AcquisitionNumber')
if isfield(Headers{i},'Manufacturer') && ~isempty(strfind(upper(Headers{1}.Manufacturer), 'PHILIPS'))
% Philips oddity
if isfield(Headers{i},'InstanceNumber')
Headers{i}.AcquisitionNumber = Headers{i}.InstanceNumber;
else
fprintf('Setting AcquisitionNumber to 1.\n');
Headers{i}.AcquisitionNumber = 1;
end
else
fprintf('Setting AcquisitionNumber to 1.\n');
Headers{i}.AcquisitionNumber = 1;
end
images = [images(:)',Headers(i)];
end
if ~isfield(Headers{i},'InstanceNumber')
fprintf('Setting InstanceNumber to 1.\n');
Headers{i}.InstanceNumber = 1;
images = [images(:)',Headers(i)];
end
%elseif isfield(Headers{i},'Private_2001_105f'),
% % This field corresponds to: > Stack Sequence 2001,105F SQ VNAP, COPY
% % http://www.medical.philips.com/main/company/connectivity/mri/index.html
% % No documentation about this private field is yet available.
% disp('Cant yet convert Philips Intera DICOM.');
% guff = {guff{:},Headers{i}};
else
images = [images(:)',Headers(i)];
end
end
%==========================================================================
% function [multiframe,other] = SelectMultiframe(Headers)
%==========================================================================
function [multiframe,other] = SelectMultiframe(Headers)
multiframe = {};
other = {};
for i=1:length(Headers)
if isfield(Headers{i},'SharedFunctionalGroupsSequence') || isfield(Headers{i},'PerFrameFunctionalGroupsSequence')
multiframe = [multiframe(:)',Headers(i)];
else
other = [other(:)',Headers(i)];
end
end
%==========================================================================
% function [mosaic,standard] = SelectMosaicImages(Headers)
%==========================================================================
function [mosaic,standard] = SelectMosaicImages(Headers)
mosaic = {};
standard = {};
for i=1:length(Headers)
if ~CheckFields(Headers{i},'ImageType','CSAImageHeaderInfo') ||...
isfield(Headers{i}.CSAImageHeaderInfo,'junk') ||...
isempty(ReadAcquisitionMatrixText(Headers{i})) ||...
isempty(ReadNumberOfImagesInMosaic(Headers{i})) ||...
ReadNumberOfImagesInMosaic(Headers{i}) == 0
% NumberOfImagesInMosaic seems to be set to zero for pseudo images
% containing e.g. online-fMRI design matrices, don't treat them as
% mosaics
standard = [standard, Headers(i)];
else
mosaic = [mosaic, Headers(i)];
end
end
%==========================================================================
% function [spect,images] = SelectSpectroscopyImages(Headers)
%==========================================================================
function [spect,images] = SelectSpectroscopyImages(Headers)
spectsel = false(1,numel(Headers));
for i=1:numel(Headers)
if isfield(Headers{i},'SOPClassUID')
spectsel(i) = strcmp(Headers{i}.SOPClassUID,'1.3.12.2.1107.5.9.1');
end
end
spect = Headers(spectsel);
images = Headers(~spectsel);
%==========================================================================
% function [standard, guff] = SelectLastGuff(standard, guff)
%==========================================================================
function [standard, guff] = SelectLastGuff(standard, guff)
% See https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=spm;5b69d495.1108
i = find(cellfun(@(x) ~isfield(x,'ImageOrientationPatient'),standard));
guff = [guff, standard(i)];
standard(i) = [];
%==========================================================================
% function ok = CheckFields(Headers,varargin)
%==========================================================================
function ok = CheckFields(Headers,varargin)
ok = 1;
for i=1:(nargin-1)
if ~isfield(Headers,varargin{i})
ok = 0;
break;
end
end
%==========================================================================
% function clean = StripUnwantedChars(dirty)
%==========================================================================
function clean = StripUnwantedChars(dirty)
msk = (dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...
(dirty>='0'&dirty<='9') | dirty=='_';
clean = dirty(msk);
%==========================================================================
% function img = ReadImageData(Header)
%==========================================================================
function img = ReadImageData(Header)
img = [];
if Header.SamplesPerPixel ~= 1
warning('spm:dicom','%s: SamplesPerPixel = %d - cant be an MRI.', Header.Filename, Header.SamplesPerPixel);
return;
end
prec = ['ubit' num2str(Header.BitsAllocated) '=>' 'uint32'];
if isfield(Header,'TransferSyntaxUID') && strcmp(Header.TransferSyntaxUID,'1.2.840.10008.1.2.2') && strcmp(Header.VROfPixelData,'OW')
fp = fopen(Header.Filename,'r','ieee-be');
else
fp = fopen(Header.Filename,'r','ieee-le');
end
if fp==-1
warning('spm:dicom','%s: Cant open file.', Header.Filename);
return;
end
if isfield(Header,'NumberOfFrames')
NFrames = Header.NumberOfFrames;
else
NFrames = 1;
end
if isfield(Header,'TransferSyntaxUID')
switch(Header.TransferSyntaxUID)
case {'1.2.840.10008.1.2.4.50','1.2.840.10008.1.2.4.51',... % 8 bit JPEG & 12 bit JPEG
'1.2.840.10008.1.2.4.57','1.2.840.10008.1.2.4.70',... % lossless NH JPEG & lossless NH, 1st order
'1.2.840.10008.1.2.4.80','1.2.840.10008.1.2.4.81',... % lossless JPEG-LS & near lossless JPEG-LS
'1.2.840.10008.1.2.4.90','1.2.840.10008.1.2.4.91',... % lossless JPEG 2000 & possibly lossy JPEG 2000, Part 1
'1.2.840.10008.1.2.4.92','1.2.840.10008.1.2.4.93' ... % lossless JPEG 2000 & possibly lossy JPEG 2000, Part 2
}
% try to read PixelData as JPEG image
fseek(fp,Header.StartOfPixelData,'bof');
fread(fp,2,'uint16'); % uint16 encoding 65534/57344 (Item)
offset = double(fread(fp,1,'uint32')); % followed by 4 0 0 0
fread(fp,2,'uint16'); % uint16 encoding 65534/57344 (Item)
fread(fp,offset);
sz = double(fread(fp,1,'*uint32'));
img = fread(fp,sz,'*uint8');
% Next uint16 seem to encode 65534/57565 (SequenceDelimitationItem), followed by 0 0
% save PixelData into temp file - imread and its subroutines can only
% read from file, not from memory
tfile = tempname;
tfp = fopen(tfile,'w+');
fwrite(tfp,img,'uint8');
fclose(tfp);
% read decompressed data, transpose to match DICOM row/column order
img = uint32(imread(tfile)');
delete(tfile);
case {'1.2.840.10008.1.2.4.94' ,'1.2.840.10008.1.2.4.95' ,... % JPIP References & JPIP Referenced Deflate Transfer
'1.2.840.10008.1.2.4.100','1.2.840.10008.1.2.4.101',... % MPEG2 MP@ML & MPEG2 MP@HL
'1.2.840.10008.1.2.4.102', ... % MPEG-4 AVC/H.264 High Profile and BD-compatible
}
warning('spm:dicom',[Header.Filename ': cant deal with JPIP/MPEG data (' Header.TransferSyntaxUID ')']);
otherwise
fseek(fp,Header.StartOfPixelData,'bof');
img = fread(fp,Header.Rows*Header.Columns*NFrames,prec);
end
else
fseek(fp,Header.StartOfPixelData,'bof');
img = fread(fp,Header.Rows*Header.Columns*NFrames,prec);
end
fclose(fp);
if numel(img)~=Header.Rows*Header.Columns*NFrames
error([Header.Filename ': cant read whole image']);
end
if Header.PixelRepresentation
% Signed data - done this way because bitshift only
% works with signed data. Negative values are stored
% as 2s complement.
neg = logical(bitshift(bitand(img,uint32(2^Header.HighBit)), -Header.HighBit));
msk = (2^Header.HighBit - 1);
img = double(bitand(img,msk));
img(neg) = img(neg)-2^(Header.HighBit);
else
% Unsigned data
msk = (2^(Header.HighBit+1) - 1);
img = double(bitand(img,msk));
end
img = reshape(img,[Header.Columns,Header.Rows,NFrames]);
%==========================================================================
% function img = ReadSpectData(Header,privdat)
%==========================================================================
function img = ReadSpectData(Header,ntp)
% Data is stored as complex float32 values, timepoint by timepoint, voxel
% by voxel. Reshaping is done in WriteSpectroscopyVolume.
if ntp*2*4 ~= Header.SizeOfCSAData
warning('spm:dicom', [Header.Filename,': Data size mismatch.']);
end
fp = fopen(Header.Filename,'r','ieee-le');
fseek(fp,Header.StartOfCSAData,'bof');
img = fread(fp,2*ntp,'float32');
fclose(fp);
%==========================================================================
% function nrm = ReadSliceNormalVector(Header)
%==========================================================================
function nrm = ReadSliceNormalVector(Header)
str = Header.CSAImageHeaderInfo;
val = GetNumaris4Val(str,'SliceNormalVector');
for i=1:3
nrm(i,1) = sscanf(val(i,:),'%g');
end
%==========================================================================
% function n = ReadNumberOfImagesInMosaic(Header)
%==========================================================================
function n = ReadNumberOfImagesInMosaic(Header)
str = Header.CSAImageHeaderInfo;
val = GetNumaris4Val(str,'NumberOfImagesInMosaic');
n = sscanf(val','%d');
if isempty(n), n = []; end
%==========================================================================
% function dim = ReadAcquisitionMatrixText(Header)
%==========================================================================
function dim = ReadAcquisitionMatrixText(Header)
str = Header.CSAImageHeaderInfo;
val = GetNumaris4Val(str,'AcquisitionMatrixText');
dim = sscanf(val','%d*%d')';
if length(dim)==1
dim = sscanf(val','%dp*%d')';
end
if isempty(dim), dim=[]; end
%==========================================================================
% function val = GetNumaris4Val(str,name)
%==========================================================================
function val = GetNumaris4Val(str,name)
name = deblank(name);
val = {};
for i=1:length(str)
if strcmp(deblank(str(i).name),name)
for j=1:str(i).nitems
if str(i).item(j).xx(1)
val = [val {str(i).item(j).val}];
end
end
break;
end
end
val = strvcat(val{:});
%==========================================================================
% function val = GetNumaris4NumVal(str,name)
%==========================================================================
function val = GetNumaris4NumVal(str,name)
val1 = GetNumaris4Val(str,name);
val = zeros(size(val1,1),1);
for k = 1:size(val1,1)
val(k)=str2num(val1(k,:));
end
%==========================================================================
% function fname = getfilelocation(Header,RootDirectory,prefix,format,OutputDirectory)
%==========================================================================
function fname = getfilelocation(Header,RootDirectory,prefix,format,OutputDirectory)
if nargin < 3
prefix = 'f';
end
if strncmp(RootDirectory,'ice',3)
RootDirectory = RootDirectory(4:end);
imtype = textscan(Header.ImageType,'%s','delimiter','\\');
try
imtype = imtype{1}{3};
catch
imtype = '';
end
prefix = [prefix imtype GetNumaris4Val(Header.CSAImageHeaderInfo,'ICE_Dims')];
end
if isfield(Header,'PatientID'), PatientID = deblank(Header.PatientID); else PatientID = 'anon'; end
if isfield(Header,'EchoNumbers'), EchoNumbers = Header.EchoNumbers; else EchoNumbers = 0; end
if isfield(Header,'SeriesNumber'), SeriesNumber = Header.SeriesNumber; else SeriesNumber = 0; end
if isfield(Header,'AcquisitionNumber'), AcquisitionNumber = Header.AcquisitionNumber; else AcquisitionNumber = 0; end
if isfield(Header,'InstanceNumber'), InstanceNumber = Header.InstanceNumber; else InstanceNumber = 0; end
ImTyp = '';
if isfield(Header,'GE_ImageType')
if numel(Header.GE_ImageType)==1
switch Header.GE_ImageType
case 1
ImTyp = '-Phase';
case 2
ImTyp = '-Real';
case 3
ImTyp = '-Imag';
end
end
end
% To use ICE Dims systematically in file names in order to avoid
% overwriting uncombined coil images, which have identical file name
% otherwise)
try
ICE_Dims = GetNumaris4Val(Header.CSAImageHeaderInfo,'ICE_Dims');
% extract ICE dims as an array of numbers (replace 'X' which is for
% combined images by '-1' first):
CHA = sscanf(strrep(ICE_Dims,'X','-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
if CHA(1)>0
CHA = sprintf('%.3d',CHA(1));
else
CHA = '';
end
catch
CHA = '';
end
if strcmp(RootDirectory, 'flat')
% Standard SPM file conversion
%----------------------------------------------------------------------
if CheckFields(Header,'SeriesNumber','AcquisitionNumber')
if CheckFields(Header,'EchoNumbers')
if ~isempty(CHA)
fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d-%s%s.%s', prefix, StripUnwantedChars(PatientID),...
SeriesNumber, AcquisitionNumber, InstanceNumber, EchoNumbers, CHA, ImTyp, format);
else
fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d%s.%s', prefix, StripUnwantedChars(PatientID),...
SeriesNumber, AcquisitionNumber, InstanceNumber, EchoNumbers, ImTyp, format);
end
else
if ~isempty(CHA)
fname = sprintf('%s%s-%.4d-%.5d-%.6d-%s%s.%s', prefix, StripUnwantedChars(PatientID),...
SeriesNumber, AcquisitionNumber, InstanceNumber, CHA, ImTyp, format);
else
fname = sprintf('%s%s-%.4d-%.5d-%.6d%s.%s', prefix, StripUnwantedChars(PatientID),...
SeriesNumber, AcquisitionNumber, InstanceNumber, ImTyp, format);
end
end
else
fname = sprintf('%s%s-%.6d%s.%s',prefix, ...
StripUnwantedChars(PatientID), InstanceNumber, ImTyp, format);
end
fname = fullfile(OutputDirectory,fname);
return;
end
% more fancy stuff - sort images into subdirectories
if isfield(Header,'StudyTime')
m = sprintf('%02d', floor(rem(Header.StudyTime/60,60)));
h = sprintf('%02d', floor(Header.StudyTime/3600));
else
m = '00';
h = '00';
end
if isfield(Header,'AcquisitionTime'), AcquisitionTime = Header.AcquisitionTime; else AcquisitionTime = 100; end
if isfield(Header,'StudyDate'), StudyDate = Header.StudyDate; else StudyDate = 100; end % Obscure Easter Egg
if isfield(Header,'SeriesDescription'), SeriesDescription = deblank(Header.SeriesDescription); else SeriesDescription = 'unknown'; end
if isfield(Header,'ProtocolName')
ProtocolName = deblank(Header.ProtocolName);
else
if isfield(Header,'SequenceName')
ProtocolName = deblank(Header.SequenceName);
else
ProtocolName='unknown';
end
end
studydate = sprintf('%s_%s-%s', datestr(StudyDate,'yyyy-mm-dd'), h,m);
switch RootDirectory
case {'date_time','series'}
id = studydate;
case {'patid', 'patid_date', 'patname'}
id = StripUnwantedChars(PatientID);
end
serdes = strrep(StripUnwantedChars(SeriesDescription), StripUnwantedChars(ProtocolName),'');
protname = sprintf('%s%s_%.4d', StripUnwantedChars(ProtocolName), serdes, SeriesNumber);
switch RootDirectory
case 'date_time'
dname = fullfile(OutputDirectory, id, protname);
case 'patid'
dname = fullfile(OutputDirectory, id, protname);
case 'patid_date'
dname = fullfile(OutputDirectory, id, studydate, protname);
case 'series'
dname = fullfile(OutputDirectory, protname);
otherwise
error('unknown file root specification');
end
if ~exist(dname,'dir')
mkdir_rec(dname);
end
% some non-product sequences on SIEMENS scanners seem to have problems
% with image numbering in MOSAICs - doublettes, unreliable ordering
% etc. To distinguish, always include Acquisition time in image name
sa = sprintf('%02d', floor(rem(AcquisitionTime,60)));
ma = sprintf('%02d', floor(rem(AcquisitionTime/60,60)));
ha = sprintf('%02d', floor(AcquisitionTime/3600));
fname = sprintf('%s%s-%s%s%s-%.5d-%.5d-%d%s.%s', prefix, id, ha, ma, sa, ...
AcquisitionNumber, InstanceNumber, EchoNumbers, ImTyp, format);
fname = fullfile(dname, fname);
%==========================================================================
% function suc = mkdir_rec(str)
%==========================================================================
function suc = mkdir_rec(str)
% works on full pathnames only
if str(end) ~= filesep, str = [str filesep]; end
pos = strfind(str,filesep);
suc = zeros(1,length(pos));
for g=2:length(pos)
if ~exist(str(1:pos(g)-1),'dir')
suc(g) = mkdir(str(1:pos(g-1)-1),str(pos(g-1)+1:pos(g)-1));
end
end
%==========================================================================
% function ret = ReadAscconv(Header)
%==========================================================================
function ret = ReadAscconv(Header)
% In SIEMENS data, there is an ASCII text section with
% additional information items. This section starts with a code
% ### ASCCONV BEGIN <some version string> ###
% and ends with
% ### ASCCONV END ###
% It is read by spm_dicom_headers into an entry 'MrProtocol' in
% CSASeriesHeaderInfo or into an entry 'MrPhoenixProtocol' in
% CSAMiscProtocolHeaderInfoVA or CSAMiscProtocolHeaderVB.
% The additional items are assignments in C syntax, here they are just
% translated according to
% [] -> ()
% " -> '
% 0xX -> hex2dec('X')
% and collected in a struct.
% In addition, there seems to be "__attribute__" meta information for some
% items. All "field names" starting with "_" are currently silently ignored.
ret=struct;
% get ascconv data
if isfield(Header, 'CSAMiscProtocolHeaderInfoVA')
X = GetNumaris4Val(Header.CSAMiscProtocolHeaderInfoVA,'MrProtocol');
elseif isfield(Header, 'CSAMiscProtocolHeaderInfoVB')
X = GetNumaris4Val(Header.CSAMiscProtocolHeaderInfoVB,'MrPhoenixProtocol');
elseif isfield(Header, 'CSASeriesHeaderInfo')
X = GetNumaris4Val(Header.CSASeriesHeaderInfo,'MrProtocol');
else
return;
end
X = regexprep(X,'^.*### ASCCONV BEGIN [^#]*###(.*)### ASCCONV END ###.*$','$1');
if ~isempty(X)
tokens = textscan(char(X),'%s', ...
'delimiter',char(10));
tokens{1}=regexprep(tokens{1},{'\[([0-9]*)\]','"(.*)"','^([^"]*)0x([0-9a-fA-F]*)','#.*','^.*\._.*$'},{'($1+1)','''$1''','$1hex2dec(''$2'')','',''});
% If everything would evaluate correctly, we could use
% eval(sprintf('ret.%s;\n',tokens{1}{:}));
for k = 1:numel(tokens{1})
if ~isempty(tokens{1}{k})
try
[tlhrh] = regexp(tokens{1}{k}, '(?:=)+', 'split', 'match');
[tlh] = regexp(tlhrh{1}, '(?:\.)+', 'split', 'match');
tlh = cellfun(@genvarname, tlh, 'UniformOutput',false);
tlh = sprintf('.%s', tlh{:});
eval(sprintf('ret%s = %s;', tlh, tlhrh{2}));
catch
disp(['AscConv: Error evaluating ''ret.' tokens{1}{k} ''';']);
end
end
end
end
%==========================================================================
% function Datatype = DetermineDatatype(Header)
%==========================================================================
function Datatype = DetermineDatatype(Header)
% Determine what datatype to use for NIfTI images
BigEndian = spm_platform('bigend');
if Header.BitsStored>16
if Header.PixelRepresentation
Datatype = [spm_type( 'int32') BigEndian];
else
Datatype = [spm_type('uint32') BigEndian];
end
else
if Header.PixelRepresentation
Datatype = [spm_type( 'int16') BigEndian];
else
Datatype = [spm_type('uint16') BigEndian];
end
end
%==========================================================================
% function fspe = ConvertMultiframes(Headers, RootDirectory, format, OutputDirectory, meta)
%==========================================================================
function fspe = ConvertMultiframes(Headers, RootDirectory, format, OutputDirectory, meta)
fspe = {};
DicomDictionary = ReadDicomDictionary;
for i=1:numel(Headers)
out = ConvertMultiframe(Headers{i}, DicomDictionary, RootDirectory, format,OutputDirectory,meta);
fspe = [fspe(:); out(:)];
end
%==========================================================================
% function out = ConvertMultiframe(Header, DicomDictionary, RootDirectory, format, OutputDirectory, meta)
%==========================================================================
function out = ConvertMultiframe(Header, DicomDictionary, RootDirectory, format, OutputDirectory, meta)
out = {};
DimOrg = GetDimOrg(Header, DicomDictionary);
FGS = GetFGS(Header, DimOrg);
N = numel(FGS);
fname0 = getfilelocation(Header, RootDirectory,'MF',format,OutputDirectory);
[pth,nam,ext0] = fileparts(fname0);
fname0 = fullfile(pth,nam);
if ~isfield(FGS,'ImageOrientationPatient') || ~isfield(FGS,'PixelSpacing') || ~isfield(FGS,'ImagePositionPatient')
fprintf('"%s" does not seem to have positional information.\n', Header.Filename);
return;
end
%if isfield(FGS, 'DimensionIndexValues')
% disp(cat(1, FGS.DimensionIndexValues))
%end
% Read the actual image data
volume = ReadImageData(Header);
% Sort into unique files according to image orientations etc
stuff = [cat(2, FGS.ImageOrientationPatient); cat(2, FGS.PixelSpacing)]';
if isfield(FGS, 'StackID')
stuff = [stuff double(cat(1, FGS.StackID))];
end
ds = find(any(diff(stuff,1,1)~=0,2));
ord = sparse([],[],[],N,numel(ds)+1);
start = 1;
for i=1:numel(ds)
ord(start:ds(i),i) = 1;
start = ds(i)+1;
end
ord(start:size(stuff,1),numel(ds)+1) = 1;
for n=1:size(ord,2)
% Identify all slices that should go into the same output file
%ind = find(all(bsxfun(@eq,stuff,u(n,:)),2));
ind = find(ord(:,n));
this = FGS(ind);
if size(ord,2)>1
fname = sprintf('%s_%-.3d',fname0,n);
else
fname = fname0;
end
% Orientation information
%----------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
if any(sum(diff(cat(2,this.ImageOrientationPatient),1,2).^2,1)>0.001)
fprintf('"%s" contains irregularly oriented slices.\n', Header.Filename);
% break % Option to skip writing out the NIfTI image
end
ImageOrientationPatient = this(1).ImageOrientationPatient(:);
if any(sum(diff(cat(2,this.PixelSpacing),1,2).^2,1)>0.001)
fprintf('"%s" contains slices with irregularly spaced pixels.\n', Header.Filename);
% break % Option to skip writing out the NIfTI image
end
PixelSpacing = this(1).PixelSpacing(:);
R = [reshape(ImageOrientationPatient,3,2)*diag(PixelSpacing); 0 0];
% Determine the order of the slices by sorting their positions according to where they project
% on a vector orthogonal to the image plane
orient = reshape(this(1).ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
Positions = cat(2,this.ImagePositionPatient)';
[proj,slice_order,inv_slice_order] = unique(round(Positions*orient(:,3)*100)/100);
if any(abs(diff(diff(proj),1,1))>0.025)
problem1 = true;
else
problem1 = false;
end
inv_time_order = ones(numel(this),1);
for i=1:numel(slice_order)
ind = find(inv_slice_order == i);
if numel(ind)>1
if isfield(this,'TemporalPositionIndex')
sort_on = cat(2,this(ind).TemporalPositionIndex)';
else
sort_on = ind;
end
[unused, tsort] = sort(sort_on);
inv_time_order(ind) = tsort';
end
end
% Image dimensions
%----------------------------------------------------------------------
nc = Header.Columns;
nr = Header.Rows;
dim = [nc nr 1 1];
dim(3) = max(inv_slice_order);
dim(4) = max(inv_time_order);
problem2 = false;
for i=1:max(inv_time_order)
if sum(inv_time_order==i)~=dim(3)
problem2 = true;
end
end
if problem1 || problem2
fname = [fname '-problem'];
end
if problem1
fprintf('"%s" contains irregularly spaced slices with the following spacings:\n', Header.Filename);
spaces = unique(round(diff(proj)*100)/100);
fprintf(' %g', spaces);
fprintf('\nSee %s%s\n\n',fname,ext0);
% break % Option to skip writing out the NIfTI image
end
if problem2
fprintf('"%s" has slices missing.\nSee the result in %s%s\n\n', Header.Filename,fname,ext0);
% break % Option to skip writing out the NIfTI image
end
if dim(3)>1
y1 = [this(slice_order( 1)).ImagePositionPatient(:); 1];
y2 = [this(slice_order(end)).ImagePositionPatient(:); 1];
x2 = [1; 1; dim(3); 1];
else
orient = reshape(ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end
if isfield(Header,'SliceThickness'), z = Header.SliceThickness; else z = 1; end
y1 = [this(1).ImagePositionPatient(:); 1];
y2 = [orient*[0;0;z];0];
x2 = [0;0;1;0];
end
x1 = [1;1;1;1];
DicomToPatient = [y1 y2 R]/[x1 x2 eye(4,2)];
AnalyzeToDicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
PatientToTal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
mat = PatientToTal*DicomToPatient*AnalyzeToDicom;
flip_lr = det(mat(1:3,1:3))>0;
if flip_lr
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end
% Possibly useful information for descrip field
%----------------------------------------------------------------------
if isfield(Header,'AcquisitionTime')
tim = datevec(Header.AcquisitionTime/(24*60*60));
elseif isfield(Header,'StudyTime')
tim = datevec(Header.StudyTime/(24*60*60));
elseif isfield(Header,'ContentTime')
tim = datevec(Header.ContentTime/(24*60*60));
else
tim = '';
end
if ~isempty(tim), tim = sprintf(' %d:%d:%.5g', tim(4),tim(5),tim(6)); end
if isfield(Header,'AcquisitionDate')
day = datestr(Header.AcquisitionDate);
elseif isfield(Header,'StudyDate')
day = datestr(Header.StudyDate);
elseif isfield(Header,'ContentDate')
day = datestr(Header.ContentDate);
else
day = '';
end
when = [day tim];
if CheckFields(Header,'MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle')
if isfield(Header,'ScanOptions')
ScanOptions = Header.ScanOptions;
else
ScanOptions = 'no';
end
modality = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg/SO=%s',...
Header.MagneticFieldStrength, Header.MRAcquisitionType,...
deblank(Header.ScanningSequence),...
Header.RepetitionTime, Header.EchoTime, Header.FlipAngle,...
ScanOptions);
else
modality = [Header.Modality ' ' Header.ImageType];
end
descrip = [modality ' ' when];
% Sort out datatype, as well as any scalefactors or intercepts
%----------------------------------------------------------------------
pinfos = [ones(length(this),1) zeros(length(this),1)];
for i=1:length(this)
if isfield(this(i),'RescaleSlope'), pinfos(i,1) = this(i).RescaleSlope; end
if isfield(this(i),'RescaleIntercept'), pinfos(i,2) = this(i).RescaleIntercept; end
% Philips do things differently. The following is for using their scales instead.
% Chenevert, Thomas L., et al. "Errors in quantitative image analysis due to
% platform-dependent image scaling." Translational oncology 7.1 (2014): 65-71.
if isfield(this(i),'MRScaleSlope'), pinfos(i,1) = 1/this(i).MRScaleSlope; end
if isfield(this(i),'MRScaleIntercept'), pinfos(i,2) = -this(i).MRScaleIntercept*pinfos(i,1); end
end
% The following requires more testing. Only tested on the following
% multiframe datasets (all Philips MRI data):
% - EPI series (either GRE-EPI (fMRI) or SE-EPI (DWI)),
% - structural mono-volume images (FLAIR, T1FFE),
% - structural multi-echo images (MPM protocol)
% - B0 mapping (two volumes including magnitude and phase in
% milliradians).
% The first three cases above correspond to
% any(any(diff(pinfos,1))) == false (identical scaling for all frames,
% no problem there), while the latter corresponds to
% any(any(diff(pinfos,1))) == true (variable scaling and problems).
if ~any(any(diff(pinfos,1)))
% Same slopes and intercepts for all slices
dt = DetermineDatatype(Header);
pinfo = pinfos(1,:);
else
% Variable slopes and intercept (maybe PET/SPECT) - or
% magnitude/phase data, or...?
% If variable slopes and intercepts in the multiframe dataset,
% each volume is saved as a separate NIfTI file with appropriate
% slope and intercept. NB: we assume that the same pinfo is used
% for all frames in a given volume - might not be the case?
dt = DetermineDatatype(Header);
dt = 'int16-be';
pinfo = [];
for cv = 1:max(inv_time_order)
ind = find(inv_time_order==cv);
pinfo = [pinfo; pinfos(ind(1),:)];
end
% Ensure random numbers are reproducible (see later)
% when intensities are dithered to prevent aliasing effects.
rand('state',0);
end
% Define output NIfTI files
%----------------------------------------------------------------------
fname0 = fname;
for cNii = 1:size(pinfo,1)
% Define output file name
if size(pinfo,1)>1
fname = sprintf('%s-%.4d',fname0,cNii);
dim = dim(1:3);
end
% Create nifti file
Nii{cNii} = nifti; %#ok<*AGROW>
fname = sprintf('%s%s', fname, ext0);
Nii{cNii}.dat = file_array(fname, dim, dt, 0, pinfo(cNii,1), pinfo(cNii,2));
Nii{cNii}.mat = mat;
Nii{cNii}.mat0 = mat;
Nii{cNii}.mat_intent = 'Scanner';
Nii{cNii}.mat0_intent = 'Scanner';
Nii{cNii}.descrip = descrip;
create(Nii{cNii});
% for json metadata, need to sort out the portion of the Header
% that corresponds to the current Nii volume (if multiscale &
% multiframe data -> 3D volumes):
if meta
cHeader{cNii} = Header;
if size(pinfo,1)>1
cHeader{cNii} = rmfield(cHeader{cNii},'PerFrameFunctionalGroupsSequence');
ind = find(inv_time_order==cNii);
cHeader{cNii}.NumberOfFrames = length(ind);
for cF = 1:length(ind)
cHeader{cNii}.PerFrameFunctionalGroupsSequence{cF} = Header.PerFrameFunctionalGroupsSequence{ind(cF)};
end
end
Nii{cNii} = spm_dicom_metadata(Nii{cNii},cHeader{cNii});
end
Nii{cNii}.dat(end,end,end,end,end) = 0;
end
% Write the image volume
%----------------------------------------------------------------------
spm_progress_bar('Init',length(this),['Writing ' fname], 'Planes written');
for i=1:length(this)
plane = volume(:,:,this(i).number);
if any(any(diff(pinfos,1)))
% This is to prevent aliasing effects in any subsequent histograms
% of the data (eg for mutual information coregistration).
% It's a bit inelegant, but probably necessary for when slices are
% individually rescaled.
plane = double(plane) + rand(size(plane)) - 0.5;
end
if pinfos(i,1)~=1, plane = plane*pinfos(i,1); end
if pinfos(i,2)~=0, plane = plane+pinfos(i,2); end
plane = fliplr(plane);
if flip_lr, plane = flipud(plane); end
z = inv_slice_order(i);
t = inv_time_order(i);
if size(pinfo,1)>1
Nii{t}.dat(:,:,z) = plane;
else
Nii{1}.dat(:,:,z,t) = plane;
end
spm_progress_bar('Set',i);
end
for cNii = 1:size(pinfo,1)
out = [out; {Nii{cNii}.dat.fname}];
end
spm_progress_bar('Clear');
end
%==========================================================================
% function DimOrg = GetDimOrg(Header, DicomDictionary)
%==========================================================================
function DimOrg = GetDimOrg(Header, DicomDictionary)
DimOrg = struct('DimensionIndexPointer',{},'FunctionalGroupPointer',{});
if isfield(Header,'DimensionIndexSequence')
for i=1:numel(Header.DimensionIndexSequence)
DIP = Header.DimensionIndexSequence{i}.DimensionIndexPointer;
ind = find(DicomDictionary.group==DIP(1) & DicomDictionary.element == DIP(2));
if numel(ind)==1
DimOrg(i).DimensionIndexPointer = DicomDictionary.values(ind).name;
else
if rem(DIP(1),2)
DimOrg(i).DimensionIndexPointer = sprintf('Private_%.4x_%.4x',DIP);
else
DimOrg(i).DimensionIndexPointer = sprintf('Tag_%.4x_%.4x',DIP);
end
end
FGP = Header.DimensionIndexSequence{i}.FunctionalGroupPointer;
ind = find(DicomDictionary.group==FGP(1) & DicomDictionary.element == FGP(2));
if numel(ind)==1
DimOrg(i).FunctionalGroupPointer = DicomDictionary.values(ind).name;
else
if rem(DIP(1),2)
DimOrg(i).FunctionalGroupPointer = sprintf('Private_%.4x_%.4x',DIP);
else
DimOrg(i).FunctionalGroupPointer = sprintf('Tag_%.4x_%.4x',DIP);
end
end
end
end
return
%==========================================================================
% FGS = GetFGS(Header, DimOrg)
%==========================================================================
function FGS = GetFGS(Header, DimOrg)
FGS = struct;
if isfield(Header,'PerFrameFunctionalGroupsSequence')
% For documentation, see C.7.6.16 "Multi-frame Functional Groups Module"
% of DICOM Standard PS 3.3 - 2003, Page 261.
% Multiframe DICOM
N = numel(Header.PerFrameFunctionalGroupsSequence);
if isfield(Header,'NumberOfFrames') && Header.NumberOfFrames ~= N
fprintf('"%s" has incompatible numbers of frames.', FGS.Filename);
end
% List of fields and subfields of those fields to retrieve information from.
Macros = {'PixelMeasuresSequence',{'PixelSpacing','SliceThickness'}
'FrameContentSequence',{'Frame Acquisition Number','FrameReferenceDatetime',...
'FrameAcquisitionDatetime','FrameAcquisitionDuration',...
'CardiacCyclePosition','RespiratoryCyclePosition',...
'DimensionIndexValues','TemporalPositionIndex','Stack ID',...
'InStackPositionNumber','FrameComments'}
'PlanePositionSequence',{'ImagePositionPatient'}
'PlaneOrientationSequence',{'ImageOrientationPatient'}
'ReferencedImageSequence',{'ReferencedSOPClassUID','ReferencedSOPInstanceUID',...
'ReferencedFrameNumber','PurposeOfReferenceCode'}
'PixelValueTransformationSequence',{'RescaleIntercept','RescaleSlope','RescaleType'}
% for specific PHILIPS rescaling
'PhilipsSequence_2005_140f',{'MRScaleSlope','MRScaleIntercept'}};
if isfield(Header,'SharedFunctionalGroupsSequence')
for d=1:numel(DimOrg)
if isfield(Header.SharedFunctionalGroupsSequence{1}, DimOrg(d).FunctionalGroupPointer) && ...
isfield(Header.SharedFunctionalGroupsSequence{1}.(DimOrg(d).FunctionalGroupPointer){1}, DimOrg(d).DimensionIndexPointer)
for n=N:-1:1
FGS(n).(DimOrg(d).DimensionIndexPointer) = Header.SharedFunctionalGroupsSequence{1}.(DimOrg(d).FunctionalGroupPointer){1}.(DimOrg(d).DimensionIndexPointer);
end
end
end
for k1=1:size(Macros,1)
if isfield(Header.SharedFunctionalGroupsSequence{1}, Macros{k1,1})
for k2=1:numel(Macros{k1,2})
if (numel(Header.SharedFunctionalGroupsSequence{1}.(Macros{k1,1}))>0) &&...
isfield(Header.SharedFunctionalGroupsSequence{1}.(Macros{k1,1}){1}, Macros{k1,2}{k2})
for n=N:-1:1
FGS(n).(Macros{k1,2}{k2}) = Header.SharedFunctionalGroupsSequence{1}.(Macros{k1,1}){1}.(Macros{k1,2}{k2});
end
end
end
end
end
end
for n=1:N
FGS(n).number = n;
F = Header.PerFrameFunctionalGroupsSequence{n};
for d=1:numel(DimOrg)
if isfield(F,DimOrg(d).FunctionalGroupPointer) && ...
isfield(F.(DimOrg(d).FunctionalGroupPointer){1}, DimOrg(d).DimensionIndexPointer)
FGS(n).(DimOrg(d).DimensionIndexPointer) = F.(DimOrg(d).FunctionalGroupPointer){1}.(DimOrg(d).DimensionIndexPointer);
end
end
for k1=1:size(Macros,1)
if isfield(F,Macros{k1,1}) && (numel(F.(Macros{k1,1}))>0)
for k2=1:numel(Macros{k1,2})
if isfield(F.(Macros{k1,1}){1},Macros{k1,2}{k2})
FGS(n).(Macros{k1,2}{k2}) = F.(Macros{k1,1}){1}.(Macros{k1,2}{k2});
end
end
end
end
end
else
error('"%s" is not multiframe.', Header.Filename);
end
%==========================================================================
% function DicomDictionary = ReadDicomDictionary(DictionaryFile)
%==========================================================================
function DicomDictionary = ReadDicomDictionary(DictionaryFile)
if nargin<1, DictionaryFile = 'spm_dicom_dict.mat'; end
try
DicomDictionary = load(DictionaryFile);
catch Problem
fprintf('\nUnable to load the file "%s".\n', DictionaryFile);
rethrow(Problem);
end
|
[STATEMENT]
lemma finite_insert_card :
assumes "finite (\<Union>SS)"
and "finite S"
and "S \<inter> (\<Union>SS) = {}"
shows "card (\<Union> (insert S SS)) = card (\<Union>SS) + card S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. card (\<Union> (insert S SS)) = card (\<Union> SS) + card S
[PROOF STEP]
by (simp add: assms(1) assms(2) assms(3) card_Un_disjoint) |
#reshaping data is comon task in data analysis
#data reshaping involves rearrangement of the form, not the contents of the data
#for the purpose of reshaping we divide vars. in 2 groups. 1st is identifier.
#these vars. identify the unit of measurements that take place on they are ususally decrete and fixed by design
#2nd is measured variable: represents what is measured on that unit.
#melting and casting in R
#reshape package is used under there are 2 func. melt() and cast()
#1.melt() : it takes data in wide format and stacks a set of cols. into a single col. data.
#the arguments to this fun. are data.frame(), id vars. and measured vars.
#e.g : install reshape package use data ships apply function melt() id var = type and year
library(reshape)
library(MASS)
data = head(ships,n=10)
var=melt(data,id=c("type","year"))
var
#aggreagation occures whenthe combination of the variables in the cast function does not idenify individual observations
#in this case cast function() reduces multiple values to a single value by suming up the vals in the value column
#e.g :
var1 = cast(var, type+year~variable,sum)
var1
library(reshape2)
dataf = head(airquality, n=20)
dataf
variable=melt(dataf,id.vars =c("Month","Day"))
variable
variable1 = dcast(variable, Month+Day~variable,sum)
variable1
#in reshape2 package melt takes wide format data and converts it into long format data
#while cast take long format data and converts it into wide format data
#e.g : use reshape2 package
#1. consider mtcars convert into long format by setting id var to cyl and gear
#2. convert dataset to wide format by using mean as aggreagation function
df = head(mtcars, n=20)
df
var=melt(df,id.vars =c("cyl","gear"))
var
var1 = dcast(var, cyl+gear~variable,mean)
var1
var2 = acast(var,cyl+gear~variable, mean)
|
module Procedures
import DataTypes
import Environment
%access public export
isProcedure : PrimitiveLispFunc
isProcedure [LispFunc _ _ _ _ _] = pure $ LispBool True
isProcedure [LispPrimitiveFunc _ _] = pure $ LispBool True
isProcedure [_] = pure $ LispBool False
isProcedure args = Left $ NumArgs (MinMax 1 1) (cast $ length args) args
procedurePrimitives : List (String, PrimitiveLispFunc)
procedurePrimitives =
[ ("procedure?", isProcedure)
] |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% MISCELLANEOUS SETTINGS/COMMANDS %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\balA}[1][1]{BAL$^\mathup{I}_{#1:#1}$\xspace}
\newcommand{\unbalA}[1][n]{UNBAL$^\mathup{I}_{1:#1}$\xspace}
\newcommand{\balB}[1][1]{BAL$^\mathup{II}_{#1:#1}$\xspace}
\newcommand{\unbalB}[1][n]{UNBAL$^\mathup{II}_{#1:1}$\xspace}
%% Add separator slide to the beginning of each section ==>
\AtBeginSection[]{
\begin{frame}[standout, c]{~}
%\vfill
\usebeamerfont{title}%
\textcolor{SpotColor}{\insertsectionhead}
%\vfill
\end{frame}%
}
%% Alternativelyy, add ``Outline'' slide to the beginning of each section ==>
%\AtBeginSection[]{
% \begin{frame}[plain]{Outline}
% \tableofcontents[currentsection]
% \end{frame}
%}
%% <==
\title{A~Template for Academic Presentations}
%\subtitle{I~Prefer to Avoid Subtitles}
\author[Smith, Smith, and Smith]{%
Adam Smith\inst{a,\,c} \and
% Set the name of the presenting coauthor in boldface:
\alert{Janet Smith}\inst{b,\,c} \and
Jeremiah Smith\inst{a}
} % Author(s)
\institute{%
\\
\inst{a}\,University of Bonn, Germany \and
\inst{b}\,University of Cologne, Germany \and
\inst{c}\,Collaborative Research Center Transregio~224%
} % Institution(s)
\date{%
\\
Name of the Inviting Institution/Seminar Series \\[\medskipamount]
\textmd{\today}%
}
%%%%%%%%%%%%%%%%%%%
%% TITLE SLIDE %%
%%%%%%%%%%%%%%%%%%%
\begin{frame}[standout]{~}
\titlepage%
\end{frame}
\begin{frame}[standout]{Outline}
\medskip
\tableofcontents
\end{frame}
%%%%%%%%%%%%%%%%%
%% MAIN PART %%
%%%%%%%%%%%%%%%%%
\section{Introduction}
\begin{frame}{\titleprefix: Choice of a~Reasonable Aspect Ratio}
When preparing a~presentation, we often do not know whether the native aspect ratio of the projector in the seminar room/lecture hall will be 4\,:\,3 or 16\,:\,9 (or 16\,:\,10).
In this case, it may be a~good idea to choose an~\alert{intermediate aspect ratio}, see \url{https://github.com/josephwright/beamer/issues/497}. The idea behind this recommendation is that it minimizes the average loss of available space.
Hence, these templates include a~presentation in the \alert{14\,:\,9 aspect ratio} (see \url{https://en.wikipedia.org/wiki/14:9_aspect_ratio}): while it is imperfect for probably every projector that you will encounter, it is good on average for all of them.
(Please note that 14\,:\,9${}\mathrel{\dot{=}} 1.556$, which is pretty close to the ``officially'' recommended 20\,:\,13${}\mathrel{\dot{=}} 1.5385$.)
\end{frame}
\begin{frame}{\titleprefix}
\begin{quote}
Great Minds Discuss Ideas. \\
Average Minds Discuss Events. \\
Small Minds Discuss People. \\
\upshape ---\url{https://quoteinvestigator.com/2014/11/18/great-minds/}
\end{quote}
\heading{Background}
\begin{itemize}
\item Temporal discounting is key concept in economics.
\item Normative model: exponential discounting. However, observed decisions are hard to explain \citep[e.g.,][]{Dohmen2012}.
\item One alternative: the ``focusing model'' by \cite{Koszegi2013}.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix}
\heading{Research Question}
\begin{itemize}
\item The composition of latex and of typical rubbers is given below.
\item Is it true that trees are regularly tapped and the coagulated latex which exudes is collected and worked up into rubber?
\end{itemize}
\pause
\heading{Preview of the Results}
\begin{itemize}
\item There is no feasible method at present known of preventing the inclusion of the resin of the latex with the rubber during coagulation.
\item[$\Rightarrow$\hspace{-2.5pt}] Although the separation of the resin from the solid caoutchouc by means of solvents is possible, it is not practicable or profitable commercially.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix: Beamer \texttt{block} Environments}
\begin{block}{Block title example: 0123456789 äöüß ÄÖÜ Often finding flowers in official fjords}
The \texttt{block} environment. The \texttt{block} environment. The \texttt{block} environment. The \texttt{block} environment. The \texttt{block} environment. \insertblocktitle
\end{block}%
\begin{exampleblock}{An~Exemplary Example}
I~am the \texttt{exampleblock} environment. Use me for examples. I~am really exemplary.
\end{exampleblock}
\begin{alertblock}{Summary: Things to remember}
The \texttt{alertblock} environment. Use this environment for really important stuff. The \texttt{alertblock} environment.
\end{alertblock}
\end{frame}
\begin{frame}{\titleprefix: Beamer \texttt{definition} and \texttt{theorem} Environments}
\begin{definition}[A~Very, Very, Very, Very, Very, Very Long Name of a~Concept that Spans Two Lines]
The \texttt{definition} environment. Upright.
\end{definition}
\begin{theorem}[Theorem's Name]
The \texttt{theorem} environment. Italic.
\end{theorem}%
\begin{lemma}[Lemma's Name]
The \texttt{lemma} environment. Italic.
\end{lemma}%
\begin{corollary}[Corollary's Name]
The \texttt{corollary} environment. Italic.
\end{corollary}%
\begin{proof}[Proof of Theorem's Name]
The \texttt{proof} environment. Upright.
\end{proof}
\end{frame}
\section{Study Design}
\begin{frame}{\titleprefix: Design of the Study}
\begin{itemize}
\item The latex of the best rubber plants furnishes from 20\% to 50\% of rubber.
\item As the removal of the impurities of the latex is one of the essential points to be aimed at, it was thought that the use of a centrifugal machine to separate the caoutchouc as a cream from the watery part of the latex would prove to be a satisfactory process.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix: Design of the Study}
The watery portion of the latex soaks into the trunk, and the soft spongy rubber which remains is kneaded and pressed into lumps or balls:
\begin{tabularx}{\textwidth}{@{} l @{\hspace{0.67em}} L @{}}
\alert{\balA, \balB:} &
Each payment transferred on single day. \\
\addlinespace
\alert{\unbalA:} &
Earlier payoff concentrated, while later payoff dispersed over ${n = 2}$, $4$, or $8$~dates. \\
\addlinespace
\alert{\unbalB:} &
Earlier payoff dispersed over ${n = 2}$, $4$, or $8$ dates, while later payoff concentrated.
\end{tabularx}
\end{frame}
\begin{frame}{\titleprefix: Control Experiment}
\begin{itemize}
\item Control for alternative explanations.
\item Many of the example sentences were taken from \url{http://sentence.yourdictionary.com/latex}.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix: An~Example \texttt{enumerate} List}
\blindlistlist[3]{enumerate}[4]
\end{frame}
\begin{frame}{\titleprefix: An~Example \texttt{itemize} List}
\blindlistlist[3]{itemize}[4]
\end{frame}
\begin{frame}{\titleprefix: Some Example Text}
\heading{Let's include some Greek letters: $\alpha$, $\beta$, $\sigma$}
\blindtext $\alpha$, $\beta$, $\sigma$
\textsf{Test: \fontencoding{LGR}\selectfont qrst qrs t qrs\noboundary\ t}. Math mode, upright: $\mathord{\textup{\fontencoding{LGR}\selectfont s\noboundary}}$
\end{frame}
\begin{frame}{\titleprefix: Some Example Formulas}
\alert{Let's include some additional Greek letters: $\gamma$, $\phi$}
\vspace{-\smallskipamount}
\[
p(R, \phi) \sim
\int_{-\infty}^\infty
\frac
{ \tilde{W}_n(\gamma) \exp \left[ \imath R / a \left( \sqrt{k^2 a^2 - \gamma^2} \cos \phi \right) \right] }
{ (k^2 a^2 - \gamma^2)^{3/4} {H'}_n^{(1)} \left( \sqrt{k^2 a^2 - \gamma^2} \right) }
\mathup{d}\gamma
\]
\pause
\vspace{-\smallskipamount}
\alert{Let's also include some upright Latin letters in math mode: $\mathup{d}$, $\mathup{e}$ (\hyperlink{Eulers_number}{next slide})}
\[
\int_{a}^{b} f(x)\,\mathup{d}x = F(b) - F(a)
\]
\pause
\vspace{-\medskipamount}
\alert{Let's test the math bold style}
\[
\mathbfup{\Sigma} \coloneqq
\mathup{Cov}(\mathbf{X}) =
\begin{bmatrix}
\mathup{Var}(X_1) & \cdots & \mathup{Cov}(X_1, X_n) \\[-2.5pt]
\vdots & \ddots & \vdots \\
\mathup{Cov}(X_n, X_1) & \cdots & \mathup{Var}(X_n)
\end{bmatrix}
\]
\end{frame}
\begin{frame}{\titleprefix: Additional Example Formulas (with upright $\mathup{\pi}$)}
\def\Pr{\ensuremath{\mathbb{P}}}
\def\rmd{\mathup{d}}
Only variables are set in italics according to \caps{ISO} style---hence, we use upright ``$\rmd$,'' ``$\mathup{e}$,'' and ``$\mathup{\pi}$'' (\texttt{\textbackslash mathup\{d\}}, \texttt{\textbackslash mathup\{e\}}, and \texttt{\textbackslash mathup\{\textbackslash pi\}}, respectively).
\begin{theorem}[Simplest form of the \emph{Central Limit Theorem}]
\ifnum \serifbodyfont=0
\sffamily
\fi
Let $X_1, X_2, \cdots$ be a sequence of i.i.d. random variables with mean $0$
and variance $1$ on a~probability space $(\Omega, \mathcal{F}, \Pr)$. Then
\hypertarget{Eulers_number}{}
\[
\Pr\left(\frac{X_1+\cdots+X_n}{\sqrt{n}}\le y\right) \to
\mathfrak{N}(y) \coloneqq
\int_{-\infty}^y \frac{\mathup{e}^{-v^2/2}}{\sqrt{2\mathup{\pi}}}\,\mathup{d}v
\quad\text{as} \quad n\to\infty,
\]
or, equivalently, letting $S_n \coloneqq \sum_1^n X_k$,
\[
\mathbb{E} f\left(S_n/\sqrt{n}\right) \to
\int_{-\infty}^\infty f(v) \frac{\mathup{e}^{-v^2/2}}{\sqrt{2\piup}}\,\mathup{d}v
\quad \mbox{as $n\to\infty$, for every $f \in \mathup{b}\mathcal{C}(\mathbb{R})$.}
\]
\end{theorem}
\end{frame}
\newcommand{\mc}[2]{\multicolumn{1}{@{} c #2}{#1}}
\begin{frame}{\titleprefix: An~\texttt{siunitx} Example Table}
\begin{table}
\caption{%
Overview of the choice lists presented to subjects \\
\citep[adapted from][]{Gerhardt2017}.%
}
\label{tab:choice_lists}%
\resizebox*{!}{0.59\textheight}{%
\input{1_Example_Content/9_Appendix/siunitx_Example_Choice_Lists}
}
\end{table}%
\end{frame}
\section{Results}
\begin{frame}{\titleprefix: Overview}
\begin{enumerate}
\item<1-> As a secondary function we may recognize the power of closing wounds, which results from the rapid coagulation of exuded latex in contact with the air:
\begin{enumerate}
\item<2-> In some cases (Allium, Convolvulaceae, etc.) rows of cells with latex-like contents occur.
\item<2-> However, the walls separating the individual cells do not break down.
\end{enumerate}
\item<3-> The rows of cells from which the laticiferous vessels are formed can be distinguished (6.3~p.p. vs. 2.6~p.p.; ${p < 0.01}$).
\end{enumerate}
\end{frame}
\begin{frame}{\titleprefix: Our Main Results}
The charts are taken from \cite{Dertwinkel-Kalt2017}.
\begin{figure}
\begin{minipage}[t]{\textwidth}
\begin{minipage}[t]{0.46\textwidth}
\Large\textbf{A} \textcolor{SpotColor}{\hspace{0.375in} {\small \textbf{Result~1}}} \\[15pt]
\includegraphics[width=1.643in, trim={3.75in 1.75in 3.75in 2in}, clip]
{1_Example_Content/Images/average_pb_fb.png} \\
\centering \footnotesize \sffamily
$\text{\balA} - \text{\unbalA[\bullet]}$
\end{minipage}
\hspace{2pt}
\begin{minipage}[t]{0.46\textwidth}
\Large\textbf{B} \textcolor{SpotColor}{\hspace{0.39in} {\small \textbf{Result~2}}} \\[15pt]
\includegraphics[width=1.710in, trim={3.75in 1.75in 3.75in 2in}, clip]
{1_Example_Content/Images/average_8_4_2.png} \\
\centering \footnotesize \sffamily
$\text{\unbalB[\bullet]} - \text{\balB}$
\end{minipage} \\
\end{minipage}
\caption{%
\textbf{(A)}~Difference between treatment and control condition. \textbf{(B)}~Heterogeneity.%
}
\end{figure}
\end{frame}
\begin{frame}{\titleprefix: Main vs. Control Experiment}
Rule out some alternative explanations.
\bigskip
\centering
{\small \alert{Result~3}} \\[15pt]
% trim={<left> <lower> <right> <upper>}
\includegraphics[height=0.5\textheight, trim={3.75in 1.75in 3.75in 2in}, clip]
{1_Example_Content/Images/average_main_control.png}
\end{frame}
\begin{frame}{\titleprefix: Another \texttt{siunitx} Example Table}
\begin{table}
\caption{%
Example of a~regression table \citep[adapted from][]{Gerhardt2017}.
Never forget to mention the dependent variable!%
}
\label{tab:lin_reg_interactions}
\resizebox*{!}{0.59\textheight}{%
\mdseries\selectfont
\input{1_Example_Content/9_Appendix/siunitx_Example_Regression}
}
\end{table}
\end{frame}
\begin{frame}{\titleprefix: Yet Another \texttt{siunitx} Example Table}
\begin{table}
\caption{Figure grouping via \texttt{siunitx} in a~table.}
\input{1_Example_Content/9_Appendix/siunitx_Example_Figure_Grouping}
\end{table}
\end{frame}
\section{Discussion}
\begin{frame}{\titleprefix}
\begin{itemize}[<+->]
\item The latex exhibits a neutral, acid, or alkaline reaction, depending on the plant from which it was obtained.
\item The latex is therefore usually allowed to coagulate on the tree \citep{Koszegi2013}.
\begin{itemize}
\item<.->[$\Rightarrow$] The latex, which is usually coagulated by standing or by heating, is obtained from incisions.
\end{itemize}
\item See also \cite{Bordalo2013, Dohmen2012}.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix: Conclusion}
\begin{itemize}
\item When exposed to air, the latex gradually undergoes putrefactive changes accompanied by coagulation.
\item The addition of a small quantity of ammonia or of formalin to some latices has the effect of preserving them.
\item There is, however, reason to believe the following.
\item The coagulation of latex into rubber is not mainly of this character.
\end{itemize}
\end{frame}
\begin{frame}{\titleprefix: An Automated Animation}
The automated transition to the next slide (=~page in the PDF document) only works in full-screen mode.
\begin{itemize}
\item The feature is available in Adobe Acrobat and Acrobat Reader.
\item Unfortunately, it is (currently, \today) not available in macOS Preview, Skim, and SumatraPDF.
\end{itemize}
\transduration{0.25}%
\only<12>{\transduration{}}\hypertarget<1>{animation_start}{}%
\foreach \n [evaluate=\n as \angle using \n * 30] in {0, ..., 12}{
\only<\n>{
\begin{figure}
\begin{tikzpicture}
\draw[draw=none, use as bounding box](-1, 0) rectangle (1, 2);
\filldraw[fill=SpotColor, draw=none] (0,1) -- (0,2) arc (90:90-\angle:1cm) -- cycle;
\end{tikzpicture}
\caption{Step~\n---Angle: \angle\textdegree}
\end{figure}
}
}%
\vspace{-\bigskipamount}
\hyperlink<12>{animation_start}{\beamerreturnbutton{Back to the start}}
\end{frame}
\begin{frame}[allowframebreaks]{\titleprefix: Testing the \texttt{allowframebreaks} option}
Let's test automatic numbering with the \texttt{allowframebreaks} option.
On this slide, \textbf{no} number should be included in the frame title.
\end{frame}
\begin{frame}[allowframebreaks]{\titleprefix: Testing the \texttt{allowframebreaks} option}
\renewcommand{\blindmarkup}[1]{\emph{#1}}
Let's test automatic numbering with the \texttt{allowframebreaks} option.
On this slide, ``(1/3)'' should appear in the frame title.
\blindtext
\parstart{\framebreak}
\Blindtext[2]
\end{frame}
%%%%%%%%%%%%%%%%%%
%% REFERENCES %%
%%%%%%%%%%%%%%%%%%
\section{\refname}
%\renewcommand\bibsection{}
% % To prevent ``References'' from appearing twice in the navigation bar
\begin{frame}[allowframebreaks]{\insertsection}
\begin{refcontext}[sorting=nyt]
% Sort BIBLIOGRAPHY by alphabet (while CITATIONS are sorted by year)
\printbibliography[heading=none]
\end{refcontext}
%% Only when using BibTeX instead of BibLaTeX ==>
%\bibliographystyle{0_0_Preamble/aea_doi_url_href}
%\bibliography{Library}
%% <==
\end{frame}
%%%%%%%%%%%%%%%%
%% APPENDIX %%
%%%%%%%%%%%%%%%%
\begin{appendix}
\section[Appendix\newline \textmd{Backup Slides}]{Appendix}
\begin{frame}[label=model]
\frametitle{\insertsection: Modeling Concentration Bias}
Subjects consider a sequences of consequences $\boldsymbol{c}$ from choice set $\boldsymbol{C}$.
%Focusing theory augments discounted utility (constant, hyperbolic, \dots) through an~additional weight \highlight{$g[\cdot]$} on the instantaneous utility function.
\begin{itemize}
\item \alert{Standard discounted utility:}
Suppose that the instantaneous utility function $u$ satisfies ${u'>0}$ and ${u''\leq 0}$, and that earlier consequences are preferred over later consequences of the same magnitude, i.e., ${D(t)\leq 1}$:
\item[] ${U}(\boldsymbol{c}\phantom{, \boldsymbol{C}}) \coloneqq
\sum_{t=1}^{T} \phantom{g_t} D(t)\,u(c_t)$, \quad where, e.g., \quad $D(t) = \delta^t$ or $D(t) = \frac{1}{1 + k\,t}$. %$\beta \delta^t$.
\medskip
\item \only<1->{\alert{Focusing model \citep{Koszegi2013}:}}
\item[]<1-> $\tilde{U}(\boldsymbol{c}\highlight{, \boldsymbol{C}}) \coloneqq \sum_{t=1}^{T} \highlight{g_t}\,D(t)\,u(c_t)$, \quad where \\[3pt]
\highlight{$g_t \equiv % g[\Delta_t(C)]$, $\Delta_t(C) =
g[\max_{\boldsymbol{c}'\in \boldsymbol{C}} %D(t)
u(c'_t) - \min_{\boldsymbol{c}'\in \boldsymbol{C}} %D(t)
u(c'_t)]$}
\smallskip
\begin{itemize}
\item<1-> Weighting function \highlight{$g[\cdot]$} increases in difference of maximum and minimum possible utility at a~point in time.
\item<1-> Subjects overweight intertemporal consequences with a greater range.
%\item<3-> Subjects overweight intertemporal consequences with a greater range
\end{itemize}
\end{itemize}
\end{frame}
\end{appendix} |
using Revise
includet("src/Spring.jl")
IArray = InternalArray
# 3. Validating the solution --------------------------------------------------------------
const step = 1e-3
const nit = Int(40/step) # round to avoid small rounding errors
# We define a problem with no friction
prob = SpringProblem(p0 = 0.8, v0 = 0, m = 1, k = 1.5)
x = eulermethod(prob, step, nit)
timeline = [prob.t0 + i*step for i in 1:length(x)]
plot(timeline, IArray(x, 1), label = "standard")
# 5. Finding the frequency of the unforced movement ---------------------------------------
# Empirically, We can see in the plot that the distance between two
# equal values (!= 0) is aproximately 5.
# Let's get the actual distance from our solution.
p0 = 1 # Reference point
P0 = -1 # Next equal point
for i = 50:length(x) # We avoid the first numbers because they are very close
if norm(x[p0][1]-x[i][1]) < 1e-3
P0 = i
break
end
end
if P0 != -1
period = timeline[P0]-timeline[p0] # Is similar to what we observed
freq = 1/period
end
# 6. Using this frequency to force it -----------------------------------------------------
cond_prob = SpringProblem(p0 = 0.8, v0 = 0, m = 1, k = 1.5, A = 1, ω = 2*π*freq)
y = eulermethod(cond_prob, step, nit)
plot!(timeline, IArray(y, 1), label = "conditioned")
savefig("media/spring_frequency_unforced.png")
|
[STATEMENT]
lemma parts_insert_Number [simp]:
"parts (insert (Number N) H) = insert (Number N) (parts H)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. parts (insert (Number N) H) = insert (Number N) (parts H)
[PROOF STEP]
apply (rule parts_insert_eq_I)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. x \<in> parts (insert (Number N) H) \<Longrightarrow> x \<in> insert (Number N) (parts H)
[PROOF STEP]
apply (erule parts.induct, auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
A set $S$ is open if and only if for every $x \in S$, there exists an $\epsilon > 0$ such that the open ball of radius $\epsilon$ centered at $x$ is contained in $S$. |
! ##################################################################################################################################
! Begin MIT license text.
! _______________________________________________________________________________________________________
! Copyright 2019 Dr William R Case, Jr ([email protected])
! Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
! associated documentation files (the "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be included in all copies or substantial
! portions of the Software and documentation.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
! THE SOFTWARE.
! _______________________________________________________________________________________________________
! End MIT license text.
SUBROUTINE WRITE_INTEGER_VEC ( ARRAY_DESCR, INT_VEC, NROWS )
! Writes an integer vector to F06 in a format that has 10 terms across the page (repeated until vector is completely written)
USE PENTIUM_II_KIND, ONLY : BYTE, LONG
USE IOUNT1, ONLY : WRT_ERR, WRT_LOG, F04, F06
USE SCONTR, ONLY : BLNK_SUB_NAM
USE TIMDAT, ONLY : TSEC
USE SUBR_BEGEND_LEVELS, ONLY : WRITE_MATRIX_BY_COLS_BEGEND
USE WRITE_INTEGER_VEC_USE_IFs ! Corrected 2019/07/14 (was WRITE_VECTOR_USE_IFs)
IMPLICIT NONE
CHARACTER(LEN=LEN(BLNK_SUB_NAM)):: SUBR_NAME = 'WRITE_INTEGER_VEC'
CHARACTER(LEN=*), INTENT(IN) :: ARRAY_DESCR ! Character descriptor of the integer array to be printed
CHARACTER(131*BYTE) :: HEADER ! MAT_DESCRIPTOR centered in a line of output
INTEGER(LONG), INTENT(IN) :: NROWS ! Number of rows in matrix MATOUT
INTEGER(LONG), INTENT(IN) :: INT_VEC(NROWS) ! Integer vector to write out
INTEGER(LONG) :: I,J ! DO loop indices
INTEGER(LONG) :: INT_VEC_LINE(10) ! 10 members of INT_VEC
INTEGER(LONG) :: NUM_LEFT ! Count of the number of rows of INT_VEC left to write out
INTEGER(LONG) :: PAD ! Number of spaces to pad in HEADER to center MAT_DESCRIPTOR
INTEGER(LONG), PARAMETER :: SUBR_BEGEND = WRITE_MATRIX_BY_COLS_BEGEND
INTRINSIC :: LEN
! **********************************************************************************************************************************
IF (WRT_LOG >= SUBR_BEGEND) THEN
CALL OURTIM
WRITE(F04,9001) SUBR_NAME,TSEC
9001 FORMAT(1X,A,' BEGN ',F10.3)
ENDIF
! **********************************************************************************************************************************
PAD = (132 - LEN(ARRAY_DESCR))/2
HEADER(1:) = ' '
HEADER(PAD+1:) = ARRAY_DESCR
WRITE(F06,101) HEADER
NUM_LEFT = NROWS
DO I=1,NROWS,10
IF (NUM_LEFT >= 10) THEN
DO J=1,10
INT_VEC_LINE(J) = INT_VEC(I+J-1)
ENDDO
WRITE(F06,103) (INT_VEC_LINE(J),J=1,10)
ELSE
DO J=1,NUM_LEFT
INT_VEC_LINE(J) = INT_VEC(I+J-1)
ENDDO
WRITE(F06,103) (INT_VEC_LINE(J),J=1,NUM_LEFT)
ENDIF
NUM_LEFT = NUM_LEFT - 10
ENDDO
WRITE(F06,*)
! **********************************************************************************************************************************
IF (WRT_LOG >= SUBR_BEGEND) THEN
CALL OURTIM
WRITE(F04,9002) SUBR_NAME,TSEC
9002 FORMAT(1X,A,' END ',F10.3)
ENDIF
RETURN
! **********************************************************************************************************************************
101 FORMAT(1X,/,1X,A,/)
103 FORMAT(16X,10(I10))
! **********************************************************************************************************************************
END SUBROUTINE WRITE_INTEGER_VEC
|
import category_theory.category
import category_theory.functor
import category_theory.types
import help_functions
import tactic.tidy
namespace diagram_lemmas
universe u
open classical function set category_theory help_functions
local notation f ` ⊚ ` :80 g:80 := category_struct.comp g f
variables {F : Type u ⥤ Type u}
{A B C : Type u}
lemma diagram_injective (f: B ⟶ A)
(g: C ⟶ A)
(inj : injective f)
: (∃! h : C ⟶ B , f ∘ h = g) ↔
(range g ⊆ range f)
:=
iff.intro
begin
tidy
end
begin
assume im,
let G : C → B → Prop := λ c b , g c = f b,
have G1 : ∀ c : C , ∃ b : B, G c b
:=
have G10 :
∀ a : A , a ∈ range g →
a ∈ range f := im,
have G11 :
∀ c : C , g c ∈ range f :=
λ c ,
have G110 : g c ∈ range g := by tidy,
G10 (g c) G110,
have G12 : ∀ c : C , ∃ b : B , g c = f b :=
λ c : C,
have G110 : g c ∈ range f := G11 c,
by tidy,
G12,
have G2 : ∀ c : C , ∃! b : B, G c b
:=
λ c,
have G20 : G c (some (G1 c)) := some_spec (G1 c),
have G21 : f (some (G1 c)) = g c :=
show f (some (G1 c)) = g c,
from
have G210 : _ := G c (some (G1 c)),
by tidy,
have G22 : ∀ b₁ : B, G c b₁ →
b₁ = (some (G1 c)) :=
λ b₁ : B, assume cbG : G c b₁,
show b₁ = (some (G1 c)), from
have G220 : f b₁ = g c := by tidy,
have G221 : f (some (G1 c)) = f b₁ := by rw [G21 , G220],
eq.symm (inj G221),
by tidy,
let h : C ⟶ B := graph_to_map G G2,
have G3 : ∀ c , (f ∘ h) c = g c:=
assume c,
have G31 : h c = some (G2 c) := by tidy,
have G32 : _ := some_spec (G2 c),
have G33 : G c (some (G2 c)) := and.left G32,
by tidy,
have G4 : f ∘ h = g := funext G3,
have G5 : ∀ h₁ : C ⟶ B , f ∘ h₁ = g → h₁ = h :=
assume h₁ fh,
have G51 : f ∘ h₁ = f ∘ h := by rw [fh , G4],
have G511 : f ⊚ h₁ = f ⊚ h := by tidy,
have G52 : mono f := iff.elim_right (mono_iff_injective f) inj,
have G53 : _ := G52.right_cancellation,
G53 h₁ h G511,
exact exists_unique.intro h G4 G5
end
lemma diagram_surjective
(f : A ⟶ B)
(g : A ⟶ C)
(sur: surjective f)
: (∃! h : B ⟶ C , h ∘ f = g) ↔
(sub_kern f g)
:=
iff.intro
begin
assume ex : ∃ h , (h ∘ f = g ∧
∀ h₁, h₁ ∘ f = g → h₁ = h),
show ∀ a₁ a₂ , kern f a₁ a₂ → kern g a₁ a₂,
cases ex with h spec,
exact spec.1 ▸ kern_comp f h
end
begin
assume k : ∀ a₁ a₂ , f a₁ = f a₂ → g a₁ = g a₂,
let h : B → C := λ b : B, g (surj_inv sur b),
have s2 : ∀ a , f (surj_inv sur (f a)) = f a :=
assume a , surj_inv_eq sur (f a),
have s3 : ∀ a , g (surj_inv sur (f a)) = g a :=
assume a , k (surj_inv sur (f a)) a (s2 a),
have s4 : ∀ a , h (f a) = g a :=
assume a,
show g (surj_inv sur (f a)) = g a,
from s3 a,
have s5: h ∘ f = g := funext s4,
have s6 : ∀ h₂ :B → C , h₂ ∘ f = g → h₂ = h :=
begin
assume h₂ h2,
have s61 : h₂ ∘ f = h ∘ f := by simp [s5 , h2],
haveI s62 : epi f := (epi_iff_surjective f).2 sur,
have left_cancel := s62.left_cancellation,
have s63 : h₂ = h := left_cancel h₂ h s61,
tidy
end,
exact exists_unique.intro h s5 s6,
end
end diagram_lemmas |
{-# LANGUAGE FlexibleContexts #-}
module Evaluator.Numerical where
import LispTypes
import Environment
import Evaluator.Operators
import Data.Complex
import Data.Ratio
import Data.Foldable
import Data.Fixed
import Numeric
import Control.Monad.Except
numericalPrimitives :: [(String, [LispVal] -> ThrowsError LispVal)]
numericalPrimitives =
-- Binary Numerical operations
[("+", numAdd),
("-", numSub),
("*", numMul),
("/", numDivide),
("modulo", numMod),
("quotient", numericBinop quot),
("remainder", numericBinop rem),
("abs", numAbs),
("ceiling", numCeil),
("floor", numFloor),
("round", numRound),
("truncate", numTruncate),
-- Conversion
("number->string", numToString),
-- Numerical Boolean operators
("=", numBoolBinop (==)),
("<", numBoolBinop (<)),
(">", numBoolBinop (>)),
("/=", numBoolBinop (/=)),
(">=", numBoolBinop (>=)),
("<=", numBoolBinop (<=)),
-- Scientific functions
("sqrt", sciSqrt),
("acos", sciAcos),
("asin", sciAsin),
("atan", sciAtan),
("cos", sciCos),
("sin", sciSin),
("tan", sciTan),
-- ("acosh", sciAcosh),
-- ("asinh", sciAsinh),
-- ("atanh", sciAtanh),
-- ("cosh", sciCosh),
-- ("sinh", sciSinh),
-- ("tanh", sciTanh),
("exp", sciExp),
("expt", sciExpt),
("log", sciLog),
-- Complex numbers operations
-- ("angle", cAngle),
("real-part", cRealPart),
("imag-part", cImagPart),
("magnitude", cMagnitude),
("make-polar", cMakePolar),
-- ("make-rectangular", cMakeRectangular),
-- Type testing functions
("number?", unaryOp numberp),
("integer?", unaryOp integerp),
("float?", unaryOp floatp),
("ratio?", unaryOp ratiop),
("complex?", unaryOp complexp)]
-- |Type testing functions
numberp, integerp, floatp, ratiop, complexp :: LispVal -> LispVal
integerp (Number _) = Bool True
integerp _ = Bool False
numberp (Number _) = Bool True
numberp (Float _) = Bool True
numberp (Ratio _) = Bool True
numberp (Complex _) = Bool True
numberp _ = Bool False
floatp (Float _) = Bool True
floatp _ = Bool False
ratiop (Ratio _) = Bool True
ratiop _ = Bool False
complexp (Complex _) = Bool True
complexp _ = Bool False
-- |Absolute value
numAbs :: [LispVal] -> ThrowsError LispVal
numAbs [Number x] = return $ Number $ abs x
numAbs [Float x] = return $ Float $ abs x
numAbs [Complex x] = return $ Complex $ abs x -- Calculates the magnitude
numAbs [Ratio x] = return $ Ratio $ abs x
numAbs [x] = throwError $ TypeMismatch "number" x
numAbs l = throwError $ NumArgs 1 l
-- |Ceiling, floor, round and truncate
numCeil, numFloor, numRound, numTruncate :: [LispVal] -> ThrowsError LispVal
numCeil [Number x] = return $ Number $ ceiling $ fromInteger x
numCeil [Ratio x] = return $ Number $ ceiling $ fromRational x
numCeil [Float x] = return $ Number $ ceiling x
numCeil [Complex x] =
if imagPart x == 0 then return $ Number $ ceiling $ realPart x
else throwError $ TypeMismatch "integer or float" $ Complex x
numCeil [x] = throwError $ TypeMismatch "integer or float" x
numCeil l = throwError $ NumArgs 1 l
numFloor [Number x] = return $ Number $ floor $ fromInteger x
numFloor [Ratio x] = return $ Number $ floor $ fromRational x
numFloor [Float x] = return $ Number $ floor x
numFloor [Complex x] =
if imagPart x == 0 then return $ Number $ floor $ realPart x
else throwError $ TypeMismatch "integer or float" $ Complex x
numFloor [x] = throwError $ TypeMismatch "integer or float" x
numFloor l = throwError $ NumArgs 1 l
numRound [Number x] = return $ Number $ round $ fromInteger x
numRound [Ratio x] = return $ Number $ round $ fromRational x
numRound [Float x] = return $ Number $ round x
numRound [Complex x] =
if imagPart x == 0 then return $ Number $ round $ realPart x
else throwError $ TypeMismatch "integer or float" $ Complex x
numRound [x] = throwError $ TypeMismatch "integer or float" x
numRound l = throwError $ NumArgs 1 l
numTruncate [Number x] = return $ Number $ truncate $ fromInteger x
numTruncate [Ratio x] = return $ Number $ truncate $ fromRational x
numTruncate [Float x] = return $ Number $ truncate x
numTruncate [Complex x] =
if imagPart x == 0 then return $ Number $ truncate $ realPart x
else throwError $ TypeMismatch "integer or float" $ Complex x
numTruncate [x] = throwError $ TypeMismatch "integer or float" x
numTruncate l = throwError $ NumArgs 1 l
-- |foldl1M is like foldlM but has no base case
foldl1M :: Monad m => (a -> a -> m a) -> [a] -> m a
foldl1M f (x : xs) = foldlM f x xs
foldl1M _ _ = error "unexpected error in foldl1M"
-- | Sum numbers
numAdd :: [LispVal] -> ThrowsError LispVal
numAdd [] = return $ Number 0
numAdd l = foldl1M (\ x y -> numCast [x, y] >>= go) l
where
go (List [Number x, Number y]) = return $ Number $ x + y
go (List [Float x, Float y]) = return $ Float $ x + y
go (List [Ratio x, Ratio y]) = return $ Ratio $ x + y
go (List [Complex x, Complex y]) = return $ Complex $ x + y
go _ = throwError $ Default "unexpected error in (+)"
-- | Subtract numbers
numSub :: [LispVal] -> ThrowsError LispVal
numSub [] = throwError $ NumArgs 1 []
numSub [Number x] = return $ Number $ -1 * x
numSub [Float x] = return $ Float $ -1 * x
numSub [Ratio x] = return $ Ratio $ -1 * x
numSub [Complex x] = return $ Complex $ -1 * x
numSub l = foldl1M (\ x y -> numCast [x, y] >>= go) l
where
go (List [Number x, Number y]) = return $ Number $ x - y
go (List [Float x, Float y]) = return $ Float $ x - y
go (List [Ratio x, Ratio y]) = return $ Ratio $ x - y
go (List [Complex x, Complex y]) = return $ Complex $ x - y
go _ = throwError $ Default "unexpected error in (-)"
-- | Multiply numbers
numMul :: [LispVal] -> ThrowsError LispVal
numMul [] = return $ Number 1
numMul l = foldl1M (\ x y -> numCast [x, y] >>= go) l
where
go (List [Number x, Number y]) = return $ Number $ x * y
go (List [Float x, Float y]) = return $ Float $ x * y
go (List [Ratio x, Ratio y]) = return $ Ratio $ x * y
go (List [Complex x, Complex y]) = return $ Complex $ x * y
go _ = throwError $ Default "unexpected error in (*)"
-- |Divide two numbers
numDivide :: [LispVal] -> ThrowsError LispVal
numDivide [] = throwError $ NumArgs 1 []
numDivide [Number 0] = throwError DivideByZero
numDivide [Ratio 0] = throwError DivideByZero
numDivide [Number x] = return $ Ratio $ 1 / fromInteger x
numDivide [Float x] = return $ Float $ 1.0 / x
numDivide [Ratio x] = return $ Ratio $ 1 / x
numDivide [Complex x] = return $ Complex $ 1 / x
numDivide l = foldl1M (\ x y -> numCast [x, y] >>= go) l
where
go (List [Number x, Number y])
| y == 0 = throwError DivideByZero
| mod x y == 0 = return $ Number $ div x y -- Integer division
| otherwise = return $ Ratio $ fromInteger x / fromInteger y
go (List [Float x, Float y])
| y == 0 = throwError DivideByZero
| otherwise = return $ Float $ x / y
go (List [Ratio x, Ratio y])
| y == 0 = throwError DivideByZero
| otherwise = return $ Ratio $ x / y
go (List [Complex x, Complex y])
| y == 0 = throwError DivideByZero
| otherwise = return $ Complex $ x / y
go _ = throwError $ Default "unexpected error in (/)"
-- |Numerical modulus
numMod :: [LispVal] -> ThrowsError LispVal
numMod [] = return $ Number 1
numMod l = foldl1M (\ x y -> numCast [x, y] >>= go) l
where
go (List [Number a, Number b]) = return $ Number $ mod' a b
go (List [Float a, Float b]) = return $ Float $ mod' a b
go (List [Ratio a, Ratio b]) = return $ Ratio $ mod' a b
-- #TODO implement modulus for complex numbers
go (List [Complex a, Complex b]) = throwError $ Default "modulus is not yet implemented for complex numbers"
go _ = throwError $ Default "unexpected error in (modulus)"
-- | Boolean operator
numBoolBinop :: (LispVal -> LispVal -> Bool) -> [LispVal] -> ThrowsError LispVal
numBoolBinop op [] = throwError $ Default "need at least two arguments"
numBoolBinop op [x] = throwError $ Default "need at least two arguments"
numBoolBinop op [x, y] = numCast [x, y] >>= go op
where
go op (List [x@(Number _), y@(Number _)]) = return $ Bool $ x `op` y
go op (List [x@(Float _), y@(Float _)]) = return $ Bool $ x `op` y
go op (List [x@(Ratio _), y@(Ratio _)]) = return $ Bool $ x `op` y
go op (List [x@(Complex _), y@(Complex _)]) = return $ Bool $ x `op` y
go op _ = throwError $ Default "unexpected error in boolean operation"
-- |Accept two numbers and cast one as the appropriate type
numCast :: [LispVal] -> ThrowsError LispVal
-- Same type, just return the two numbers
numCast [a@(Number _), b@(Number _)] = return $ List [a,b]
numCast [a@(Float _), b@(Float _)] = return $ List [a,b]
numCast [a@(Ratio _), b@(Ratio _)] = return $ List [a,b]
numCast [a@(Complex _), b@(Complex _)] = return $ List [a,b]
-- First number is an integer
numCast [Number a, b@(Float _)] = return $ List [Float $ fromInteger a, b]
numCast [Number a, b@(Ratio _)] = return $ List [Ratio $ fromInteger a, b]
numCast [Number a, b@(Complex _)] = return $ List [Complex $ fromInteger a, b]
-- First number is a float
numCast [a@(Float _), Number b] = return $ List [a, Float $ fromInteger b]
numCast [a@(Float _), Ratio b] = return $ List [a, Float $ fromRational b]
numCast [Float a, b@(Complex _)] = return $ List [Complex $ a :+ 0, b]
-- First number is a rational
numCast [a@(Ratio _), Number b] = return $ List [a, Ratio $ fromInteger b]
numCast [Ratio a, b@(Float _)] = return $ List [Float $ fromRational a, b]
numCast [Ratio a, b@(Complex _)] =
return $ List [Complex $ fromInteger (numerator a) / fromInteger (denominator a), b]
-- First number is a complex
numCast [a@(Complex _), Number b] = return $ List [a, Complex $ fromInteger b]
numCast [a@(Complex _), Float b] = return $ List [a, Complex $ b :+ 0]
numCast [a@(Complex _), Ratio b] =
return $ List [a, Complex $ fromInteger (numerator b) / fromInteger (denominator b)]
-- Error cases
numCast [a, b] = case a of
Number _ -> throwError $ TypeMismatch "number" b
Float _ -> throwError $ TypeMismatch "number" b
Ratio _ -> throwError $ TypeMismatch "number" b
Complex _ -> throwError $ TypeMismatch "number" b
_ -> throwError $ TypeMismatch "number" a
numCast _ = throwError $ Default "unknown error in numCast"
-- |Take a primitive Haskell Integer function and wrap it
-- with code to unpack an argument list, apply the function to it
-- and return a numeric value
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
-- Throw an error if there's only one argument
numericBinop op val@[_] = throwError $ NumArgs 2 val
-- Fold the operator leftway if there are enough args
numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
-- |Convert a Number to a String
numToString :: [LispVal] -> ThrowsError LispVal
numToString [Number x] = return $ String $ show x
numToString [Float x] = return $ String $ show x
numToString [Ratio x] = return $ String $ show x
numToString [Complex x] = return $ String $ show x
numToString [x] = throwError $ TypeMismatch "number" x
numToString badArgList = throwError $ NumArgs 2 badArgList
-- | Trigonometric functions
sciCos, sciSin, sciTan, sciAcos, sciAsin, sciAtan :: [LispVal] -> ThrowsError LispVal
-- | Cosine of a number
sciCos [Number x] = return $ Float $ cos $ fromInteger x
sciCos [Float x] = return $ Float $ cos x
sciCos [Ratio x] = return $ Float $ cos $ fromRational x
sciCos [Complex x] = return $ Complex $ cos x
sciCos [notnum] = throwError $ TypeMismatch "number" notnum
sciCos badArgList = throwError $ NumArgs 1 badArgList
-- | Sine of a number
sciSin [Number x] = return $ Float $ sin $ fromInteger x
sciSin [Float x] = return $ Float $ sin x
sciSin [Ratio x] = return $ Float $ sin $ fromRational x
sciSin [Complex x] = return $ Complex $ sin x
sciSin [notnum] = throwError $ TypeMismatch "number" notnum
sciSin badArgList = throwError $ NumArgs 1 badArgList
-- | Tangent of a number
sciTan [Number x] = return $ Float $ tan $ fromInteger x
sciTan [Float x] = return $ Float $ tan x
sciTan [Ratio x] = return $ Float $ tan $ fromRational x
sciTan [Complex x] = return $ Complex $ tan x
sciTan [notnum] = throwError $ TypeMismatch "number" notnum
sciTan badArgList = throwError $ NumArgs 1 badArgList
-- | Arccosine of a number
sciAcos [Number x] = return $ Float $ acos $ fromInteger x
sciAcos [Float x] = return $ Float $ acos x
sciAcos [Ratio x] = return $ Float $ acos $ fromRational x
sciAcos [Complex x] = return $ Complex $ acos x
sciAcos [notnum] = throwError $ TypeMismatch "number" notnum
sciAcos badArgList = throwError $ NumArgs 1 badArgList
-- | Sine of a number
sciAsin [Number x] = return $ Float $ asin $ fromInteger x
sciAsin [Float x] = return $ Float $ asin x
sciAsin [Ratio x] = return $ Float $ asin $ fromRational x
sciAsin [Complex x] = return $ Complex $ asin x
sciAsin [notnum] = throwError $ TypeMismatch "number" notnum
sciAsin badArgList = throwError $ NumArgs 1 badArgList
-- | Tangent of a number
sciAtan [Number x] = return $ Float $ atan $ fromInteger x
sciAtan [Float x] = return $ Float $ atan x
sciAtan [Ratio x] = return $ Float $ atan $ fromRational x
sciAtan [Complex x] = return $ Complex $ atan x
sciAtan [notnum] = throwError $ TypeMismatch "number" notnum
sciAtan badArgList = throwError $ NumArgs 1 badArgList
-- #TODO Implement hyperbolic functions
-- Ask teacher
-- | Hyperbolic functions
-- sciAcosh, sciAsinh, sciAtanh, sciCosh, sciSinh, sciTanh :: [LispVal] -> ThrowsError LispVal
-- Misc. Scientific primitives
sciSqrt, sciExp, sciExpt, sciLog :: [LispVal] -> ThrowsError LispVal
-- | Square root of a number
sciSqrt [Number x] = return $ Float $ sqrt $ fromInteger x
sciSqrt [Float x] = return $ Float $ sqrt x
sciSqrt [Ratio x] = return $ Float $ sqrt $ fromRational x
sciSqrt [Complex x] = return $ Complex $ sqrt x
sciSqrt [notnum] = throwError $ TypeMismatch "number" notnum
sciSqrt badArgList = throwError $ NumArgs 1 badArgList
-- | Return e to the power of x
sciExp [Number x] = return $ Float $ exp $ fromInteger x
sciExp [Float x] = return $ Float $ exp x
sciExp [Ratio x] = return $ Float $ exp $ fromRational x
sciExp [Complex x] = return $ Complex $ exp x
sciExp [notnum] = throwError $ TypeMismatch "number" notnum
sciExp badArgList = throwError $ NumArgs 1 badArgList
-- | Return x to the power of y
sciExpt [x, y] = numCast [x, y] >>= go
where
go (List [Number x, Number y]) = return $ Number $ round $ (fromInteger x) ** (fromInteger y)
go (List [Float x, Float y]) = return $ Float $ x ** y
go (List [Ratio x, Ratio y]) = return $ Float $ (fromRational x) ** (fromRational y)
go (List [Complex x, Complex y]) = return $ Complex $ x ** y
go _ = throwError $ Default "unexpected error in (-)"
sciExpt badArgList = throwError $ NumArgs 2 badArgList
-- | Return the natural logarithm of x
sciLog [Number x] = return $ Float $ log $ fromInteger x
sciLog [Float x] = return $ Float $ log x
sciLog [Ratio x] = return $ Float $ log $ fromRational x
sciLog [Complex x] = return $ Complex $ log x
sciLog [notnum] = throwError $ TypeMismatch "number" notnum
sciLog badArgList = throwError $ NumArgs 1 badArgList
-- #TODO implement phase (angle)
-- Ask teacher how to convert phase formats from haskell to guile scheme
-- | Complex number functions
cRealPart, cImagPart, cMakePolar, cMagnitude :: [LispVal] -> ThrowsError LispVal
-- | Real part of a complex number
cRealPart [Number x] = return $ Number $ fromInteger x
cRealPart [Float x] = return $ Float x
cRealPart [Ratio x] = return $ Float $ fromRational x
cRealPart [Complex x] = return $ Float $ realPart x
cRealPart [notnum] = throwError $ TypeMismatch "number" notnum
cRealPart badArgList = throwError $ NumArgs 1 badArgList
-- | Imaginary part of a complex number
cImagPart [Number x] = return $ Number 0
cImagPart [Float x] = return $ Number 0
cImagPart [Ratio x] = return $ Number 0
cImagPart [Complex x] = return $ Float $ imagPart x
cImagPart [notnum] = throwError $ TypeMismatch "number" notnum
cImagPart badArgList = throwError $ NumArgs 1 badArgList
-- | Form a complex number from polar components of magnitude and phase.
cMakePolar [mag, p] = numCast [mag, p] >>= go
where
go (List [Number mag, Number p])
| mag == 0 = return $ Number 0
| p == 0 = return $ Number mag
| otherwise = return $ Complex $ mkPolar (fromInteger mag) (fromInteger p)
go (List [Float mag, Float p])
| mag == 0 = return $ Number 0
| p == 0 = return $ Float mag
| otherwise = return $ Complex $ mkPolar mag p
go (List [Ratio mag, Ratio p])
| mag == 0 = return $ Number 0
| p == 0 = return $ Float (fromRational mag)
| otherwise = return $ Complex $ mkPolar (fromRational mag) (fromRational p)
go val@(List [Complex mag, Complex p]) = throwError $ TypeMismatch "real" val
go _ = throwError $ Default "unexpected error in make-polar"
cMakePolar badArgList = throwError $ NumArgs 2 badArgList
-- | Return the magnitude (length) of a complex number
cMagnitude [Number x] = return $ Number $ fromInteger x
cMagnitude [Float x] = return $ Float x
cMagnitude [Ratio x] = return $ Float $ fromRational x
cMagnitude [Complex x] = return $ Float $ magnitude x
cMagnitude [notnum] = throwError $ TypeMismatch "number" notnum
cMagnitude badArgList = throwError $ NumArgs 1 badArgList |
Formal statement is: lemma null_measure_idem [simp]: "null_measure (null_measure M) = null_measure M" Informal statement is: The null measure of a null measure is the null measure. |
(*
* Copyright 2014, General Dynamics C4 Systems
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(GD_GPL)
*)
theory Finalise_C
imports IpcCancel_C
begin
context kernel_m
begin
lemma switchIfRequiredTo_ccorres [corres]:
"ccorres dc xfdc (valid_queues and valid_objs' and tcb_at' thread
and (\<lambda>s. weak_sch_act_wf (ksSchedulerAction s) s) and st_tcb_at' runnable' thread)
(UNIV \<inter> \<lbrace>\<acute>target = tcb_ptr_to_ctcb_ptr thread\<rbrace>) hs
(switchIfRequiredTo thread)
(Call switchIfRequiredTo_'proc)"
apply (cinit lift: target_')
apply (ctac add: possibleSwitchTo_ccorres)
apply clarsimp
done
declare if_split [split del]
lemma empty_fail_getEndpoint:
"empty_fail (getEndpoint ep)"
unfolding getEndpoint_def
by (auto intro: empty_fail_getObject)
definition
"option_map2 f m = option_map f \<circ> m"
lemma tcbSchedEnqueue_cslift_spec:
"\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> \<lbrace>s. \<exists>d v. option_map2 tcbPriority_C (cslift s) \<acute>tcb = Some v
\<and> v \<le> ucast maxPrio
\<and> option_map2 tcbDomain_C (cslift s) \<acute>tcb = Some d
\<and> d \<le> ucast maxDom
\<and> (end_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))) \<noteq> NULL
\<longrightarrow> option_map2 tcbPriority_C (cslift s)
(head_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))))
\<noteq> None
\<and> option_map2 tcbDomain_C (cslift s)
(head_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))))
\<noteq> None)\<rbrace>
Call tcbSchedEnqueue_'proc
{s'. option_map2 tcbEPNext_C (cslift s') = option_map2 tcbEPNext_C (cslift s)
\<and> option_map2 tcbEPPrev_C (cslift s') = option_map2 tcbEPPrev_C (cslift s)
\<and> option_map2 tcbPriority_C (cslift s') = option_map2 tcbPriority_C (cslift s)
\<and> option_map2 tcbDomain_C (cslift s') = option_map2 tcbDomain_C (cslift s)}"
apply (hoare_rule HoarePartial.ProcNoRec1)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: option_map2_def fun_eq_iff h_t_valid_clift
h_t_valid_field[OF h_t_valid_clift])
apply (rule conjI)
apply (clarsimp simp: typ_heap_simps cong: if_cong)
apply (simp split: if_split)
apply (clarsimp simp: typ_heap_simps if_Some_helper cong: if_cong)
by (simp split: if_split)
lemma setThreadState_cslift_spec:
"\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> \<lbrace>s. s \<Turnstile>\<^sub>c \<acute>tptr \<and> (\<forall>x. ksSchedulerAction_' (globals s) = tcb_Ptr x
\<and> x \<noteq> 0 \<and> x \<noteq> ~~ 0
\<longrightarrow> (\<exists>d v. option_map2 tcbPriority_C (cslift s) (tcb_Ptr x) = Some v
\<and> v \<le> ucast maxPrio
\<and> option_map2 tcbDomain_C (cslift s) (tcb_Ptr x) = Some d
\<and> d \<le> ucast maxDom
\<and> (end_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))) \<noteq> NULL
\<longrightarrow> option_map2 tcbPriority_C (cslift s)
(head_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))))
\<noteq> None
\<and> option_map2 tcbDomain_C (cslift s)
(head_C (index \<acute>ksReadyQueues (unat (d*0x100 + v))))
\<noteq> None)))\<rbrace>
Call setThreadState_'proc
{s'. option_map2 tcbEPNext_C (cslift s') = option_map2 tcbEPNext_C (cslift s)
\<and> option_map2 tcbEPPrev_C (cslift s') = option_map2 tcbEPPrev_C (cslift s)
\<and> option_map2 tcbPriority_C (cslift s') = option_map2 tcbPriority_C (cslift s)
\<and> option_map2 tcbDomain_C (cslift s') = option_map2 tcbDomain_C (cslift s)
\<and> ksReadyQueues_' (globals s') = ksReadyQueues_' (globals s)}"
apply (rule allI, rule conseqPre)
apply vcg_step
apply vcg_step
apply vcg_step
apply vcg_step
apply vcg_step
apply vcg_step
apply vcg_step
apply (vcg exspec=tcbSchedEnqueue_cslift_spec)
apply (vcg_step+)[2]
apply vcg_step
apply (vcg exspec=isRunnable_modifies)
apply vcg
apply vcg_step
apply vcg_step
apply (vcg_step+)[1]
apply vcg
apply vcg_step+
apply (clarsimp simp: typ_heap_simps h_t_valid_clift_Some_iff
fun_eq_iff option_map2_def if_1_0_0)
by (simp split: if_split)
lemma ep_queue_relation_shift:
"(option_map2 tcbEPNext_C (cslift s')
= option_map2 tcbEPNext_C (cslift s)
\<and> option_map2 tcbEPPrev_C (cslift s')
= option_map2 tcbEPPrev_C (cslift s))
\<longrightarrow> ep_queue_relation (cslift s') ts qPrev qHead
= ep_queue_relation (cslift s) ts qPrev qHead"
apply clarsimp
apply (induct ts arbitrary: qPrev qHead)
apply simp
apply simp
apply (simp add: option_map2_def fun_eq_iff
map_option_case)
apply (drule_tac x=qHead in spec)+
apply (clarsimp split: option.split_asm)
done
lemma rf_sr_cscheduler_relation:
"(s, s') \<in> rf_sr \<Longrightarrow> cscheduler_action_relation
(ksSchedulerAction s) (ksSchedulerAction_' (globals s'))"
by (clarsimp simp: rf_sr_def cstate_relation_def Let_def)
lemma obj_at_ko_at2':
"\<lbrakk> obj_at' P p s; ko_at' ko p s \<rbrakk> \<Longrightarrow> P ko"
apply (drule obj_at_ko_at')
apply clarsimp
apply (drule ko_at_obj_congD', simp+)
done
lemma ctcb_relation_tcbDomain:
"ctcb_relation tcb tcb' \<Longrightarrow> ucast (tcbDomain tcb) = tcbDomain_C tcb'"
by (simp add: ctcb_relation_def)
lemma ctcb_relation_tcbPriority:
"ctcb_relation tcb tcb' \<Longrightarrow> ucast (tcbPriority tcb) = tcbPriority_C tcb'"
by (simp add: ctcb_relation_def)
lemma ctcb_relation_tcbDomain_maxDom:
"\<lbrakk> ctcb_relation tcb tcb'; tcbDomain tcb \<le> maxDomain \<rbrakk> \<Longrightarrow> tcbDomain_C tcb' \<le> ucast maxDom"
apply (subst ctcb_relation_tcbDomain[symmetric], simp)
apply (subst ucast_le_migrate)
apply ((simp add:maxDom_def word_size)+)[2]
apply (simp add: ucast_up_ucast is_up_def source_size_def word_size target_size_def)
apply (simp add: maxDom_to_H)
done
lemma ctcb_relation_tcbPriority_maxPrio:
"\<lbrakk> ctcb_relation tcb tcb'; tcbPriority tcb \<le> maxPriority \<rbrakk>
\<Longrightarrow> tcbPriority_C tcb' \<le> ucast maxPrio"
apply (subst ctcb_relation_tcbPriority[symmetric], simp)
apply (subst ucast_le_migrate)
apply ((simp add: seL4_MaxPrio_def word_size)+)[2]
apply (simp add: ucast_up_ucast is_up_def source_size_def word_size target_size_def)
apply (simp add: maxPrio_to_H)
done
lemma tcbSchedEnqueue_cslift_precond_discharge:
"\<lbrakk> (s, s') \<in> rf_sr; obj_at' (P :: tcb \<Rightarrow> bool) x s;
valid_queues s; valid_objs' s \<rbrakk> \<Longrightarrow>
(\<exists>d v. option_map2 tcbPriority_C (cslift s') (tcb_ptr_to_ctcb_ptr x) = Some v
\<and> v \<le> ucast maxPrio
\<and> option_map2 tcbDomain_C (cslift s') (tcb_ptr_to_ctcb_ptr x) = Some d
\<and> d \<le> ucast maxDom
\<and> (end_C (index (ksReadyQueues_' (globals s')) (unat (d*0x100 + v))) \<noteq> NULL
\<longrightarrow> option_map2 tcbPriority_C (cslift s')
(head_C (index (ksReadyQueues_' (globals s')) (unat (d*0x100 + v))))
\<noteq> None
\<and> option_map2 tcbDomain_C (cslift s')
(head_C (index (ksReadyQueues_' (globals s')) (unat (d*0x100 + v))))
\<noteq> None))"
apply (drule(1) obj_at_cslift_tcb)
apply (clarsimp simp: typ_heap_simps' option_map2_def)
apply (frule_tac t=x in valid_objs'_maxPriority, fastforce simp: obj_at'_def)
apply (frule_tac t=x in valid_objs'_maxDomain, fastforce simp: obj_at'_def)
apply (drule_tac P="\<lambda>tcb. tcbPriority tcb \<le> maxPriority" in obj_at_ko_at2', simp)
apply (drule_tac P="\<lambda>tcb. tcbDomain tcb \<le> maxDomain" in obj_at_ko_at2', simp)
apply (simp add: ctcb_relation_tcbDomain_maxDom ctcb_relation_tcbPriority_maxPrio)
apply (frule_tac d="tcbDomain ko" and p="tcbPriority ko"
in rf_sr_sched_queue_relation)
apply (simp add: maxDom_to_H maxPrio_to_H)+
apply (simp add: cready_queues_index_to_C_def2 numPriorities_def)
apply (clarsimp simp: ctcb_relation_def)
apply (frule arg_cong[where f=unat], subst(asm) unat_ucast_8_32)
apply (frule tcb_queue'_head_end_NULL)
apply (erule conjunct1[OF valid_queues_valid_q])
apply (frule(1) tcb_queue_relation_qhead_valid')
apply (simp add: valid_queues_valid_q)
apply (clarsimp simp: h_t_valid_clift_Some_iff)
done
lemma cancel_all_ccorres_helper:
"ccorres dc xfdc
(\<lambda>s. valid_objs' s \<and> valid_queues s
\<and> (\<forall>t\<in>set ts. tcb_at' t s \<and> t \<noteq> 0)
\<and> sch_act_wf (ksSchedulerAction s) s)
{s'. \<exists>p. ep_queue_relation (cslift s') ts
p (thread_' s')} hs
(mapM_x (\<lambda>t. do
y \<leftarrow> setThreadState Restart t;
tcbSchedEnqueue t
od) ts)
(WHILE \<acute>thread \<noteq> tcb_Ptr 0 DO
(CALL setThreadState(\<acute>thread, scast ThreadState_Restart));;
(CALL tcbSchedEnqueue(\<acute>thread));;
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t \<acute>thread\<rbrace>
(\<acute>thread :== h_val (hrs_mem \<acute>t_hrs) (Ptr &(\<acute>thread\<rightarrow>[''tcbEPNext_C'']) :: tcb_C ptr ptr))
OD)"
unfolding whileAnno_def
proof (induct ts)
case Nil
show ?case
apply (simp del: Collect_const)
apply (rule iffD1 [OF ccorres_expand_while_iff])
apply (rule ccorres_tmp_lift2[where G'=UNIV and G''="\<lambda>x. UNIV", simplified])
apply ceqv
apply (simp add: ccorres_cond_iffs mapM_x_def sequence_x_def
dc_def[symmetric])
apply (rule ccorres_guard_imp2, rule ccorres_return_Skip)
apply simp
done
next
case (Cons thread threads)
show ?case
apply (rule iffD1 [OF ccorres_expand_while_iff])
apply (simp del: Collect_const
add: dc_def[symmetric] mapM_x_Cons)
apply (rule ccorres_guard_imp2)
apply (rule_tac xf'=thread_' in ccorres_abstract)
apply ceqv
apply (rule_tac P="rv' = tcb_ptr_to_ctcb_ptr thread"
in ccorres_gen_asm2)
apply (rule_tac P="tcb_ptr_to_ctcb_ptr thread \<noteq> Ptr 0"
in ccorres_gen_asm)
apply (clarsimp simp add: Collect_True ccorres_cond_iffs
simp del: Collect_const)
apply (rule_tac r'=dc and xf'=xfdc in ccorres_split_nothrow[where F=UNIV])
apply (intro ccorres_rhs_assoc)
apply (ctac(no_vcg) add: setThreadState_ccorres)
apply (rule ccorres_add_return2)
apply (ctac(no_vcg) add: tcbSchedEnqueue_ccorres)
apply (rule_tac P="tcb_at' thread"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def)
apply (drule obj_at_ko_at', clarsimp)
apply (erule cmap_relationE1 [OF cmap_relation_tcb])
apply (erule ko_at_projectKO_opt)
apply (fastforce intro: typ_heap_simps)
apply (wp sts_running_valid_queues | simp)+
apply (rule ceqv_refl)
apply (rule "Cons.hyps")
apply (wp sts_valid_objs' sts_sch_act sch_act_wf_lift hoare_vcg_const_Ball_lift
sts_running_valid_queues sts_st_tcb' setThreadState_oa_queued | simp)+
apply (vcg exspec=setThreadState_cslift_spec exspec=tcbSchedEnqueue_cslift_spec)
apply (clarsimp simp: tcb_at_not_NULL
Collect_const_mem valid_tcb_state'_def
ThreadState_Restart_def mask_def
valid_objs'_maxDomain valid_objs'_maxPriority)
apply (drule(1) obj_at_cslift_tcb)
apply (clarsimp simp: typ_heap_simps)
apply (rule conjI)
apply clarsimp
apply (frule rf_sr_cscheduler_relation)
apply (clarsimp simp: cscheduler_action_relation_def
st_tcb_at'_def
split: scheduler_action.split_asm)
apply (rename_tac word)
apply (frule_tac x=word in tcbSchedEnqueue_cslift_precond_discharge)
apply simp
apply clarsimp
apply clarsimp
apply clarsimp
apply clarsimp
apply (rule conjI)
apply (frule(3) tcbSchedEnqueue_cslift_precond_discharge)
apply clarsimp
apply clarsimp
apply (subst ep_queue_relation_shift, fastforce)
apply (drule_tac x="tcb_ptr_to_ctcb_ptr thread"
in fun_cong)+
apply (clarsimp simp add: option_map2_def typ_heap_simps)
apply fastforce
done
qed
lemma cancelAllIPC_ccorres:
"ccorres dc xfdc
(invs') (UNIV \<inter> {s. epptr_' s = Ptr epptr}) []
(cancelAllIPC epptr) (Call cancelAllIPC_'proc)"
apply (cinit lift: epptr_')
apply (rule ccorres_symb_exec_l [OF _ getEndpoint_inv _ empty_fail_getEndpoint])
apply (rule_tac xf'=ret__unsigned_'
and val="case rv of IdleEP \<Rightarrow> scast EPState_Idle
| RecvEP _ \<Rightarrow> scast EPState_Recv | SendEP _ \<Rightarrow> scast EPState_Send"
and R="ko_at' rv epptr"
in ccorres_symb_exec_r_known_rv_UNIV[where R'=UNIV])
apply vcg
apply clarsimp
apply (erule cmap_relationE1 [OF cmap_relation_ep])
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp add: typ_heap_simps)
apply (simp add: cendpoint_relation_def Let_def
split: endpoint.split_asm)
apply ceqv
apply (rule_tac A="invs' and ko_at' rv epptr"
in ccorres_guard_imp2[where A'=UNIV])
apply wpc
apply (rename_tac list)
apply (simp add: endpoint_state_defs
Collect_False Collect_True
ccorres_cond_iffs
del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (rule ccorres_abstract_cleanup)
apply csymbr
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2)
apply (rule_tac r'=dc and xf'=xfdc
in ccorres_split_nothrow)
apply (rule_tac P="ko_at' (RecvEP list) epptr and invs'"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule cmap_relationE1 [OF cmap_relation_ep])
apply assumption
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp: typ_heap_simps setEndpoint_def)
apply (rule rev_bexI)
apply (rule setObject_eq; simp add: objBits_simps)[1]
apply (clarsimp simp: rf_sr_def cstate_relation_def
Let_def carch_state_relation_def carch_globals_def
cmachine_state_relation_def)
apply (clarsimp simp: cpspace_relation_def
update_ep_map_tos typ_heap_simps')
apply (erule(2) cpspace_relation_ep_update_ep)
subgoal by (simp add: cendpoint_relation_def endpoint_state_defs)
subgoal by simp
apply (rule ceqv_refl)
apply (simp only: ccorres_seq_skip dc_def[symmetric])
apply (rule ccorres_split_nothrow_novcg)
apply (rule cancel_all_ccorres_helper)
apply ceqv
apply (ctac add: rescheduleRequired_ccorres)
apply (wp weak_sch_act_wf_lift_linear
cancelAllIPC_mapM_x_valid_queues
| simp)+
apply (rule mapM_x_wp', wp)+
apply (wp sts_st_tcb')
apply (clarsimp split: if_split)
apply (rule mapM_x_wp', wp)+
apply (clarsimp simp: valid_tcb_state'_def)
apply (simp add: guard_is_UNIV_def)
apply (wp set_ep_valid_objs' hoare_vcg_const_Ball_lift
weak_sch_act_wf_lift_linear)
apply vcg
apply (simp add: ccorres_cond_iffs dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (rename_tac list)
apply (simp add: endpoint_state_defs
Collect_False Collect_True
ccorres_cond_iffs dc_def[symmetric]
del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (rule ccorres_abstract_cleanup)
apply csymbr
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2)
apply (rule_tac r'=dc and xf'=xfdc
in ccorres_split_nothrow)
apply (rule_tac P="ko_at' (SendEP list) epptr and invs'"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule cmap_relationE1 [OF cmap_relation_ep])
apply assumption
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp: typ_heap_simps setEndpoint_def)
apply (rule rev_bexI)
apply (rule setObject_eq, simp_all add: objBits_simps)[1]
apply (clarsimp simp: rf_sr_def cstate_relation_def
Let_def carch_state_relation_def carch_globals_def
cmachine_state_relation_def)
apply (clarsimp simp: cpspace_relation_def typ_heap_simps'
update_ep_map_tos)
apply (erule(2) cpspace_relation_ep_update_ep)
subgoal by (simp add: cendpoint_relation_def endpoint_state_defs)
subgoal by simp
apply (rule ceqv_refl)
apply (simp only: ccorres_seq_skip dc_def[symmetric])
apply (rule ccorres_split_nothrow_novcg)
apply (rule cancel_all_ccorres_helper)
apply ceqv
apply (ctac add: rescheduleRequired_ccorres)
apply (wp cancelAllIPC_mapM_x_valid_queues)
apply (wp mapM_x_wp' weak_sch_act_wf_lift_linear
sts_st_tcb' | clarsimp simp: valid_tcb_state'_def split: if_split)+
apply (simp add: guard_is_UNIV_def)
apply (wp set_ep_valid_objs' hoare_vcg_const_Ball_lift
weak_sch_act_wf_lift_linear)
apply vcg
apply (clarsimp simp: valid_ep'_def invs_valid_objs' invs_queues)
apply (rule cmap_relationE1[OF cmap_relation_ep], assumption)
apply (erule ko_at_projectKO_opt)
apply (frule obj_at_valid_objs', clarsimp+)
apply (clarsimp simp: projectKOs valid_obj'_def valid_ep'_def)
subgoal by (auto simp: typ_heap_simps cendpoint_relation_def
Let_def tcb_queue_relation'_def
invs_valid_objs' valid_objs'_maxDomain valid_objs'_maxPriority
intro!: obj_at_conj')
apply (clarsimp simp: guard_is_UNIV_def)
apply (wp getEndpoint_wp)
apply clarsimp
done
lemma empty_fail_getNotification:
"empty_fail (getNotification ep)"
unfolding getNotification_def
by (auto intro: empty_fail_getObject)
lemma cancelAllSignals_ccorres:
"ccorres dc xfdc
(invs') (UNIV \<inter> {s. ntfnPtr_' s = Ptr ntfnptr}) []
(cancelAllSignals ntfnptr) (Call cancelAllSignals_'proc)"
apply (cinit lift: ntfnPtr_')
apply (rule ccorres_symb_exec_l [OF _ get_ntfn_inv' _ empty_fail_getNotification])
apply (rule_tac xf'=ret__unsigned_'
and val="case ntfnObj rv of IdleNtfn \<Rightarrow> scast NtfnState_Idle
| ActiveNtfn _ \<Rightarrow> scast NtfnState_Active | WaitingNtfn _ \<Rightarrow> scast NtfnState_Waiting"
and R="ko_at' rv ntfnptr"
in ccorres_symb_exec_r_known_rv_UNIV[where R'=UNIV])
apply vcg
apply clarsimp
apply (erule cmap_relationE1 [OF cmap_relation_ntfn])
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp add: typ_heap_simps)
apply (simp add: cnotification_relation_def Let_def
split: ntfn.split_asm)
apply ceqv
apply (rule_tac A="invs' and ko_at' rv ntfnptr"
in ccorres_guard_imp2[where A'=UNIV])
apply wpc
apply (simp add: notification_state_defs ccorres_cond_iffs
dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (simp add: notification_state_defs ccorres_cond_iffs
dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (rename_tac list)
apply (simp add: notification_state_defs ccorres_cond_iffs
dc_def[symmetric] Collect_True
del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (rule ccorres_abstract_cleanup)
apply csymbr
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2)
apply (rule_tac r'=dc and xf'=xfdc in ccorres_split_nothrow)
apply (rule_tac P="ko_at' rv ntfnptr and invs'"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule_tac x=ntfnptr in cmap_relationE1 [OF cmap_relation_ntfn], assumption)
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp: typ_heap_simps setNotification_def)
apply (rule rev_bexI)
apply (rule setObject_eq, simp_all add: objBits_simps)[1]
apply (clarsimp simp: rf_sr_def cstate_relation_def
Let_def carch_state_relation_def carch_globals_def
cmachine_state_relation_def)
apply (clarsimp simp: cpspace_relation_def typ_heap_simps'
update_ntfn_map_tos)
apply (erule(2) cpspace_relation_ntfn_update_ntfn)
subgoal by (simp add: cnotification_relation_def notification_state_defs Let_def)
subgoal by simp
apply (rule ceqv_refl)
apply (simp only: ccorres_seq_skip dc_def[symmetric])
apply (rule ccorres_split_nothrow_novcg)
apply (rule cancel_all_ccorres_helper)
apply ceqv
apply (ctac add: rescheduleRequired_ccorres)
apply (wp cancelAllIPC_mapM_x_valid_queues)
apply (wp mapM_x_wp' weak_sch_act_wf_lift_linear
sts_st_tcb' | clarsimp simp: valid_tcb_state'_def split: if_split)+
apply (simp add: guard_is_UNIV_def)
apply (wp set_ntfn_valid_objs' hoare_vcg_const_Ball_lift
weak_sch_act_wf_lift_linear)
apply vcg
apply clarsimp
apply (rule cmap_relationE1[OF cmap_relation_ntfn], assumption)
apply (erule ko_at_projectKO_opt)
apply (frule obj_at_valid_objs', clarsimp+)
apply (clarsimp simp add: valid_obj'_def valid_ntfn'_def projectKOs)
subgoal by (auto simp: typ_heap_simps cnotification_relation_def
Let_def tcb_queue_relation'_def
invs_valid_objs' valid_objs'_maxDomain valid_objs'_maxPriority
intro!: obj_at_conj')
apply (clarsimp simp: guard_is_UNIV_def)
apply (wp getNotification_wp)
apply clarsimp
done
lemma tcb_queue_concat:
"tcb_queue_relation getNext getPrev mp (xs @ z # ys) qprev qhead
\<Longrightarrow> tcb_queue_relation getNext getPrev mp (z # ys)
(tcb_ptr_to_ctcb_ptr (last ((ctcb_ptr_to_tcb_ptr qprev) # xs))) (tcb_ptr_to_ctcb_ptr z)"
apply (induct xs arbitrary: qprev qhead)
apply clarsimp
apply clarsimp
apply (elim meta_allE, drule(1) meta_mp)
apply (clarsimp cong: if_cong)
done
lemma tcb_fields_ineq_helper:
"\<lbrakk> tcb_at' (ctcb_ptr_to_tcb_ptr x) s; tcb_at' (ctcb_ptr_to_tcb_ptr y) s \<rbrakk> \<Longrightarrow>
&(x\<rightarrow>[''tcbSchedPrev_C'']) \<noteq> &(y\<rightarrow>[''tcbSchedNext_C''])"
apply (clarsimp dest!: tcb_aligned'[OF obj_at'_weakenE, OF _ TrueI]
ctcb_ptr_to_tcb_ptr_aligned)
apply (clarsimp simp: field_lvalue_def)
apply (subgoal_tac "is_aligned (ptr_val y - ptr_val x) 8")
apply (drule sym, fastforce simp: is_aligned_def dvd_def)
apply (erule(1) aligned_sub_aligned)
apply (simp add: word_bits_conv)
done
end
primrec
tcb_queue_relation2 :: "(tcb_C \<Rightarrow> tcb_C ptr) \<Rightarrow> (tcb_C \<Rightarrow> tcb_C ptr)
\<Rightarrow> (tcb_C ptr \<rightharpoonup> tcb_C) \<Rightarrow> tcb_C ptr list
\<Rightarrow> tcb_C ptr \<Rightarrow> tcb_C ptr \<Rightarrow> bool"
where
"tcb_queue_relation2 getNext getPrev hp [] before after = True"
| "tcb_queue_relation2 getNext getPrev hp (x # xs) before after =
(\<exists>tcb. hp x = Some tcb \<and> getPrev tcb = before
\<and> getNext tcb = hd (xs @ [after])
\<and> tcb_queue_relation2 getNext getPrev hp xs x after)"
lemma use_tcb_queue_relation2:
"tcb_queue_relation getNext getPrev hp xs qprev qhead
= (tcb_queue_relation2 getNext getPrev hp
(map tcb_ptr_to_ctcb_ptr xs) qprev (tcb_Ptr 0)
\<and> qhead = (hd (map tcb_ptr_to_ctcb_ptr xs @ [tcb_Ptr 0])))"
apply (induct xs arbitrary: qhead qprev)
apply simp
apply (simp add: conj_comms cong: conj_cong)
done
lemma tcb_queue_relation2_concat:
"tcb_queue_relation2 getNext getPrev hp
(xs @ ys) before after
= (tcb_queue_relation2 getNext getPrev hp
xs before (hd (ys @ [after]))
\<and> tcb_queue_relation2 getNext getPrev hp
ys (last (before # xs)) after)"
apply (induct xs arbitrary: before)
apply simp
apply (rename_tac x xs before)
apply (simp split del: if_split)
apply (case_tac "hp x")
apply simp
apply simp
done
lemma tcb_queue_relation2_cong:
"\<lbrakk>queue = queue'; before = before'; after = after';
\<And>p. p \<in> set queue' \<Longrightarrow> mp p = mp' p\<rbrakk>
\<Longrightarrow> tcb_queue_relation2 getNext getPrev mp queue before after =
tcb_queue_relation2 getNext getPrev mp' queue' before' after'"
using [[hypsubst_thin = true]]
apply clarsimp
apply (induct queue' arbitrary: before')
apply simp+
done
context kernel_m begin
lemma setThreadState_ccorres_valid_queues'_simple:
"ccorres dc xfdc (\<lambda>s. tcb_at' thread s \<and> valid_queues' s \<and> \<not> runnable' st \<and> sch_act_simple s)
({s'. (\<forall>cl fl. cthread_state_relation_lifted st (cl\<lparr>tsType_CL := ts_' s' && mask 4\<rparr>, fl))}
\<inter> {s. tptr_' s = tcb_ptr_to_ctcb_ptr thread}) []
(setThreadState st thread) (Call setThreadState_'proc)"
apply (cinit lift: tptr_' cong add: call_ignore_cong)
apply (ctac (no_vcg) add: threadSet_tcbState_simple_corres)
apply (ctac add: scheduleTCB_ccorres_valid_queues'_simple)
apply (wp threadSet_valid_queues'_and_not_runnable')
apply (clarsimp simp: weak_sch_act_wf_def valid_queues'_def)
done
lemma suspend_ccorres:
assumes cteDeleteOne_ccorres:
"\<And>w slot. ccorres dc xfdc
(invs' and cte_wp_at' (\<lambda>ct. w = -1 \<or> cteCap ct = NullCap
\<or> (\<forall>cap'. ccap_relation (cteCap ct) cap' \<longrightarrow> cap_get_tag cap' = w)) slot)
({s. gs_get_assn cteDeleteOne_'proc (ghost'state_' (globals s)) = w}
\<inter> {s. slot_' s = Ptr slot}) []
(cteDeleteOne slot) (Call cteDeleteOne_'proc)"
shows
"ccorres dc xfdc
(invs' and sch_act_simple and tcb_at' thread and (\<lambda>s. thread \<noteq> ksIdleThread s))
(UNIV \<inter> {s. target_' s = tcb_ptr_to_ctcb_ptr thread}) []
(suspend thread) (Call suspend_'proc)"
apply (cinit lift: target_')
apply (ctac(no_vcg) add: cancelIPC_ccorres1 [OF cteDeleteOne_ccorres])
apply (ctac(no_vcg) add: setThreadState_ccorres_valid_queues'_simple)
apply (ctac add: tcbSchedDequeue_ccorres')
apply (rule_tac Q="\<lambda>_.
(\<lambda>s. \<forall>t' d p. (t' \<in> set (ksReadyQueues s (d, p)) \<longrightarrow>
obj_at' (\<lambda>tcb. tcbQueued tcb \<and> tcbDomain tcb = d
\<and> tcbPriority tcb = p) t' s \<and>
(t' \<noteq> thread \<longrightarrow> st_tcb_at' runnable' t' s)) \<and>
distinct (ksReadyQueues s (d, p))) and valid_queues' and valid_objs' and tcb_at' thread"
in hoare_post_imp)
apply clarsimp
apply (drule_tac x="t" in spec)
apply (drule_tac x=d in spec)
apply (drule_tac x=p in spec)
apply (clarsimp elim!: obj_at'_weakenE simp: inQ_def)
apply (wp_trace sts_valid_queues_partial)[1]
apply (rule hoare_strengthen_post)
apply (rule hoare_vcg_conj_lift)
apply (rule hoare_vcg_conj_lift)
apply (rule cancelIPC_sch_act_simple)
apply (rule cancelIPC_tcb_at'[where t=thread])
apply (rule delete_one_conc_fr.cancelIPC_invs)
apply (fastforce simp: invs_valid_queues' invs_queues invs_valid_objs'
valid_tcb_state'_def)
apply (auto simp: "StrictC'_thread_state_defs")
done
lemma cap_to_H_NTFNCap_tag:
"\<lbrakk> cap_to_H cap = NotificationCap word1 word2 a b;
cap_lift C_cap = Some cap \<rbrakk> \<Longrightarrow>
cap_get_tag C_cap = scast cap_notification_cap"
apply (clarsimp simp: cap_to_H_def Let_def split: cap_CL.splits if_split_asm)
by (simp_all add: Let_def cap_lift_def split: if_splits)
lemmas ccorres_pre_getBoundNotification = ccorres_pre_threadGet [where f=tcbBoundNotification, folded getBoundNotification_def]
lemma option_to_ptr_not_NULL:
"option_to_ptr x \<noteq> NULL \<Longrightarrow> x \<noteq> None"
by (auto simp: option_to_ptr_def option_to_0_def split: option.splits)
lemma doUnbindNotification_ccorres:
"ccorres dc xfdc (invs' and tcb_at' tcb)
(UNIV \<inter> {s. ntfnPtr_' s = ntfn_Ptr ntfnptr} \<inter> {s. tcbptr_' s = tcb_ptr_to_ctcb_ptr tcb}) []
(do ntfn \<leftarrow> getNotification ntfnptr; doUnbindNotification ntfnptr ntfn tcb od)
(Call doUnbindNotification_'proc)"
apply (cinit' lift: ntfnPtr_' tcbptr_')
apply (rule ccorres_symb_exec_l [OF _ get_ntfn_inv' _ empty_fail_getNotification])
apply (rule_tac P="invs' and ko_at' rv ntfnptr" and P'=UNIV
in ccorres_split_nothrow_novcg)
apply (rule ccorres_from_vcg[where rrel=dc and xf=xfdc])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: option_to_ptr_def option_to_0_def)
apply (frule cmap_relation_ntfn)
apply (erule (1) cmap_relation_ko_atE)
apply (rule conjI)
apply (erule h_t_valid_clift)
apply (clarsimp simp: setNotification_def split_def)
apply (rule bexI [OF _ setObject_eq])
apply (simp add: rf_sr_def cstate_relation_def Let_def init_def
typ_heap_simps'
cpspace_relation_def update_ntfn_map_tos)
apply (elim conjE)
apply (intro conjI)
-- "tcb relation"
apply (rule cpspace_relation_ntfn_update_ntfn, assumption+)
apply (clarsimp simp: cnotification_relation_def Let_def
mask_def [where n=2] NtfnState_Waiting_def)
apply (case_tac "ntfnObj rv", ((simp add: option_to_ctcb_ptr_def)+)[4])
subgoal by (simp add: carch_state_relation_def typ_heap_simps')
subgoal by (simp add: cmachine_state_relation_def)
subgoal by (simp add: h_t_valid_clift_Some_iff)
subgoal by (simp add: objBits_simps)
subgoal by (simp add: objBits_simps)
apply assumption
apply ceqv
apply (rule ccorres_move_c_guard_tcb)
apply (simp add: setBoundNotification_def)
apply (rule_tac P'="\<top>" and P="\<top>"
in threadSet_ccorres_lemma3[unfolded dc_def])
apply vcg
apply simp
apply (erule(1) rf_sr_tcb_update_no_queue2)
apply (simp add: typ_heap_simps')+
apply (simp add: tcb_cte_cases_def)
apply (simp add: ctcb_relation_def option_to_ptr_def option_to_0_def)
apply (simp add: invs'_def valid_state'_def)
apply (wp get_ntfn_ko' | simp add: guard_is_UNIV_def)+
done
lemma doUnbindNotification_ccorres':
"ccorres dc xfdc (invs' and tcb_at' tcb and ko_at' ntfn ntfnptr)
(UNIV \<inter> {s. ntfnPtr_' s = ntfn_Ptr ntfnptr} \<inter> {s. tcbptr_' s = tcb_ptr_to_ctcb_ptr tcb}) []
(doUnbindNotification ntfnptr ntfn tcb)
(Call doUnbindNotification_'proc)"
apply (cinit' lift: ntfnPtr_' tcbptr_')
apply (rule_tac P="invs' and ko_at' ntfn ntfnptr" and P'=UNIV
in ccorres_split_nothrow_novcg)
apply (rule ccorres_from_vcg[where rrel=dc and xf=xfdc])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: option_to_ptr_def option_to_0_def)
apply (frule cmap_relation_ntfn)
apply (erule (1) cmap_relation_ko_atE)
apply (rule conjI)
apply (erule h_t_valid_clift)
apply (clarsimp simp: setNotification_def split_def)
apply (rule bexI [OF _ setObject_eq])
apply (simp add: rf_sr_def cstate_relation_def Let_def init_def
typ_heap_simps'
cpspace_relation_def update_ntfn_map_tos)
apply (elim conjE)
apply (intro conjI)
-- "tcb relation"
apply (rule cpspace_relation_ntfn_update_ntfn, assumption+)
apply (clarsimp simp: cnotification_relation_def Let_def
mask_def [where n=2] NtfnState_Waiting_def)
apply (fold_subgoals (prefix))[2]
subgoal premises prems using prems
by (case_tac "ntfnObj ntfn", (simp add: option_to_ctcb_ptr_def)+)
subgoal by (simp add: carch_state_relation_def typ_heap_simps')
subgoal by (simp add: cmachine_state_relation_def)
subgoal by (simp add: h_t_valid_clift_Some_iff)
subgoal by (simp add: objBits_simps)
subgoal by (simp add: objBits_simps)
apply assumption
apply ceqv
apply (rule ccorres_move_c_guard_tcb)
apply (simp add: setBoundNotification_def)
apply (rule_tac P'="\<top>" and P="\<top>"
in threadSet_ccorres_lemma3[unfolded dc_def])
apply vcg
apply simp
apply (erule(1) rf_sr_tcb_update_no_queue2)
apply (simp add: typ_heap_simps')+
apply (simp add: tcb_cte_cases_def)
apply (simp add: ctcb_relation_def option_to_ptr_def option_to_0_def)
apply (simp add: invs'_def valid_state'_def)
apply (wp get_ntfn_ko' | simp add: guard_is_UNIV_def)+
done
lemma unbindNotification_ccorres:
"ccorres dc xfdc
(invs') (UNIV \<inter> {s. tcb_' s = tcb_ptr_to_ctcb_ptr tcb}) []
(unbindNotification tcb) (Call unbindNotification_'proc)"
apply (cinit lift: tcb_')
apply (rule_tac xf'=ntfnPtr_'
and r'="\<lambda>rv rv'. rv' = option_to_ptr rv \<and> rv \<noteq> Some 0"
in ccorres_split_nothrow)
apply (simp add: getBoundNotification_def)
apply (rule_tac P="no_0_obj' and valid_objs'" in threadGet_vcg_corres_P)
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (drule obj_at_ko_at', clarsimp)
apply (drule spec, drule(1) mp, clarsimp)
apply (clarsimp simp: typ_heap_simps ctcb_relation_def)
apply (drule(1) ko_at_valid_objs', simp add: projectKOs)
apply (clarsimp simp: option_to_ptr_def option_to_0_def projectKOs
valid_obj'_def valid_tcb'_def)
apply ceqv
apply simp
apply wpc
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip[unfolded dc_def])
apply (rule ccorres_cond_true)
apply (ctac (no_vcg) add: doUnbindNotification_ccorres[unfolded dc_def, simplified])
apply (wp gbn_wp')
apply vcg
apply (clarsimp simp: option_to_ptr_def option_to_0_def pred_tcb_at'_def
obj_at'_weakenE[OF _ TrueI]
split: option.splits)
apply (clarsimp simp: invs'_def valid_pspace'_def valid_state'_def)
done
lemma unbindMaybeNotification_ccorres:
"ccorres dc xfdc (invs') (UNIV \<inter> {s. ntfnPtr_' s = ntfn_Ptr ntfnptr}) []
(unbindMaybeNotification ntfnptr) (Call unbindMaybeNotification_'proc)"
apply (cinit lift: ntfnPtr_')
apply (rule ccorres_symb_exec_l [OF _ get_ntfn_inv' _ empty_fail_getNotification])
apply (rule ccorres_rhs_assoc2)
apply (rule_tac P="ntfnBoundTCB rv \<noteq> None \<longrightarrow>
option_to_ctcb_ptr (ntfnBoundTCB rv) \<noteq> NULL"
in ccorres_gen_asm)
apply (rule_tac xf'=boundTCB_'
and val="option_to_ctcb_ptr (ntfnBoundTCB rv)"
and R="ko_at' rv ntfnptr and valid_bound_tcb' (ntfnBoundTCB rv)"
in ccorres_symb_exec_r_known_rv_UNIV[where R'=UNIV])
apply vcg
apply clarsimp
apply (erule cmap_relationE1[OF cmap_relation_ntfn])
apply (erule ko_at_projectKO_opt)
apply (clarsimp simp: typ_heap_simps cnotification_relation_def Let_def)
apply ceqv
apply wpc
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip)
apply (rule ccorres_cond_true)
apply (rule ccorres_call[where xf'=xfdc])
apply (rule doUnbindNotification_ccorres'[simplified])
apply simp
apply simp
apply simp
apply (clarsimp simp add: guard_is_UNIV_def option_to_ctcb_ptr_def )
apply (wp getNotification_wp)
apply (clarsimp )
apply (frule (1) ko_at_valid_ntfn'[OF _ invs_valid_objs'])
by (auto simp: valid_ntfn'_def valid_bound_tcb'_def obj_at'_def projectKOs
objBitsKO_def is_aligned_def option_to_ctcb_ptr_def tcb_at_not_NULL
split: ntfn.splits)
lemma finaliseCap_True_cases_ccorres:
"\<And>final. isEndpointCap cap \<or> isNotificationCap cap
\<or> isReplyCap cap \<or> isDomainCap cap \<or> cap = NullCap \<Longrightarrow>
ccorres (\<lambda>rv rv'. ccap_relation (fst rv) (finaliseCap_ret_C.remainder_C rv')
\<and> irq_opt_relation (snd rv) (finaliseCap_ret_C.irq_C rv'))
ret__struct_finaliseCap_ret_C_'
(invs') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. final_' s = from_bool final}
\<inter> {s. exposed_' s = from_bool flag (* dave has name wrong *)}) []
(finaliseCap cap final flag) (Call finaliseCap_'proc)"
apply (subgoal_tac "\<not> isArchCap \<top> cap")
prefer 2
apply (clarsimp simp: isCap_simps)
apply (cinit lift: cap_' final_' exposed_' cong: call_ignore_cong)
apply csymbr
apply (simp add: cap_get_tag_isCap Collect_False del: Collect_const)
apply (fold case_bool_If)
apply (simp add: false_def)
apply csymbr
apply wpc
apply (simp add: cap_get_tag_isCap ccorres_cond_univ_iff Let_def)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_split_nothrow_novcg)
apply (simp add: when_def)
apply (rule ccorres_cond2)
apply (clarsimp simp: Collect_const_mem from_bool_0)
apply csymbr
apply (rule ccorres_call[where xf'=xfdc], rule cancelAllIPC_ccorres)
apply simp
apply simp
apply simp
apply (rule ccorres_from_vcg[where P=\<top> and P'=UNIV])
apply (simp add: return_def, vcg)
apply (rule ceqv_refl)
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2,
rule ccorres_split_throws)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def ccap_relation_NullCap_iff
irq_opt_relation_def)
apply vcg
apply wp
apply (simp add: guard_is_UNIV_def)
apply wpc
apply (simp add: cap_get_tag_isCap Let_def
ccorres_cond_empty_iff ccorres_cond_univ_iff)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_split_nothrow_novcg)
apply (simp add: when_def)
apply (rule ccorres_cond2)
apply (clarsimp simp: Collect_const_mem from_bool_0)
apply (subgoal_tac "cap_get_tag capa = scast cap_notification_cap") prefer 2
apply (clarsimp simp: ccap_relation_def isNotificationCap_def)
apply (case_tac cap, simp_all)[1]
apply (clarsimp simp: option_map_def split: option.splits)
apply (drule (2) cap_to_H_NTFNCap_tag[OF sym])
apply (rule ccorres_rhs_assoc)
apply (rule ccorres_rhs_assoc)
apply csymbr
apply csymbr
apply (ctac (no_vcg) add: unbindMaybeNotification_ccorres)
apply (rule ccorres_call[where xf'=xfdc], rule cancelAllSignals_ccorres)
apply simp
apply simp
apply simp
apply (wp | wpc | simp add: guard_is_UNIV_def)+
apply (rule ccorres_return_Skip')
apply (rule ceqv_refl)
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2,
rule ccorres_split_throws)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def ccap_relation_NullCap_iff
irq_opt_relation_def)
apply vcg
apply wp
apply (simp add: guard_is_UNIV_def)
apply wpc
apply (simp add: cap_get_tag_isCap Let_def
ccorres_cond_empty_iff ccorres_cond_univ_iff)
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2,
rule ccorres_split_throws)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def ccap_relation_NullCap_iff
irq_opt_relation_def)
apply vcg
apply wpc
apply (simp add: cap_get_tag_isCap Let_def
ccorres_cond_empty_iff ccorres_cond_univ_iff)
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2,
rule ccorres_split_throws)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def ccap_relation_NullCap_iff)
apply (clarsimp simp add: irq_opt_relation_def)
apply vcg
-- "NullCap case by exhaustion"
apply (simp add: cap_get_tag_isCap Let_def
ccorres_cond_empty_iff ccorres_cond_univ_iff)
apply (rule ccorres_rhs_assoc2, rule ccorres_rhs_assoc2,
rule ccorres_split_throws)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def ccap_relation_NullCap_iff
irq_opt_relation_def)
apply vcg
apply (clarsimp simp: Collect_const_mem cap_get_tag_isCap)
apply (rule TrueI conjI impI TrueI)+
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (clarsimp simp: invs'_def valid_state'_def valid_pspace'_def isNotificationCap_def
isEndpointCap_def valid_obj'_def projectKOs valid_ntfn'_def
valid_bound_tcb'_def
dest!: obj_at_valid_objs')
apply clarsimp
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply clarsimp
done
lemma finaliseCap_True_standin_ccorres:
"\<And>final.
ccorres (\<lambda>rv rv'. ccap_relation (fst rv) (finaliseCap_ret_C.remainder_C rv')
\<and> irq_opt_relation (snd rv) (finaliseCap_ret_C.irq_C rv'))
ret__struct_finaliseCap_ret_C_'
(invs') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. final_' s = from_bool final}
\<inter> {s. exposed_' s = from_bool True (* dave has name wrong *)}) []
(finaliseCapTrue_standin cap final) (Call finaliseCap_'proc)"
unfolding finaliseCapTrue_standin_simple_def
apply (case_tac "P :: bool" for P)
apply (erule finaliseCap_True_cases_ccorres)
apply (simp add: finaliseCap_def ccorres_fail')
done
lemma offset_xf_for_sequence:
"\<forall>s f. offset_' (offset_'_update f s) = f (offset_' s)
\<and> globals (offset_'_update f s) = globals s"
by simp
end
context begin interpretation Arch . (*FIXME: arch_split*)
crunch pde_mappings'[wp]: invalidateHWASIDEntry "valid_pde_mappings'"
end
context kernel_m begin
lemma invalidateASIDEntry_ccorres:
"ccorres dc xfdc (\<lambda>s. valid_pde_mappings' s \<and> asid \<le> mask asid_bits)
(UNIV \<inter> {s. asid_' s = asid}) []
(invalidateASIDEntry asid) (Call invalidateASIDEntry_'proc)"
apply (cinit lift: asid_')
apply (ctac(no_vcg) add: loadHWASID_ccorres)
apply csymbr
apply (simp(no_asm) add: when_def del: Collect_const)
apply (rule ccorres_split_nothrow_novcg_dc)
apply (rule ccorres_cond2[where R=\<top>])
apply (clarsimp simp: Collect_const_mem pde_stored_asid_def to_bool_def
split: if_split)
apply csymbr
apply (rule ccorres_Guard)+
apply (rule_tac P="rv \<noteq> None" in ccorres_gen_asm)
apply (ctac(no_simp) add: invalidateHWASIDEntry_ccorres)
apply (clarsimp simp: pde_stored_asid_def unat_ucast
split: if_split_asm)
apply (rule sym, rule nat_mod_eq')
apply (simp add: pde_pde_invalid_lift_def pde_lift_def)
apply (rule unat_less_power[where sz=8, simplified])
apply (simp add: word_bits_conv)
apply (rule order_le_less_trans, rule word_and_le1)
apply simp
apply (rule ccorres_return_Skip)
apply (fold dc_def)
apply (ctac add: invalidateASID_ccorres)
apply wp
apply (simp add: guard_is_UNIV_def)
apply wp
apply (clarsimp simp: Collect_const_mem pde_pde_invalid_lift_def pde_lift_def
order_le_less_trans[OF word_and_le1])
done
end
context begin interpretation Arch . (*FIXME: arch_split*)
crunch obj_at'[wp]: invalidateASIDEntry "obj_at' P p"
crunch obj_at'[wp]: flushSpace "obj_at' P p"
crunch valid_objs'[wp]: invalidateASIDEntry "valid_objs'"
crunch valid_objs'[wp]: flushSpace "valid_objs'"
crunch pde_mappings'[wp]: invalidateASIDEntry "valid_pde_mappings'"
crunch pde_mappings'[wp]: flushSpace "valid_pde_mappings'"
end
context kernel_m begin
lemma invs'_invs_no_cicd':
"invs' s \<longrightarrow> all_invs_but_ct_idle_or_in_cur_domain' s"
by (simp add: invs'_invs_no_cicd)
lemma deleteASIDPool_ccorres:
"ccorres dc xfdc (invs' and (\<lambda>_. base < 2 ^ 17 \<and> pool \<noteq> 0))
(UNIV \<inter> {s. asid_base_' s = base} \<inter> {s. pool_' s = Ptr pool}) []
(deleteASIDPool base pool) (Call deleteASIDPool_'proc)"
apply (rule ccorres_gen_asm)
apply (cinit lift: asid_base_' pool_' simp: whileAnno_def)
apply (rule ccorres_assert)
apply (clarsimp simp: liftM_def dc_def[symmetric] fun_upd_def[symmetric]
when_def
simp del: Collect_const)
apply (rule ccorres_Guard)+
apply (rule ccorres_pre_gets_armKSASIDTable_ksArchState)
apply (rule_tac R="\<lambda>s. rv = armKSASIDTable (ksArchState s)" in ccorres_cond2)
apply clarsimp
apply (subst rf_sr_armKSASIDTable, assumption)
apply (simp add: asid_high_bits_word_bits)
apply (rule shiftr_less_t2n)
apply (simp add: asid_low_bits_def asid_high_bits_def)
apply (subst ucast_asid_high_bits_is_shift)
apply (simp add: mask_def, simp add: asid_bits_def)
apply (simp add: option_to_ptr_def option_to_0_def split: option.split)
apply (rule ccorres_Guard_Seq ccorres_rhs_assoc)+
apply (rule ccorres_pre_getObject_asidpool)
apply (rename_tac poolKO)
apply (simp only: mapM_discarded)
apply (rule ccorres_rhs_assoc2,
rule ccorres_split_nothrow_novcg)
apply (simp add: word_sle_def Kernel_C.asidLowBits_def Collect_True
del: Collect_const)
apply (rule ccorres_semantic_equivD2[rotated])
apply (simp only: semantic_equiv_def)
apply (rule Seq_ceqv [OF ceqv_refl _ xpres_triv])
apply (simp only: ceqv_Guard_UNIV)
apply (rule While_ceqv [OF _ _ xpres_triv], rule impI, rule refl)
apply (rule ceqv_remove_eqv_skip)
apply (simp add: ceqv_Guard_UNIV ceqv_refl)
apply (rule_tac F="\<lambda>n. ko_at' poolKO pool and valid_objs' and valid_pde_mappings'"
in ccorres_mapM_x_while_gen[OF _ _ _ _ _ offset_xf_for_sequence,
where j=1, simplified])
apply (intro allI impI)
apply (rule ccorres_guard_imp2)
apply (rule_tac xf'="offset_'" in ccorres_abstract, ceqv)
apply (rule_tac P="rv' = of_nat n" in ccorres_gen_asm2)
apply (rule ccorres_Guard[where F=ArrayBounds])
apply (rule ccorres_move_c_guard_ap)
apply (rule_tac R="ko_at' poolKO pool and valid_objs'" in ccorres_cond2)
apply (clarsimp dest!: rf_sr_cpspace_asidpool_relation)
apply (erule cmap_relationE1, erule ko_at_projectKO_opt)
apply (clarsimp simp: casid_pool_relation_def typ_heap_simps
inv_ASIDPool
split: asidpool.split_asm asid_pool_C.split_asm)
apply (simp add: upto_enum_word del: upt.simps)
apply (drule(1) ko_at_valid_objs')
apply (simp add: projectKOs)
apply (clarsimp simp: array_relation_def valid_obj'_def
ran_def)
apply (drule_tac x="of_nat n" in spec)+
apply (simp add: asid_low_bits_def word_le_nat_alt)
apply (simp add: word_unat.Abs_inverse unats_def)
apply (simp add: option_to_ptr_def option_to_0_def split: option.split_asm)
apply clarsimp
apply (ctac(no_vcg) add: flushSpace_ccorres)
apply (ctac add: invalidateASIDEntry_ccorres)
apply wp
apply (rule ccorres_return_Skip)
apply (clarsimp simp: Collect_const_mem)
apply (simp add: upto_enum_word typ_at_to_obj_at_arches
obj_at'_weakenE[OF _ TrueI]
del: upt.simps)
apply (simp add: is_aligned_mask[symmetric])
apply (rule conjI[rotated])
apply (simp add: asid_low_bits_def word_of_nat_less)
apply (clarsimp simp: mask_def)
apply (erule is_aligned_add_less_t2n)
apply (subst(asm) Suc_unat_diff_1)
apply (simp add: asid_low_bits_def)
apply (simp add: unat_power_lower asid_low_bits_word_bits)
apply (erule of_nat_less_pow_32 [OF _ asid_low_bits_word_bits])
apply (simp add: asid_low_bits_def asid_bits_def)
apply (simp add: asid_bits_def)
apply (simp add: upto_enum_word )
apply (vcg exspec=flushSpace_modifies exspec=invalidateASIDEntry_modifies)
apply clarsimp
apply (rule hoare_pre, wp)
apply simp
apply (simp add: upto_enum_word asid_low_bits_def)
apply ceqv
apply (rule ccorres_move_const_guard)+
apply (rule ccorres_split_nothrow_novcg_dc)
apply (rule_tac P="\<lambda>s. rv = armKSASIDTable (ksArchState s)"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: simpler_modify_def)
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def
carch_state_relation_def cmachine_state_relation_def
carch_globals_def h_t_valid_clift_Some_iff)
apply (erule array_relation_update[unfolded fun_upd_def])
apply (simp add: asid_high_bits_of_def unat_ucast asid_low_bits_def)
apply (rule sym, rule nat_mod_eq')
apply (rule order_less_le_trans, rule iffD1[OF word_less_nat_alt])
apply (rule shiftr_less_t2n[where m=7])
subgoal by simp
subgoal by simp
subgoal by (simp add: option_to_ptr_def option_to_0_def)
subgoal by (simp add: asid_high_bits_def)
apply (rule ccorres_pre_getCurThread)
apply (ctac add: setVMRoot_ccorres)
apply wp
apply (simp add: guard_is_UNIV_def)
apply (simp add: pred_conj_def fun_upd_def[symmetric]
cur_tcb'_def[symmetric])
apply (strengthen invs'_invs_no_cicd', strengthen invs_asid_update_strg')
apply (rule mapM_x_wp')
apply (rule hoare_pre, wp)
apply simp
apply (simp add: guard_is_UNIV_def Kernel_C.asidLowBits_def
word_sle_def word_sless_def Collect_const_mem
mask_def asid_bits_def plus_one_helper
asid_shiftr_low_bits_less)
apply (rule ccorres_return_Skip)
apply (simp add: Kernel_C.asidLowBits_def
word_sle_def word_sless_def)
apply (auto simp: asid_shiftr_low_bits_less Collect_const_mem
mask_def asid_bits_def plus_one_helper)
done
lemma deleteASID_ccorres:
"ccorres dc xfdc (invs' and K (asid < 2 ^ 17) and K (pdPtr \<noteq> 0))
(UNIV \<inter> {s. asid_' s = asid} \<inter> {s. pd_' s = Ptr pdPtr}) []
(deleteASID asid pdPtr) (Call deleteASID_'proc)"
apply (cinit lift: asid_' pd_' cong: call_ignore_cong)
apply (rule ccorres_Guard_Seq)+
apply (rule_tac r'="\<lambda>rv rv'. case rv (ucast (asid_high_bits_of asid)) of
None \<Rightarrow> rv' = NULL
| Some v \<Rightarrow> rv' = Ptr v \<and> rv' \<noteq> NULL"
and xf'="poolPtr_'" in ccorres_split_nothrow)
apply (rule_tac P="invs' and K (asid < 2 ^ 17)"
and P'=UNIV in ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: simpler_gets_def Let_def)
apply (erule(1) getKSASIDTable_ccorres_stuff)
apply (simp add: asid_high_bits_of_def
asidLowBits_def Kernel_C.asidLowBits_def
asid_low_bits_def unat_ucast)
apply (rule sym, rule mod_less)
apply (rule unat_less_power[where sz=7, simplified])
apply (simp add: word_bits_conv)
apply (rule shiftr_less_t2n[where m=7, simplified])
apply simp
apply (rule order_less_le_trans, rule ucast_less)
apply simp
apply (simp add: asid_high_bits_def)
apply ceqv
apply csymbr
apply wpc
apply (simp add: ccorres_cond_iffs dc_def[symmetric]
Collect_False
del: Collect_const
cong: call_ignore_cong)
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip)
apply (simp add: dc_def[symmetric] when_def
Collect_True liftM_def
cong: conj_cong call_ignore_cong
del: Collect_const)
apply (rule ccorres_pre_getObject_asidpool)
apply (rule ccorres_Guard_Seq[where F=ArrayBounds])
apply (rule ccorres_move_c_guard_ap)
apply (rule ccorres_Guard_Seq)+
apply (rename_tac pool)
apply (rule_tac xf'=ret__int_'
and val="from_bool (inv ASIDPool pool (asid && mask asid_low_bits)
= Some pdPtr)"
and R="ko_at' pool x2 and K (pdPtr \<noteq> 0)"
in ccorres_symb_exec_r_known_rv_UNIV[where R'=UNIV])
apply (vcg, clarsimp)
apply (clarsimp dest!: rf_sr_cpspace_asidpool_relation)
apply (erule(1) cmap_relation_ko_atE)
apply (clarsimp simp: typ_heap_simps casid_pool_relation_def
array_relation_def
split: asidpool.split_asm asid_pool_C.split_asm)
apply (drule_tac x="asid && mask asid_low_bits" in spec)
apply (simp add: asid_low_bits_def Kernel_C.asidLowBits_def
mask_def word_and_le1)
apply (drule sym, simp)
apply (simp add: option_to_ptr_def option_to_0_def
from_bool_def inv_ASIDPool
split: option.split if_split bool.split)
apply ceqv
apply (rule ccorres_cond2[where R=\<top>])
apply (simp add: Collect_const_mem from_bool_0)
apply (rule ccorres_rhs_assoc)+
apply (ctac (no_vcg) add: flushSpace_ccorres)
apply (ctac (no_vcg) add: invalidateASIDEntry_ccorres)
apply (rule ccorres_Guard_Seq[where F=ArrayBounds])
apply (rule ccorres_move_c_guard_ap)
apply (rule ccorres_Guard_Seq)+
apply (rule ccorres_split_nothrow_novcg_dc)
apply (rule_tac P="ko_at' pool x2" in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule cmap_relationE1[OF rf_sr_cpspace_asidpool_relation],
assumption, erule ko_at_projectKO_opt)
apply (rule bexI [OF _ setObject_eq],
simp_all add: objBits_simps archObjSize_def pageBits_def)[1]
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def typ_heap_simps)
apply (rule conjI)
apply (clarsimp simp: cpspace_relation_def typ_heap_simps'
update_asidpool_map_tos
update_asidpool_map_to_asidpools)
apply (rule cmap_relation_updI, simp_all)[1]
apply (simp add: casid_pool_relation_def fun_upd_def[symmetric]
inv_ASIDPool
split: asidpool.split_asm asid_pool_C.split_asm)
apply (erule array_relation_update)
subgoal by (simp add: mask_def)
subgoal by (simp add: option_to_ptr_def option_to_0_def)
subgoal by (simp add: asid_low_bits_def)
subgoal by (simp add: carch_state_relation_def cmachine_state_relation_def
carch_globals_def update_asidpool_map_tos
typ_heap_simps')
apply (rule ccorres_pre_getCurThread)
apply (ctac add: setVMRoot_ccorres)
apply (simp add: cur_tcb'_def[symmetric])
apply (strengthen invs'_invs_no_cicd')
apply wp
apply (clarsimp simp: rf_sr_def guard_is_UNIV_def
cstate_relation_def Let_def)
apply wp[1]
apply (simp add: fun_upd_def[symmetric])
apply wp
apply (rule ccorres_return_Skip)
subgoal by (clarsimp simp: guard_is_UNIV_def Collect_const_mem
word_sle_def word_sless_def
Kernel_C.asidLowBits_def
asid_low_bits_def order_le_less_trans [OF word_and_le1])
apply wp
apply vcg
apply (clarsimp simp: Collect_const_mem if_1_0_0
word_sless_def word_sle_def
Kernel_C.asidLowBits_def
typ_at_to_obj_at_arches)
apply (rule conjI)
apply (clarsimp simp: mask_def inv_ASIDPool
split: asidpool.split)
apply (frule obj_at_valid_objs', clarsimp+)
apply (clarsimp simp: asid_bits_def typ_at_to_obj_at_arches
obj_at'_weakenE[OF _ TrueI]
fun_upd_def[symmetric] valid_obj'_def
projectKOs invs_valid_pde_mappings'
invs_cur')
apply (rule conjI, blast)
subgoal by (fastforce simp: inv_into_def ran_def split: if_split_asm)
by (clarsimp simp: order_le_less_trans [OF word_and_le1]
asid_shiftr_low_bits_less asid_bits_def mask_def
plus_one_helper arg_cong[where f="\<lambda>x. 2 ^ x", OF meta_eq_to_obj_eq, OF asid_low_bits_def]
split: option.split_asm)
lemma setObject_ccorres_lemma:
fixes val :: "'a :: pspace_storable" shows
"\<lbrakk> \<And>s. \<Gamma> \<turnstile> (Q s) c {s'. (s \<lparr> ksPSpace := ksPSpace s (ptr \<mapsto> injectKO val) \<rparr>, s') \<in> rf_sr},{};
\<And>s s' val (val' :: 'a). \<lbrakk> ko_at' val' ptr s; (s, s') \<in> rf_sr \<rbrakk>
\<Longrightarrow> s' \<in> Q s;
\<And>val :: 'a. updateObject val = updateObject_default val;
\<And>val :: 'a. (1 :: word32) < 2 ^ objBits val;
\<And>(val :: 'a) (val' :: 'a). objBits val = objBits val';
\<Gamma> \<turnstile> Q' c UNIV \<rbrakk>
\<Longrightarrow> ccorres dc xfdc \<top> Q' hs
(setObject ptr val) c"
apply (rule ccorres_from_vcg_nofail)
apply (rule allI)
apply (case_tac "obj_at' (\<lambda>x :: 'a. True) ptr \<sigma>")
apply (rule_tac P'="Q \<sigma>" in conseqPre, rule conseqPost, assumption)
apply clarsimp
apply (rule bexI [OF _ setObject_eq], simp+)
apply (drule obj_at_ko_at')
apply clarsimp
apply clarsimp
apply (rule conseqPre, erule conseqPost)
apply clarsimp
apply (subgoal_tac "fst (setObject ptr val \<sigma>) = {}")
apply simp
apply (erule notE, erule_tac s=\<sigma> in empty_failD[rotated])
apply (simp add: setObject_def split_def)
apply (rule ccontr)
apply (clarsimp elim!: nonemptyE)
apply (frule use_valid [OF _ obj_at_setObject3[where P=\<top>]], simp_all)[1]
apply (simp add: typ_at_to_obj_at'[symmetric])
apply (frule(1) use_valid [OF _ setObject_typ_at'])
apply simp
apply simp
apply clarsimp
done
lemma findPDForASID_nonzero:
"\<lbrace>\<top>\<rbrace> findPDForASID asid \<lbrace>\<lambda>rv s. rv \<noteq> 0\<rbrace>,-"
apply (simp add: findPDForASID_def cong: option.case_cong)
apply (wp | wpc | simp only: o_def simp_thms)+
done
lemma unat_shiftr_le_bound:
"2 ^ (len_of TYPE('a :: len) - n) - 1 \<le> bnd \<Longrightarrow> 0 < n
\<Longrightarrow> unat ((x :: 'a word) >> n) \<le> bnd"
apply (erule order_trans[rotated], simp)
apply (rule nat_le_Suc_less_imp)
apply (rule unat_less_helper, simp)
apply (rule shiftr_less_t2n3)
apply simp
apply simp
done
lemma pageTableMapped_ccorres:
"ccorres (\<lambda>rv rv'. rv' = option_to_ptr rv \<and> rv \<noteq> Some 0) ret__ptr_to_struct_pde_C_'
(invs' and K (asid \<le> mask asid_bits))
(UNIV \<inter> {s. asid_' s = asid} \<inter> {s. vaddr_' s = vaddr} \<inter> {s. pt_' s = Ptr ptPtr}) []
(pageTableMapped asid vaddr ptPtr) (Call pageTableMapped_'proc)"
apply (cinit lift: asid_' vaddr_' pt_')
apply (simp add: ignoreFailure_def catch_def
bindE_bind_linearise liftE_def
del: Collect_const cong: call_ignore_cong)
apply (rule ccorres_split_nothrow_novcg_case_sum)
apply clarsimp
apply (ctac (no_vcg) add: findPDForASID_ccorres)
apply ceqv
apply (simp add: Collect_False del: Collect_const cong: call_ignore_cong)
apply (rule ccorres_Guard_Seq)+
apply csymbr
apply (rule_tac xf'=pde_' and r'=cpde_relation in ccorres_split_nothrow_novcg)
apply (rule ccorres_add_return2, rule ccorres_pre_getObject_pde)
apply (rule ccorres_move_array_assertion_pd
| (rule ccorres_flip_Guard, rule ccorres_move_array_assertion_pd))+
apply (rule_tac P="ko_at' x (lookup_pd_slot rv vaddr) and no_0_obj'
and page_directory_at' rv"
in ccorres_from_vcg[where P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def lookup_pd_slot_def Let_def)
apply (drule(1) page_directory_at_rf_sr)
apply (erule cmap_relationE1[OF rf_sr_cpde_relation],
erule ko_at_projectKO_opt)
apply (clarsimp simp: typ_heap_simps' shiftl_t2n field_simps)
apply ceqv
apply (rule_tac P="rv \<noteq> 0" in ccorres_gen_asm)
apply csymbr+
apply (wpc, simp_all add: if_1_0_0 returnOk_bind throwError_bind
del: Collect_const)
prefer 2
apply (rule ccorres_cond_true_seq)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: if_1_0_0 cpde_relation_def Let_def
return_def addrFromPPtr_def
pde_pde_coarse_lift_def)
apply (rule conjI)
apply (simp add: pde_lift_def Let_def split: if_split_asm)
apply (clarsimp simp: option_to_0_def option_to_ptr_def split: if_split)
apply (clarsimp simp: ARM.addrFromPPtr_def ARM.ptrFromPAddr_def)
apply ((rule ccorres_cond_false_seq ccorres_cond_false
ccorres_return_C | simp)+)[3]
apply (simp only: simp_thms)
apply wp
apply (clarsimp simp: guard_is_UNIV_def Collect_const_mem if_1_0_0)
apply (simp add: cpde_relation_def Let_def pde_lift_def
split: if_split_asm,
auto simp: option_to_0_def option_to_ptr_def pde_tag_defs)[1]
apply simp
apply (rule ccorres_split_throws)
apply (rule ccorres_return_C, simp+)
apply vcg
apply (wp hoare_drop_imps findPDForASID_nonzero)
apply (simp add: guard_is_UNIV_def word_sle_def pdBits_def pageBits_def
unat_gt_0 unat_shiftr_le_bound)
apply (simp add: guard_is_UNIV_def option_to_0_def option_to_ptr_def)
apply auto[1]
done
lemma pageTableMapped_pd:
"\<lbrace>\<top>\<rbrace> pageTableMapped asid vaddr ptPtr
\<lbrace>\<lambda>rv s. case rv of Some x \<Rightarrow> page_directory_at' x s | _ \<Rightarrow> True\<rbrace>"
apply (simp add: pageTableMapped_def)
apply (rule hoare_pre)
apply (wp getPDE_wp hoare_vcg_all_lift_R | wpc)+
apply (rule hoare_post_imp_R, rule findPDForASID_page_directory_at'_simple)
apply (clarsimp split: if_split)
apply simp
done
lemma unmapPageTable_ccorres:
"ccorres dc xfdc (invs' and (\<lambda>s. asid \<le> mask asid_bits \<and> vaddr < kernelBase))
(UNIV \<inter> {s. asid_' s = asid} \<inter> {s. vaddr_' s = vaddr} \<inter> {s. pt_' s = Ptr ptPtr}) []
(unmapPageTable asid vaddr ptPtr) (Call unmapPageTable_'proc)"
apply (rule ccorres_gen_asm)
apply (cinit lift: asid_' vaddr_' pt_')
apply (ctac(no_vcg) add: pageTableMapped_ccorres)
apply wpc
apply (simp add: option_to_ptr_def option_to_0_def ccorres_cond_iffs)
apply (rule ccorres_return_Skip[unfolded dc_def])
apply (simp add: option_to_ptr_def option_to_0_def ccorres_cond_iffs)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_Guard_Seq)+
apply csymbr
apply (rule ccorres_move_array_assertion_pd)
apply csymbr
apply csymbr
apply (rule ccorres_split_nothrow_novcg_dc)
apply (rule storePDE_Basic_ccorres)
apply (simp add: cpde_relation_def Let_def pde_lift_pde_invalid)
apply (fold dc_def)
apply csymbr
apply (ctac add: cleanByVA_PoU_ccorres)
apply (ctac(no_vcg) add:flushTable_ccorres)
apply wp
apply (vcg exspec=cleanByVA_PoU_modifies)
apply wp
apply (fastforce simp: guard_is_UNIV_def Collect_const_mem Let_def
shiftl_t2n field_simps lookup_pd_slot_def)
apply (rule_tac Q="\<lambda>rv s. (case rv of Some pd \<Rightarrow> page_directory_at' pd s | _ \<Rightarrow> True) \<and> invs' s"
in hoare_post_imp)
apply (clarsimp simp: lookup_pd_slot_def Let_def
mask_add_aligned less_kernelBase_valid_pde_offset''
page_directory_at'_def)
apply (wp pageTableMapped_pd)
apply (clarsimp simp: word_sle_def lookup_pd_slot_def
Let_def shiftl_t2n field_simps
Collect_const_mem pdBits_def pageBits_def)
apply (simp add: unat_shiftr_le_bound unat_eq_0)
done
lemma return_Null_ccorres:
"ccorres ccap_relation ret__struct_cap_C_'
\<top> UNIV (SKIP # hs)
(return NullCap) (\<acute>ret__struct_cap_C :== CALL cap_null_cap_new()
;; return_C ret__struct_cap_C_'_update ret__struct_cap_C_')"
apply (rule ccorres_from_vcg_throws)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: ccap_relation_NullCap_iff return_def)
done
lemma no_0_pd_at'[elim!]:
"\<lbrakk> page_directory_at' 0 s; no_0_obj' s \<rbrakk> \<Longrightarrow> P"
apply (clarsimp simp: page_directory_at'_def)
apply (drule spec[where x=0], clarsimp)
done
lemma Arch_finaliseCap_ccorres:
"\<And>final.
ccorres ccap_relation ret__struct_cap_C_'
(invs' and valid_cap' (ArchObjectCap cap)
and (\<lambda>s. 2 ^ acapBits cap \<le> gsMaxObjectSize s))
(UNIV \<inter> {s. ccap_relation (ArchObjectCap cap) (cap_' s)}
\<inter> {s. final_' s = from_bool final}) []
(Arch.finaliseCap cap final) (Call Arch_finaliseCap_'proc)"
apply (cinit lift: cap_' final_' cong: call_ignore_cong)
apply csymbr
apply (simp add: ARM_H.finaliseCap_def cap_get_tag_isCap_ArchObject
del: Collect_const)
apply (wpc, simp_all add: isCap_simps Collect_False Collect_True
case_bool_If
del: Collect_const)[1]
apply (rule ccorres_if_lhs)
apply (simp add: from_bool_0 true_def)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply simp
apply (ctac(no_vcg) add: deleteASIDPool_ccorres)
apply (rule return_Null_ccorres)
apply wp
apply (simp add: from_bool_0 false_def)
apply (rule return_Null_ccorres)+
apply (rule ccorres_Cond_rhs_Seq)
apply (frule(1) cap_get_tag_isCap_unfolded_H_cap)
apply (frule small_frame_cap_is_mapped_alt)
apply (clarsimp simp: cap_small_frame_cap_lift cap_to_H_def
case_option_over_if
elim!: ccap_relationE simp del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (simp cong: if_cong del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq, simp_all del: Collect_const)[1]
apply (rule ccorres_rhs_assoc)+
apply (csymbr, csymbr, csymbr)
apply (ctac(no_vcg) add: unmapPage_ccorres)
apply (rule return_Null_ccorres)
apply wp
apply (rule return_Null_ccorres)
apply simp
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (frule(1) cap_get_tag_isCap_unfolded_H_cap)
apply (frule frame_cap_is_mapped_alt)
apply (clarsimp simp: cap_frame_cap_lift cap_to_H_def
case_option_over_if
elim!: ccap_relationE simp del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq, simp_all del: Collect_const)[1]
apply (rule ccorres_rhs_assoc)+
apply (csymbr, csymbr, csymbr, csymbr)
apply (ctac(no_vcg) add: unmapPage_ccorres)
apply (rule return_Null_ccorres)
apply wp
apply (rule return_Null_ccorres)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (simp add: if_1_0_0 from_bool_0 del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_page_table_cap_lift cap_to_H_def
case_option_over_if if_1_0_0
elim!: ccap_relationE
simp del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq)
apply (simp add: from_bool_0 to_bool_def)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply (ctac(no_vcg) add: unmapPageTable_ccorres)
apply (rule return_Null_ccorres)
apply wp
apply (simp add: to_bool_def)
apply (rule return_Null_ccorres)
apply (simp only: bool.simps)
apply (simp cong: option.case_cong
add: case_option_If)
apply (rule ccorres_cond_false_seq)
apply simp
apply (rule return_Null_ccorres)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply (simp only: if_1_0_0 simp_thms from_bool_0)
apply (rule ccorres_Cond_rhs_Seq)
apply (rule ccorres_rhs_assoc)+
apply csymbr+
apply (simp only: if_1_0_0 simp_thms)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_page_directory_cap_lift cap_to_H_def
case_option_over_if
elim!: ccap_relationE simp del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply (simp add: to_bool_def)
apply (ctac(no_vcg) add: deleteASID_ccorres)
apply (rule return_Null_ccorres)
apply wp
apply simp
apply (rule return_Null_ccorres)
apply (simp cong: option.case_cong add: case_option_If)
apply (rule ccorres_cond_false_seq, simp)
apply (rule return_Null_ccorres)
apply (clarsimp simp: from_bool_0 Collect_const_mem)
apply (intro conjI)
apply (clarsimp simp: valid_cap'_def)
apply (clarsimp simp: asid_bits_def)
apply clarsimp
apply (rule conjI)
apply (clarsimp simp: valid_cap'_def mask_def)
apply (frule cap_get_tag_isCap_unfolded_H_cap, rule refl)
subgoal by (clarsimp simp: cap_small_frame_cap_lift cap_to_H_def to_bool_def
vmsz_aligned_aligned_pageBits
elim!: ccap_relationE
split: option.split_asm if_split_asm)
apply (clarsimp simp: valid_cap'_def mask_def)
apply (frule(1) cap_get_tag_isCap_unfolded_H_cap)
subgoal by (clarsimp simp: cap_frame_cap_lift cap_to_H_def to_bool_def
vmsz_aligned_aligned_pageBits
elim!: ccap_relationE
split: option.split_asm if_split_asm)
apply (clarsimp simp: valid_cap'_def mask_def)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_page_table_cap_lift cap_to_H_def to_bool_def
elim!: ccap_relationE
split: option.split_asm if_split_asm)
apply (clarsimp simp: valid_cap'_def)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (frule cap_lift_page_directory_cap)
apply (clarsimp simp: ccap_relation_def cap_to_H_def capAligned_def
to_bool_def cap_page_directory_cap_lift_def
split: if_split_asm)
apply (rule conjI)
apply (clarsimp simp: asid_bits_def cap_page_directory_cap_lift_def)
apply clarsimp
apply clarsimp
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_asid_pool_cap_lift cap_to_H_def
elim!: ccap_relationE simp del: Collect_const)
apply (clarsimp simp: gen_framesize_to_H_def cap_get_tag_isCap_unfolded_H_cap)
apply (rule conjI)
apply clarsimp
apply (frule cap_get_tag_isCap_unfolded_H_cap, simp)
apply (clarsimp simp: cap_lift_small_frame_cap cap_to_H_simps
cap_small_frame_cap_lift_def Kernel_C.ARMSmallPage_def
elim!: ccap_relationE)
apply clarsimp
apply (frule(1) cap_get_tag_isCap_unfolded_H_cap)
apply (frule frame_cap_size)
apply (simp add: mask_eq_iff_w2p word_size del: frame_cap_size)
apply (clarsimp simp: cap_frame_cap_lift cap_to_H_def
vm_page_size_defs framesize_to_H_def
elim!: ccap_relationE simp del: Collect_const frame_cap_size
split: if_split)
apply (clarsimp simp: c_valid_cap_def cl_valid_cap_def
Kernel_C.ARMSmallPage_def)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_page_table_cap_lift cap_to_H_def
elim!: ccap_relationE simp del: Collect_const)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap)
done
lemma ccte_relation_ccap_relation:
"ccte_relation cte cte' \<Longrightarrow> ccap_relation (cteCap cte) (cte_C.cap_C cte')"
by (clarsimp simp: ccte_relation_def ccap_relation_def
cte_to_H_def map_option_Some_eq2
c_valid_cte_def)
lemma isFinalCapability_ccorres:
"ccorres (op = \<circ> from_bool) ret__unsigned_long_'
(cte_wp_at' (op = cte) slot and invs')
(UNIV \<inter> {s. cte_' s = Ptr slot}) []
(isFinalCapability cte) (Call isFinalCapability_'proc)"
apply (cinit lift: cte_')
apply (rule ccorres_Guard_Seq)
apply (simp add: Let_def del: Collect_const)
apply (rule ccorres_symb_exec_r)
apply (rule_tac xf'="mdb_'" in ccorres_abstract)
apply ceqv
apply (rule_tac P="mdb_node_to_H (mdb_node_lift rv') = cteMDBNode cte" in ccorres_gen_asm2)
apply csymbr
apply (rule_tac r'="op = \<circ> from_bool" and xf'="prevIsSameObject_'"
in ccorres_split_nothrow_novcg)
apply (rule ccorres_cond2[where R=\<top>])
apply (clarsimp simp: Collect_const_mem nullPointer_def)
apply (simp add: mdbPrev_to_H[symmetric])
apply (rule ccorres_from_vcg[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (simp add: return_def from_bool_def false_def)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_symb_exec_l[OF _ getCTE_inv getCTE_wp empty_fail_getCTE])
apply (rule_tac P="cte_wp_at' (op = cte) slot
and cte_wp_at' (op = rv) (mdbPrev (cteMDBNode cte))
and valid_cap' (cteCap rv)
and K (capAligned (cteCap cte) \<and> capAligned (cteCap rv))"
and P'=UNIV in ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def mdbPrev_to_H[symmetric])
apply (simp add: rf_sr_cte_at_validD)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (rule cmap_relationE1 [OF cmap_relation_cte], assumption+,
simp?, simp add: typ_heap_simps)+
apply (drule ccte_relation_ccap_relation)+
apply (rule exI, rule conjI, assumption)+
apply (auto)[1]
apply ceqv
apply (clarsimp simp del: Collect_const)
apply (rule ccorres_cond2[where R=\<top>])
apply (simp add: from_bool_0 Collect_const_mem)
apply (rule ccorres_return_C, simp+)[1]
apply csymbr
apply (rule ccorres_cond2[where R=\<top>])
apply (simp add: nullPointer_def Collect_const_mem mdbNext_to_H[symmetric])
apply (rule ccorres_return_C, simp+)[1]
apply (rule ccorres_symb_exec_l[OF _ getCTE_inv getCTE_wp empty_fail_getCTE])
apply (rule_tac P="cte_wp_at' (op = cte) slot
and cte_wp_at' (op = rva) (mdbNext (cteMDBNode cte))
and K (capAligned (cteCap rva) \<and> capAligned (cteCap cte))
and valid_cap' (cteCap cte)"
and P'=UNIV in ccorres_from_vcg_throws)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def from_bool_eq_if from_bool_0
mdbNext_to_H[symmetric] rf_sr_cte_at_validD)
apply (clarsimp simp: cte_wp_at_ctes_of split: if_split)
apply (rule cmap_relationE1 [OF cmap_relation_cte], assumption+,
simp?, simp add: typ_heap_simps)+
apply (drule ccte_relation_ccap_relation)+
apply (auto simp: false_def true_def from_bool_def split: bool.splits)[1]
apply (wp getCTE_wp')
apply (clarsimp simp add: guard_is_UNIV_def Collect_const_mem false_def
from_bool_0 true_def from_bool_def)
apply vcg
apply (rule conseqPre, vcg)
apply clarsimp
apply (clarsimp simp: Collect_const_mem)
apply (frule(1) rf_sr_cte_at_validD, simp add: typ_heap_simps)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (erule(1) cmap_relationE1 [OF cmap_relation_cte])
apply (simp add: typ_heap_simps)
apply (clarsimp simp add: ccte_relation_def map_option_Some_eq2)
by (auto,
auto dest!: ctes_of_valid' [OF _ invs_valid_objs']
elim!: valid_capAligned)
lemma cteDeleteOne_ccorres:
"ccorres dc xfdc
(invs' and cte_wp_at' (\<lambda>ct. w = -1 \<or> cteCap ct = NullCap
\<or> (\<forall>cap'. ccap_relation (cteCap ct) cap' \<longrightarrow> cap_get_tag cap' = w)) slot)
({s. gs_get_assn cteDeleteOne_'proc (ghost'state_' (globals s)) = w}
\<inter> {s. slot_' s = Ptr slot}) []
(cteDeleteOne slot) (Call cteDeleteOne_'proc)"
unfolding cteDeleteOne_def
apply (rule ccorres_symb_exec_l'
[OF _ getCTE_inv getCTE_sp empty_fail_getCTE])
apply (cinit' lift: slot_' cong: call_ignore_cong)
apply (rule ccorres_move_c_guard_cte)
apply csymbr
apply (rule ccorres_abstract_cleanup)
apply (rule ccorres_gen_asm2,
erule_tac t="cap_type = scast cap_null_cap"
and s="cteCap cte = NullCap"
in ssubst)
apply (clarsimp simp only: when_def unless_def dc_def[symmetric])
apply (rule ccorres_cond2[where R=\<top>])
apply (clarsimp simp: Collect_const_mem)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply (rule ccorres_Guard_Seq)
apply (rule ccorres_basic_srnoop)
apply (ctac(no_vcg) add: isFinalCapability_ccorres[where slot=slot])
apply (rule_tac A="invs' and cte_wp_at' (op = cte) slot"
in ccorres_guard_imp2[where A'=UNIV])
apply (simp add: split_def dc_def[symmetric]
del: Collect_const)
apply (rule ccorres_move_c_guard_cte)
apply (ctac(no_vcg) add: finaliseCap_True_standin_ccorres)
apply (rule ccorres_assert)
apply (simp add: dc_def[symmetric])
apply (ctac add: emptySlot_ccorres)
apply (simp add: pred_conj_def finaliseCapTrue_standin_simple_def)
apply (strengthen invs_mdb_strengthen' invs_urz)
apply (wp typ_at_lifts isFinalCapability_inv
| strengthen invs_valid_objs')+
apply (clarsimp simp: from_bool_def true_def irq_opt_relation_def
invs_pspace_aligned' cte_wp_at_ctes_of)
apply (erule(1) cmap_relationE1 [OF cmap_relation_cte])
apply (clarsimp simp: typ_heap_simps ccte_relation_ccap_relation)
apply (wp isFinalCapability_inv)
apply simp
apply (simp del: Collect_const add: false_def)
apply (rule ccorres_return_Skip)
apply (clarsimp simp: Collect_const_mem cte_wp_at_ctes_of)
apply (erule(1) cmap_relationE1 [OF cmap_relation_cte])
apply (clarsimp simp: typ_heap_simps cap_get_tag_isCap
dest!: ccte_relation_ccap_relation)
apply (auto simp: o_def)
done
(* FIXME : move *)
lemma of_int_uint_ucast:
"of_int (uint (x :: 'a::len word)) = (ucast x :: 'b::len word)"
by (metis ucast_def word_of_int)
lemma getIRQSlot_ccorres_stuff:
"\<lbrakk> (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow>
CTypesDefs.ptr_add (intStateIRQNode_' (globals s')) (uint (irq :: 10 word))
= Ptr (irq_node' s + 2 ^ cte_level_bits * ucast irq)"
apply (clarsimp simp add: rf_sr_def cstate_relation_def Let_def
cinterrupt_relation_def)
apply (simp add: objBits_simps cte_level_bits_def
size_of_def mult.commute mult.left_commute of_int_uint_ucast )
done
lemma deletingIRQHandler_ccorres:
"ccorres dc xfdc (invs' and (\<lambda>s. weak_sch_act_wf (ksSchedulerAction s) s))
(UNIV \<inter> {s. irq_opt_relation (Some irq) (irq_' s)}) []
(deletingIRQHandler irq) (Call deletingIRQHandler_'proc)"
apply (cinit lift: irq_' cong: call_ignore_cong)
apply (clarsimp simp: irq_opt_relation_def ptr_add_assertion_def dc_def[symmetric]
cong: call_ignore_cong )
apply (rule_tac r'="\<lambda>rv rv'. rv' = Ptr rv"
and xf'="slot_'" in ccorres_split_nothrow)
apply (simp add: sint_ucast_eq_uint is_down)
apply (rule ccorres_move_array_assertion_irq)
apply (rule ccorres_from_vcg[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: getIRQSlot_def liftM_def getInterruptState_def
locateSlot_conv)
apply (simp add: bind_def simpler_gets_def return_def
ucast_nat_def uint_up_ucast is_up)
apply (erule getIRQSlot_ccorres_stuff)
apply ceqv
apply (rule ccorres_symb_exec_l)
apply (rule ccorres_symb_exec_l)
apply (rule ccorres_Guard_Seq)
apply (rule ccorres_symb_exec_r)
apply (ctac add: cteDeleteOne_ccorres[where w="scast cap_notification_cap"])
apply vcg
apply (rule conseqPre, vcg, clarsimp simp: rf_sr_def
gs_set_assn_Delete_cstate_relation[unfolded o_def])
apply (wp getCTE_wp' | simp add: getSlotCap_def getIRQSlot_def locateSlot_conv
getInterruptState_def)+
apply vcg
apply (clarsimp simp: cap_get_tag_isCap ghost_assertion_data_get_def
ghost_assertion_data_set_def)
apply (simp add: cap_tag_defs)
apply (clarsimp simp: cte_wp_at_ctes_of Collect_const_mem
irq_opt_relation_def Kernel_C.maxIRQ_def)
apply (drule word_le_nat_alt[THEN iffD1])
apply (clarsimp simp:uint_0_iff unat_gt_0 uint_up_ucast is_up unat_def[symmetric])
done
lemma Zombie_new_spec:
"\<forall>s. \<Gamma>\<turnstile> ({s} \<inter> {s. type_' s = 32 \<or> type_' s < 31}) Call Zombie_new_'proc
{s'. cap_zombie_cap_lift (ret__struct_cap_C_' s') =
\<lparr> capZombieID_CL = \<^bsup>s\<^esup>ptr && ~~ mask (if \<^bsup>s\<^esup>type = (1 << 5) then 5 else unat (\<^bsup>s\<^esup>type + 1))
|| \<^bsup>s\<^esup>number___unsigned_long && mask (if \<^bsup>s\<^esup>type = (1 << 5) then 5 else unat (\<^bsup>s\<^esup>type + 1)),
capZombieType_CL = \<^bsup>s\<^esup>type && mask 6 \<rparr>
\<and> cap_get_tag (ret__struct_cap_C_' s') = scast cap_zombie_cap}"
apply vcg
apply (clarsimp simp: word_sle_def)
apply (simp add: mask_def word_log_esimps[where 'a=32, simplified])
apply clarsimp
apply (simp add: word_add_less_mono1[where k=1 and j="0x1F", simplified])
done
lemma mod_mask_drop:
"\<lbrakk> m = 2 ^ n; 0 < m; mask n && msk = mask n \<rbrakk> \<Longrightarrow>
(x mod m) && msk = x mod m"
by (simp add: word_mod_2p_is_mask
word_bw_assocs)
lemma irq_opt_relation_Some_ucast:
"\<lbrakk> x && mask 10 = x; ucast x \<le> (scast Kernel_C.maxIRQ :: 10 word) \<or> x \<le> (scast Kernel_C.maxIRQ :: word32) \<rbrakk>
\<Longrightarrow> irq_opt_relation (Some (ucast x)) (ucast ((ucast x):: 10 word))"
using ucast_ucast_mask[where x=x and 'a=10, symmetric]
apply (simp add: irq_opt_relation_def)
apply (rule conjI, clarsimp simp: irqInvalid_def Kernel_C.maxIRQ_def)
apply (simp only: unat_arith_simps )
apply (clarsimp simp: word_le_nat_alt Kernel_C.maxIRQ_def)
done
lemma upcast_ucast_id:
"len_of TYPE('a) \<le> len_of TYPE('b) \<Longrightarrow>
((ucast (a :: 'a::len word) :: 'b ::len word) = ucast b) \<Longrightarrow> (a = b)"
apply (rule word_eqI)
apply (simp add:word_size)
apply (drule_tac f = "%x. (x !! n)" in arg_cong)
apply (simp add:nth_ucast)
done
lemma mask_eq_ucast_eq:
"\<lbrakk> x && mask (len_of TYPE('a)) = (x :: ('c :: len word));
len_of TYPE('a) \<le> len_of TYPE('b)\<rbrakk>
\<Longrightarrow> ucast (ucast x :: ('a :: len word)) = (ucast x :: ('b :: len word))"
apply (rule word_eqI)
apply (drule_tac f = "\<lambda>x. (x !! n)" in arg_cong)
apply (auto simp:nth_ucast word_size)
done
lemma irq_opt_relation_Some_ucast':
"\<lbrakk> x && mask 10 = x; ucast x \<le> (scast Kernel_C.maxIRQ :: 10 word) \<or> x \<le> (scast Kernel_C.maxIRQ :: word32) \<rbrakk>
\<Longrightarrow> irq_opt_relation (Some (ucast x)) (ucast x)"
apply (rule_tac P = "%y. irq_opt_relation (Some (ucast x)) y" in subst[rotated])
apply (rule irq_opt_relation_Some_ucast[rotated])
apply simp+
apply (rule word_eqI)
apply (drule_tac f = "%x. (x !! n)" in arg_cong)
apply (simp add:nth_ucast and_bang word_size)
done
lemma ccap_relation_IRQHandler_mask:
"\<lbrakk> ccap_relation acap ccap; isIRQHandlerCap acap \<rbrakk>
\<Longrightarrow> capIRQ_CL (cap_irq_handler_cap_lift ccap) && mask 10
= capIRQ_CL (cap_irq_handler_cap_lift ccap)"
apply (simp only: cap_get_tag_isCap[symmetric])
apply (drule ccap_relation_c_valid_cap)
apply (simp add: c_valid_cap_def cap_irq_handler_cap_lift cl_valid_cap_def)
done
lemma prepare_thread_delete_ccorres:
"ccorres dc xfdc \<top> UNIV []
(prepareThreadDelete thread) (Call Arch_prepareThreadDelete_'proc)"
unfolding prepareThreadDelete_def
apply (rule ccorres_Call)
apply (rule Arch_prepareThreadDelete_impl[unfolded Arch_prepareThreadDelete_body_def])
apply (rule ccorres_return_Skip)
done
lemma finaliseCap_ccorres:
"\<And>final.
ccorres (\<lambda>rv rv'. ccap_relation (fst rv) (finaliseCap_ret_C.remainder_C rv')
\<and> irq_opt_relation (snd rv) (finaliseCap_ret_C.irq_C rv'))
ret__struct_finaliseCap_ret_C_'
(invs' and sch_act_simple and valid_cap' cap and (\<lambda>s. ksIdleThread s \<notin> capRange cap)
and (\<lambda>s. 2 ^ capBits cap \<le> gsMaxObjectSize s))
(UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. final_' s = from_bool final}
\<inter> {s. exposed_' s = from_bool flag (* dave has name wrong *)}) []
(finaliseCap cap final flag) (Call finaliseCap_'proc)"
apply (rule_tac F="capAligned cap" in Corres_UL_C.ccorres_req)
apply (clarsimp simp: valid_capAligned)
apply (case_tac "P :: bool" for P)
apply (rule ccorres_guard_imp2, erule finaliseCap_True_cases_ccorres)
apply simp
apply (subgoal_tac "\<exists>acap. (0 <=s (-1 :: word8)) \<or> acap = capCap cap")
prefer 2 apply simp
apply (erule exE)
apply (cinit lift: cap_' final_' exposed_' cong: call_ignore_cong)
apply csymbr
apply (simp del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq)
apply (clarsimp simp: cap_get_tag_isCap isCap_simps from_bool_neq_0
cong: if_cong simp del: Collect_const)
apply (clarsimp simp: word_sle_def)
apply (rule ccorres_if_lhs)
apply (rule ccorres_fail)
apply (simp add: liftM_def del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_split_nothrow_novcg)
apply (rule ccorres_call[where xf'="finaliseCap_ret_C.remainder_C \<circ> fc_ret_'"],
rule Arch_finaliseCap_ccorres)
apply simp+
apply (rule ceqv_refl)
apply (rule ccorres_rhs_assoc2, rule ccorres_split_throws)
apply (rule_tac P'="{s. rv' = finaliseCap_ret_C.remainder_C (fc_ret_' s)}"
in ccorres_from_vcg_throws[where P=\<top>])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def Collect_const_mem irq_opt_relation_def)
apply vcg
apply wp
apply (simp add: guard_is_UNIV_def Collect_const_mem)
apply (simp add: cap_get_tag_isCap Collect_False
del: Collect_const)
apply csymbr
apply (simp add: cap_get_tag_isCap Collect_False Collect_True
del: Collect_const)
apply (rule ccorres_if_lhs)
apply (simp, rule ccorres_fail)
apply (simp add: from_bool_0 Collect_True Collect_False false_def
del: Collect_const)
apply csymbr
apply (simp add: cap_get_tag_isCap Collect_False Collect_True
del: Collect_const)
apply (rule ccorres_if_lhs)
apply (simp add: Let_def)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap word_sle_def
return_def word_mod_less_divisor
less_imp_neq [OF word_mod_less_divisor])
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (clarsimp simp: isCap_simps capAligned_def
objBits_simps word_bits_conv
signed_shift_guard_simpler_32)
apply (rule conjI)
apply (simp add: word_less_nat_alt)
apply clarsimp
apply (simp add: ccap_relation_def cap_zombie_cap_lift)
apply (simp add: cap_to_H_def isZombieTCB_C_def ZombieTCB_C_def)
apply (simp add: less_mask_eq word_less_nat_alt less_imp_neq)
apply (simp add: mod_mask_drop[where n=5] mask_def[where n=5]
less_imp_neq [OF word_mod_less_divisor]
less_imp_neq Let_def)
apply (thin_tac "a = b" for a b)+
apply (subgoal_tac "P" for P)
apply (subst add.commute, subst unatSuc, assumption)+
apply (rule conjI)
apply (rule word_eqI)
apply (simp add: word_size word_ops_nth_size nth_w2p
less_Suc_eq_le is_aligned_nth)
apply (safe, simp_all)[1]
apply (simp add: shiftL_nat irq_opt_relation_def)
apply (rule trans, rule unat_power_lower32[symmetric])
apply (simp add: word_bits_conv)
apply (rule unat_cong, rule word_eqI)
apply (simp add: word_size word_ops_nth_size nth_w2p
is_aligned_nth less_Suc_eq_le)
apply (safe, simp_all)[1]
apply (subst add.commute, subst eq_diff_eq[symmetric])
apply (clarsimp simp: minus_one_norm)
apply (rule ccorres_if_lhs)
apply (simp add: Let_def getThreadCSpaceRoot_def locateSlot_conv
Collect_True Collect_False
del: Collect_const)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply csymbr
apply (rule ccorres_Guard_Seq)+
apply csymbr
apply (ctac(no_vcg) add: unbindNotification_ccorres)
apply (ctac(no_vcg) add: suspend_ccorres[OF cteDeleteOne_ccorres])
apply (ctac(no_vcg) add: prepare_thread_delete_ccorres)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: word_sle_def return_def)
apply (subgoal_tac "cap_get_tag capa = scast cap_thread_cap")
apply (drule(1) cap_get_tag_to_H)
apply (clarsimp simp: isCap_simps capAligned_def)
apply (simp add: ccap_relation_def cap_zombie_cap_lift)
apply (simp add: cap_to_H_def isZombieTCB_C_def ZombieTCB_C_def
mask_def)
apply (simp add: cte_level_bits_def tcbCTableSlot_def
Kernel_C.tcbCTable_def tcbCNodeEntries_def
word_bool_alg.conj_disj_distrib2
word_bw_assocs)
apply (simp add: objBits_simps ctcb_ptr_to_tcb_ptr_def)
apply (frule is_aligned_add_helper[where p="tcbptr - ctcb_offset" and d=ctcb_offset for tcbptr])
apply (simp add: ctcb_offset_def)
apply (simp add: mask_def irq_opt_relation_def)
apply (simp add: cap_get_tag_isCap)
apply wp+
apply (rule ccorres_if_lhs)
apply (simp add: Let_def)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def irq_opt_relation_def)
apply (simp add: isArchCap_T_isArchObjectCap[symmetric]
del: Collect_const)
apply (rule ccorres_if_lhs)
apply (simp add: Collect_False Collect_True Let_def true_def
del: Collect_const)
apply (rule_tac P="(capIRQ cap) \<le> ARM.maxIRQ" in ccorres_gen_asm)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_symb_exec_r)
apply (rule_tac xf'=irq_' in ccorres_abstract,ceqv)
apply (rule_tac P="rv' = ucast (capIRQ cap)" in ccorres_gen_asm2)
apply (ctac(no_vcg) add: deletingIRQHandler_ccorres)
apply (rule ccorres_from_vcg_throws[where P=\<top> ])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def)
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (simp add: ccap_relation_NullCap_iff split: if_split)
apply (frule(1) ccap_relation_IRQHandler_mask)
apply (erule irq_opt_relation_Some_ucast)
apply (simp add: ARM.maxIRQ_def Kernel_C.maxIRQ_def)
apply wp
apply vcg
apply (rule conseqPre,vcg)
apply clarsimp
apply (rule ccorres_if_lhs)
apply simp
apply (rule ccorres_fail)
apply (rule ccorres_add_return, rule ccorres_split_nothrow_novcg[where r'=dc and xf'=xfdc])
apply (rule ccorres_Cond_rhs)
apply (simp add: ccorres_cond_iffs dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (rule ccorres_Cond_rhs)
apply (simp add: ccorres_cond_iffs dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (rule ccorres_Cond_rhs)
apply (rule ccorres_inst[where P=\<top> and P'=UNIV])
apply simp
apply (rule ccorres_Cond_rhs)
apply (simp add: ccorres_cond_iffs dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (simp add: ccorres_cond_iffs dc_def[symmetric])
apply (rule ccorres_return_Skip)
apply (rule ceqv_refl)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def ccap_relation_NullCap_iff
irq_opt_relation_def)
apply wp
apply (simp add: guard_is_UNIV_def)
apply (clarsimp simp: cap_get_tag_isCap word_sle_def Collect_const_mem
false_def from_bool_def)
apply (intro impI conjI)
apply (clarsimp split: bool.splits)
apply (clarsimp split: bool.splits)
apply (clarsimp simp: valid_cap'_def isCap_simps)
apply (clarsimp simp: isCap_simps capRange_def capAligned_def)
apply (clarsimp simp: isCap_simps valid_cap'_def)
apply (clarsimp simp: isCap_simps capRange_def capAligned_def)
apply (clarsimp simp: isCap_simps valid_cap'_def )
apply clarsimp
apply (clarsimp simp: isCap_simps valid_cap'_def )
apply (clarsimp simp: tcb_ptr_to_ctcb_ptr_def ccap_relation_def isCap_simps
c_valid_cap_def cap_thread_cap_lift_def cap_to_H_def
ctcb_ptr_to_tcb_ptr_def Let_def
split: option.splits cap_CL.splits if_splits)
apply clarsimp
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (clarsimp simp: isCap_simps from_bool_def false_def)
apply (clarsimp simp: tcb_cnode_index_defs ptr_add_assertion_def)
apply clarsimp
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (frule(1) ccap_relation_IRQHandler_mask)
apply (clarsimp simp: isCap_simps irqInvalid_def
valid_cap'_def ARM.maxIRQ_def
Kernel_C.maxIRQ_def)
apply (rule irq_opt_relation_Some_ucast', simp)
apply (clarsimp simp: isCap_simps irqInvalid_def
valid_cap'_def ARM.maxIRQ_def
Kernel_C.maxIRQ_def)
apply fastforce
apply clarsimp
apply (frule cap_get_tag_to_H, erule(1) cap_get_tag_isCap [THEN iffD2])
apply (frule(1) ccap_relation_IRQHandler_mask)
apply (clarsimp simp add:mask_eq_ucast_eq)
done
end
end
|
/-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Yury Kudryashov
! This file was ported from Lean 3 source module topology.paracompact
! leanprover-community/mathlib commit 2705404e701abc6b3127da906f40bae062a169c9
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Topology.SubsetProperties
import Mathlib.Topology.Separation
import Mathlib.Data.Option.Basic
/-!
# Paracompact topological spaces
A topological space `X` is said to be paracompact if every open covering of `X` admits a locally
finite refinement.
The definition requires that each set of the new covering is a subset of one of the sets of the
initial covering. However, one can ensure that each open covering `s : ι → Set X` admits a *precise*
locally finite refinement, i.e., an open covering `t : ι → Set X` with the same index set such that
`∀ i, t i ⊆ s i`, see lemma `precise_refinement`. We also provide a convenience lemma
`precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the
whole space.
We also prove the following facts.
* Every compact space is paracompact, see instance `paracompact_of_compact`.
* A locally compact sigma compact Hausdorff space is paracompact, see instance
`paracompact_of_locallyCompact_sigmaCompact`. Moreover, we can choose a locally finite
refinement with sets in a given collection of filter bases of `𝓝 x, `x : X`, see
`refinement_of_locallyCompact_sigmaCompact_of_nhds_basis`. For example, in a proper metric space
every open covering `⋃ i, s i` admits a refinement `⋃ i, Metric.ball (c i) (r i)`.
* Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in
the instance graph.
* Every `EMetricSpace` is a paracompact space, see instance `EMetricSpace.ParacompactSpace` in
`Topology/MetricSpace/EMetricParacompact`.
## TODO
Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem).
## Tags
compact space, paracompact space, locally finite covering
-/
open Set Filter Function
open Filter Topology
universe u v
/-- A topological space is called paracompact, if every open covering of this space admits a locally
finite refinement. We use the same universe for all types in the definition to avoid creating a
class like `ParacompactSpace.{u v}`. Due to lemma `precise_refinement` below, every open covering
`s : α → Set X` indexed on `α : Type v` has a *precise* locally finite refinement, i.e., a locally
finite refinement `t : α → Set X` indexed on the same type such that each `∀ i, t i ⊆ s i`. -/
class ParacompactSpace (X : Type v) [TopologicalSpace X] : Prop where
/-- Every open cover of a paracompact space assumes a locally finite refinement. -/
locallyFinite_refinement :
∀ (α : Type v) (s : α → Set X) (_ : ∀ a, IsOpen (s a)) (_ : (⋃ a, s a) = univ),
∃ (β : Type v) (t : β → Set X) (_ : ∀ b, IsOpen (t b)) (_ : (⋃ b, t b) = univ),
LocallyFinite t ∧ ∀ b, ∃ a, t b ⊆ s a
#align paracompact_space ParacompactSpace
variable {ι : Type u} {X : Type v} [TopologicalSpace X]
/-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is,
one indexed on the same type with each open set contained in the corresponding original one. -/
theorem precise_refinement [ParacompactSpace X] (u : ι → Set X) (uo : ∀ a, IsOpen (u a))
(uc : (⋃ i, u i) = univ) :
∃ v : ι → Set X, (∀ a, IsOpen (v a)) ∧ (⋃ i, v i) = univ ∧ LocallyFinite v ∧ ∀ a, v a ⊆ u a :=
by
-- Apply definition to `range u`, then turn existence quantifiers into functions using `choose`
have := ParacompactSpace.locallyFinite_refinement (range u) (fun r ↦ (r : Set X))
(SetCoe.forall.2 <| forall_range_iff.2 uo) (by rwa [← unionₛ_range, Subtype.range_coe])
simp only [SetCoe.exists, exists_range_iff', unionᵢ_eq_univ_iff, exists_prop] at this
choose α t hto hXt htf ind hind using this
choose t_inv ht_inv using hXt
choose U hxU hU using htf
-- Send each `i` to the union of `t a` over `a ∈ ind ⁻¹' {i}`
refine' ⟨fun i ↦ ⋃ (a : α) (_ha : ind a = i), t a, _, _, _, _⟩
· exact fun a ↦ isOpen_unionᵢ fun a ↦ isOpen_unionᵢ fun _ ↦ hto a
· simp only [eq_univ_iff_forall, mem_unionᵢ]
exact fun x ↦ ⟨ind (t_inv x), _, rfl, ht_inv _⟩
· refine' fun x ↦ ⟨U x, hxU x, ((hU x).image ind).subset _⟩
simp only [subset_def, mem_unionᵢ, mem_setOf_eq, Set.Nonempty, mem_inter_iff]
rintro i ⟨y, ⟨a, rfl, hya⟩, hyU⟩
exact mem_image_of_mem _ ⟨y, hya, hyU⟩
· simp only [subset_def, mem_unionᵢ]
rintro i x ⟨a, rfl, hxa⟩
exact hind _ hxa
#align precise_refinement precise_refinement
/-- In a paracompact space, every open covering of a closed set admits a locally finite refinement
indexed by the same type. -/
theorem precise_refinement_set [ParacompactSpace X] {s : Set X} (hs : IsClosed s) (u : ι → Set X)
(uo : ∀ i, IsOpen (u i)) (us : s ⊆ ⋃ i, u i) :
∃ v : ι → Set X, (∀ i, IsOpen (v i)) ∧ (s ⊆ ⋃ i, v i) ∧ LocallyFinite v ∧ ∀ i, v i ⊆ u i := by
-- Porting note: Added proof of uc
have uc : (unionᵢ fun i => Option.elim' (sᶜ) u i) = univ := by
apply Subset.antisymm (subset_univ _)
· simp_rw [← compl_union_self s, Option.elim', unionᵢ_option]
apply union_subset_union_right (sᶜ) us
rcases precise_refinement (Option.elim' (sᶜ) u) (Option.forall.2 ⟨isOpen_compl_iff.2 hs, uo⟩)
uc with
⟨v, vo, vc, vf, vu⟩
refine' ⟨v ∘ some, fun i ↦ vo _, _, vf.comp_injective (Option.some_injective _), fun i ↦ vu _⟩
· simp only [unionᵢ_option, ← compl_subset_iff_union] at vc
exact Subset.trans (subset_compl_comm.1 <| vu Option.none) vc
#align precise_refinement_set precise_refinement_set
-- See note [lower instance priority]
/-- A compact space is paracompact. -/
instance (priority := 100) paracompact_of_compact [CompactSpace X] : ParacompactSpace X := by
-- the proof is trivial: we choose a finite subcover using compactness, and use it
refine' ⟨fun ι s ho hu ↦ _⟩
rcases isCompact_univ.elim_finite_subcover _ ho hu.ge with ⟨T, hT⟩
have := hT; simp only [subset_def, mem_unionᵢ] at this
choose i _ _ using fun x ↦ this x (mem_univ x)
refine' ⟨(T : Set ι), fun t ↦ s t, fun t ↦ ho _, _, locallyFinite_of_finite _,
fun t ↦ ⟨t, Subset.rfl⟩⟩
simpa only [unionᵢ_coe_set, ← univ_subset_iff]
#align paracompact_of_compact paracompact_of_compact
/-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set
in `X`. Suppose that for each `x ∈ s` the sets `B x : ι x → Set X` with the predicate
`p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering
`fun i ↦ B (c i) (r i)` of `s` such that all “centers” `c i` belong to `s` and each `r i` satisfies
`p (c i)`.
The notation is inspired by the case `B x r = Metric.ball x r` but the theorem applies to
`nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then
the user should use a basis obtained by `Filter.HasBasis.restrict_subset` or a similar lemma, see
the proof of `paracompact_of_locallyCompact_sigmaCompact` for an example.
The formalization is based on two [ncatlab](https://ncatlab.org/) proofs:
* [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact);
* [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds).
See also `refinement_of_locallyCompact_sigmaCompact_of_nhds_basis` for a version of this lemma
dealing with a covering of the whole space.
In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible
to choose `α = X`. This fact is not yet formalized in `mathlib`. -/
theorem refinement_of_locallyCompact_sigmaCompact_of_nhds_basis_set [LocallyCompactSpace X]
[SigmaCompactSpace X] [T2Space X] {ι : X → Type u} {p : ∀ x, ι x → Prop} {B : ∀ x, ι x → Set X}
{s : Set X} (hs : IsClosed s) (hB : ∀ x ∈ s, (𝓝 x).HasBasis (p x) (B x)) :
∃ (α : Type v) (c : α → X) (r : ∀ a, ι (c a)),
(∀ a, c a ∈ s ∧ p (c a) (r a)) ∧
(s ⊆ ⋃ a, B (c a) (r a)) ∧ LocallyFinite fun a ↦ B (c a) (r a) := by
classical
-- For technical reasons we prepend two empty sets to the sequence `CompactExhaustion.choice X`
set K' : CompactExhaustion X := CompactExhaustion.choice X
set K : CompactExhaustion X := K'.shiftr.shiftr
set Kdiff := fun n ↦ K (n + 1) \ interior (K n)
-- Now we restate some properties of `CompactExhaustion` for `K`/`Kdiff`
have hKcov : ∀ x, x ∈ Kdiff (K'.find x + 1) := by
intro x
simpa only [K'.find_shiftr] using
diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x)
have Kdiffc : ∀ n, IsCompact (Kdiff n ∩ s) :=
fun n ↦ ((K.isCompact _).diff isOpen_interior).inter_right hs
-- Next we choose a finite covering `B (c n i) (r n i)` of each
-- `Kdiff (n + 1) ∩ s` such that `B (c n i) (r n i) ∩ s` is disjoint with `K n`
have : ∀ (n) (x : ↑(Kdiff (n + 1) ∩ s)), K nᶜ ∈ 𝓝 (x : X) :=
fun n x ↦ IsOpen.mem_nhds (K.isClosed n).isOpen_compl
fun hx' ↦ x.2.1.2 <| K.subset_interior_succ _ hx'
-- Porting note: Commented out `haveI` for now.
--haveI : ∀ (n) (x : ↑(Kdiff n ∩ s)), Nonempty (ι x) := fun n x ↦ (hB x x.2.2).nonempty
choose! r hrp hr using fun n (x : ↑(Kdiff (n + 1) ∩ s)) ↦ (hB x x.2.2).mem_iff.1 (this n x)
have hxr : ∀ (n x) (hx : x ∈ Kdiff (n + 1) ∩ s), B x (r n ⟨x, hx⟩) ∈ 𝓝 x := fun n x hx ↦
(hB x hx.2).mem_of_mem (hrp _ ⟨x, hx⟩)
choose T hT using fun n ↦ (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n)
set T' : ∀ n, Set ↑(Kdiff (n + 1) ∩ s) := fun n ↦ T n
-- Finally, we take the union of all these coverings
refine' ⟨Σn, T' n, fun a ↦ a.2, fun a ↦ r a.1 a.2, _, _, _⟩
· rintro ⟨n, x, hx⟩
exact ⟨x.2.2, hrp _ _⟩
· refine' fun x hx ↦ mem_unionᵢ.2 _
rcases mem_unionᵢ₂.1 (hT _ ⟨hKcov x, hx⟩) with ⟨⟨c, hc⟩, hcT, hcx⟩
exact ⟨⟨_, ⟨c, hc⟩, hcT⟩, hcx⟩
· intro x
refine'
⟨interior (K (K'.find x + 3)),
IsOpen.mem_nhds isOpen_interior (K.subset_interior_succ _ (hKcov x).1), _⟩
have : (⋃ k ≤ K'.find x + 2, range <| Sigma.mk k : Set (Σn, T' n)).Finite :=
(finite_le_nat _).bunionᵢ fun k _ ↦ finite_range _
apply this.subset
rintro ⟨k, c, hc⟩
simp only [mem_unionᵢ, mem_setOf_eq, mem_image, Subtype.coe_mk]
rintro ⟨x, hxB : x ∈ B c (r k c), hxK⟩
refine' ⟨k, _, ⟨c, hc⟩, rfl⟩
have := (mem_compl_iff _ _).1 (hr k c hxB)
revert this
contrapose!
simp only [ge_iff_le, not_le]
exact fun hnk ↦ K.subset hnk (interior_subset hxK)
#align refinement_of_locally_compact_sigma_compact_of_nhds_basis_set refinement_of_locallyCompact_sigmaCompact_of_nhds_basis_set
/-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each
`x` the sets `B x : ι x → Set X` with the predicate `p x : ι x → Prop` form a basis of the filter
`𝓝 x`. Then there exists a locally finite covering `fun i ↦ B (c i) (r i)` of `X` such that each
`r i` satisfies `p (c i)`.
The notation is inspired by the case `B x r = Metric.ball x r` but the theorem applies to
`nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then
the user should use a basis obtained by `Filter.HasBasis.restrict_subset` or a similar lemma, see
the proof of `paracompact_of_locallyCompact_sigmaCompact` for an example.
The formalization is based on two [ncatlab](https://ncatlab.org/) proofs:
* [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact);
* [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds).
See also `refinement_of_locallyCompact_sigmaCompact_of_nhds_basis_set` for a version of this lemma
dealing with a covering of a closed set.
In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible
to choose `α = X`. This fact is not yet formalized in `mathlib`. -/
theorem refinement_of_locallyCompact_sigmaCompact_of_nhds_basis [LocallyCompactSpace X]
[SigmaCompactSpace X] [T2Space X] {ι : X → Type u} {p : ∀ x, ι x → Prop} {B : ∀ x, ι x → Set X}
(hB : ∀ x, (𝓝 x).HasBasis (p x) (B x)) :
∃ (α : Type v) (c : α → X) (r : ∀ a, ι (c a)),
(∀ a, p (c a) (r a)) ∧ (⋃ a, B (c a) (r a)) = univ ∧ LocallyFinite fun a ↦ B (c a) (r a) :=
let ⟨α, c, r, hp, hU, hfin⟩ :=
refinement_of_locallyCompact_sigmaCompact_of_nhds_basis_set isClosed_univ fun x _ ↦ hB x
⟨α, c, r, fun a ↦ (hp a).2, univ_subset_iff.1 hU, hfin⟩
#align refinement_of_locally_compact_sigma_compact_of_nhds_basis refinement_of_locallyCompact_sigmaCompact_of_nhds_basis
-- See note [lower instance priority]
/-- A locally compact sigma compact Hausdorff space is paracompact. See also
`refinement_of_locallyCompact_sigmaCompact_of_nhds_basis` for a more precise statement. -/
instance (priority := 100) paracompact_of_locallyCompact_sigmaCompact [LocallyCompactSpace X]
[SigmaCompactSpace X] [T2Space X] : ParacompactSpace X := by
refine' ⟨fun α s ho hc ↦ _⟩
choose i hi using unionᵢ_eq_univ_iff.1 hc
have : ∀ x : X, (𝓝 x).HasBasis (fun t : Set X ↦ (x ∈ t ∧ IsOpen t) ∧ t ⊆ s (i x)) id :=
fun x : X ↦ (nhds_basis_opens x).restrict_subset (IsOpen.mem_nhds (ho (i x)) (hi x))
rcases refinement_of_locallyCompact_sigmaCompact_of_nhds_basis this with
⟨β, c, t, hto, htc, htf⟩
exact ⟨β, t, fun x ↦ (hto x).1.2, htc, htf, fun b ↦ ⟨i <| c b, (hto b).2⟩⟩
#align paracompact_of_locally_compact_sigma_compact paracompact_of_locallyCompact_sigmaCompact
/- Dieudonné's theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof
at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/
theorem normal_of_paracompact_t2 [T2Space X] [ParacompactSpace X] : NormalSpace X := by
-- First we show how to go from points to a set on one side.
have : ∀ s t : Set X, IsClosed s → IsClosed t →
(∀ x ∈ s, ∃ u v, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ t ⊆ v ∧ Disjoint u v) →
∃ u v, IsOpen u ∧ IsOpen v ∧ s ⊆ u ∧ t ⊆ v ∧ Disjoint u v := by
/- For each `x ∈ s` we choose open disjoint `u x ∋ x` and `v x ⊇ t`. The sets `u x` form an
open covering of `s`. We choose a locally finite refinement `u' : s → Set X`, then
`⋃ i, u' i` and `(closure (⋃ i, u' i))ᶜ` are disjoint open neighborhoods of `s` and `t`. -/
intro s t hs _ H
choose u v hu hv hxu htv huv using SetCoe.forall'.1 H
rcases precise_refinement_set hs u hu fun x hx ↦ mem_unionᵢ.2 ⟨⟨x, hx⟩, hxu _⟩ with
⟨u', hu'o, hcov', hu'fin, hsub⟩
refine' ⟨⋃ i, u' i, closure (⋃ i, u' i)ᶜ, isOpen_unionᵢ hu'o, isClosed_closure.isOpen_compl,
hcov', _, disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)⟩
rw [hu'fin.closure_unionᵢ, compl_unionᵢ, subset_interᵢ_iff]
refine' fun i x hxt hxu ↦
absurd (htv i hxt) (closure_minimal _ (isClosed_compl_iff.2 <| hv _) hxu)
exact fun y hyu hyv ↦ (huv i).le_bot ⟨hsub _ hyu, hyv⟩
-- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`.
refine' ⟨fun s t hs ht hst ↦ this s t hs ht fun x hx ↦ _⟩
rcases this t {x} ht isClosed_singleton fun y hy ↦ (by
simp_rw [singleton_subset_iff]
exact t2_separation (hst.symm.ne_of_mem hy hx))
with ⟨v, u, hv, hu, htv, hxu, huv⟩
exact ⟨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symm⟩
#align normal_of_paracompact_t2 normal_of_paracompact_t2
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""WaveNet construction"""
from __future__ import with_statement, print_function, absolute_import
import math
import numpy as np
from mindspore import nn, Tensor
import mindspore.common.dtype as mstype
from mindspore.ops import operations as P
from wavenet_vocoder import upsample
from .modules import Embedding
from .modules import Conv1d1x1
from .modules import ResidualConv1dGLU
from .mixture import sample_from_discretized_mix_logistic
from .mixture import sample_from_mix_gaussian
from .mixture import sample_from_mix_onehotcategorical
class WaveNet(nn.Cell):
"""
WaveNet model definition. Only local condition is supported
Args:
out_channels (int): Output channels. If input_type is mu-law quantized one-hot vecror, it should equal to the
quantize channels. Otherwise, it equals to num_mixtures x 3. Default: 256.
layers (int): Number of ResidualConv1dGLU layers
stacks (int): Number of dilation cycles
residual_channels (int): Residual input / output channels
gate_channels (int): Gated activation channels.
skip_out_channels (int): Skip connection channels.
kernel_size (int): Kernel size .
dropout (float): Dropout rate.
cin_channels (int): Local conditioning channels. If given negative value, local conditioning is disabled.
gin_channels (int): Global conditioning channels. If given negative value, global conditioning is disabled.
n_speakers (int): Number of speakers. This is used when global conditioning is enabled.
upsample_conditional_features (bool): Whether upsampling local conditioning features by resize_nearestneighbor
and conv or not.
scalar_input (Bool): If True, scalar input ([-1, 1]) is expected, otherwise, quantized one-hot vector
is expected.
use_speaker_embedding (Bool): Use speaker embedding or Not.
"""
def __init__(self, out_channels=256, layers=20, stacks=2,
residual_channels=512,
gate_channels=512,
skip_out_channels=512,
kernel_size=3, dropout=1 - 0.95,
cin_channels=-1, gin_channels=-1, n_speakers=None,
upsample_conditional_features=False,
upsample_net="ConvInUpsampleNetwork",
upsample_params=None,
scalar_input=False,
use_speaker_embedding=False,
output_distribution="Logistic",
cin_pad=0,
):
super(WaveNet, self).__init__()
self.transpose_op = P.Transpose()
self.softmax = P.Softmax(axis=1)
self.reshape_op = P.Reshape()
self.zeros_op = P.Zeros()
self.ones_op = P.Ones()
self.relu_op = P.ReLU()
self.squeeze_op = P.Squeeze()
self.expandim_op = P.ExpandDims()
self.transpose_op = P.Transpose()
self.tile_op = P.Tile()
self.scalar_input = scalar_input
self.out_channels = out_channels
self.cin_channels = cin_channels
self.output_distribution = output_distribution
self.fack_data = P.Zeros()
assert layers % stacks == 0
layers_per_stack = layers // stacks
if scalar_input:
self.first_conv = Conv1d1x1(1, residual_channels)
else:
self.first_conv = Conv1d1x1(out_channels, residual_channels)
conv_layers = []
for layer in range(layers):
dilation = 2 ** (layer % layers_per_stack)
conv = ResidualConv1dGLU(
residual_channels, gate_channels,
kernel_size=kernel_size,
skip_out_channels=skip_out_channels,
bias=True,
dropout=dropout,
dilation=dilation,
cin_channels=cin_channels,
gin_channels=gin_channels)
conv_layers.append(conv)
self.conv_layers = nn.CellList(conv_layers)
self.last_conv_layers = nn.CellList([
nn.ReLU(),
Conv1d1x1(skip_out_channels, skip_out_channels),
nn.ReLU(),
Conv1d1x1(skip_out_channels, out_channels)])
if gin_channels > 0 and use_speaker_embedding:
assert n_speakers is not None
self.embed_speakers = Embedding(
n_speakers, gin_channels, padding_idx=None, std=0.1)
else:
self.embed_speakers = None
if upsample_conditional_features:
self.upsample_net = getattr(upsample, upsample_net)(**upsample_params)
else:
self.upsample_net = None
self.factor = math.sqrt(1.0 / len(self.conv_layers))
def _expand_global_features(self, batch_size, time_step, g_fp, is_expand=True):
"""Expand global conditioning features to all time steps
Args:
batch_size (int): Batch size.
time_step (int): Time length.
g_fp (Tensor): Global features, (B x C) or (B x C x 1).
is_expand (bool) : Expanded global conditioning features
Returns:
Tensor: B x C x T or B x T x C or None
"""
if g_fp is None:
return None
if len(g_fp.shape) == 2:
g_fp = self.expandim_op(g_fp, -1)
else:
g_fp = g_fp
if is_expand:
expand_fp = self.tile_op(g_fp, (batch_size, 1, time_step))
return expand_fp
expand_fp = self.tile_op(g_fp, (batch_size, 1, time_step))
expand_fp = self.transpose_op(expand_fp, (0, 2, 1))
return expand_fp
def construct(self, x, c=None, g=None, softmax=False):
"""
Args:
x (Tensor): One-hot encoded audio signal
c (Tensor): Local conditioning feature
g (Tensor): Global conditioning feature
softmax (bool): Whether use softmax or not
Returns:
Tensor: Net output
"""
g = None
B, _, T = x.shape
if g is not None:
if self.embed_speakers is not None:
g = self.embed_speakers(self.reshape_op(g, (B, -1)))
g = self.transpose_op(g, (0, 2, 1))
g_bct = self._expand_global_features(B, T, g, is_expand=True)
if c is not None and self.upsample_net is not None:
c = self.upsample_net(c)
x = self.first_conv(x)
skips = 0
for f in self.conv_layers:
x, h = f(x, c, g_bct)
skips += h
skips *= self.factor
x = skips
for f in self.last_conv_layers:
x = f(x)
x = self.softmax(x) if softmax else x
return x
def relu_numpy(self, inX):
"""numpy relu function"""
return np.maximum(0, inX)
def softmax_numpy(self, x):
""" numpy softmax function """
x -= np.max(x, axis=1, keepdims=True)
return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True)
def incremental_forward(self, initial_input=None, c=None, g=None,
T=100, test_inputs=None,
tqdm=lambda x: x, softmax=True, quantize=True,
log_scale_min=-50.0, is_numpy=True):
"""
Incremental forward. Current output depends on last output.
Args:
initial_input (Tensor): Initial input, the shape is B x C x 1
c (Tensor): Local conditioning feature, the shape is B x C x T
g (Tensor): Global conditioning feature, the shape is B x C or B x C x 1
T (int): decoding time step.
test_inputs: Teacher forcing inputs (for debugging)
tqdm (lamda): tqmd
softmax (bool): Whether use softmax or not
quantize (bool): Whether quantize softmax output in last step when decoding current step
log_scale_min (float): Log scale minimum value
Returns:
Tensor: Predicted on-hot encoded samples or scalar vector depending on loss type
"""
self.clear_buffer()
B = 1
if test_inputs is not None:
if self.scalar_input:
if test_inputs.shape[1] == 1:
test_inputs = self.transpose_op(test_inputs, (0, 2, 1))
else:
if test_inputs.shape[1] == self.out_channels:
test_inputs = self.transpose_op(test_inputs, (0, 2, 1))
B = test_inputs.shape[0]
if T is None:
T = test_inputs.shape[1]
else:
T = max(T, test_inputs.shape[1])
T = int(T)
# Global conditioning
if g is not None:
if self.embed_speakers is not None:
g = self.embed_speakers(self.reshape_op(g, (B, -1)))
g = self.transpose_op(g, (0, 2, 1))
assert g.dim() == 3
g_btc = self._expand_global_features(B, T, g, is_expand=False)
# Local conditioning
if c is not None:
B = c.shape[0]
if self.upsample_net is not None:
c = self.upsample_net(c)
assert c.shape[-1] == T
if c.shape[-1] == T:
c = self.transpose_op(c, (0, 2, 1))
outputs = []
if initial_input is None:
if self.scalar_input:
initial_input = self.zeros_op((B, 1, 1), mstype.float32)
else:
initial_input = np.zeros((B, 1, self.out_channels), np.float32)
initial_input[:, :, 127] = 1
initial_input = Tensor(initial_input)
else:
if initial_input.shape[1] == self.out_channels:
initial_input = self.transpose_op(initial_input, (0, 2, 1))
if is_numpy:
current_input = initial_input.asnumpy()
else:
current_input = initial_input
for t in tqdm(range(T)):
if test_inputs is not None and t < test_inputs.shape[1]:
current_input = self.expandim_op(test_inputs[:, t, :], 1)
else:
if t > 0:
if not is_numpy:
current_input = Tensor(outputs[-1])
else:
current_input = outputs[-1]
# Conditioning features for single time step
ct = None if c is None else self.expandim_op(c[:, t, :], 1)
gt = None if g is None else self.expandim_op(g_btc[:, t, :], 1)
x = current_input
if is_numpy:
ct = ct.asnumpy()
x = self.first_conv.incremental_forward(x, is_numpy=is_numpy)
skips = 0
for f in self.conv_layers:
x, h = f.incremental_forward(x, ct, gt, is_numpy=is_numpy)
skips += h
skips *= self.factor
x = skips
for f in self.last_conv_layers:
try:
x = f.incremental_forward(x, is_numpy=is_numpy)
except AttributeError:
if is_numpy:
x = self.relu_numpy(x)
else:
x = self.relu_op(x)
# Generate next input by sampling
if not is_numpy:
x = x.asnumpy()
if self.scalar_input:
if self.output_distribution == "Logistic":
x = sample_from_discretized_mix_logistic(x.reshape((B, -1, 1)), log_scale_min=log_scale_min)
elif self.output_distribution == "Normal":
x = sample_from_mix_gaussian(x.reshape((B, -1, 1)), log_scale_min=log_scale_min)
else:
assert False
else:
x = self.softmax_numpy(np.reshape(x, (B, -1))) if softmax else np.reshape(x, (B, -1))
if quantize:
x = sample_from_mix_onehotcategorical(x)
outputs += [x]
# T x B x C
outputs = np.stack(outputs, 0)
# B x C x T
outputs = np.transpose(outputs, (1, 2, 0))
self.clear_buffer()
return outputs
def clear_buffer(self):
"""clear buffer"""
self.first_conv.clear_buffer()
for f in self.conv_layers:
f.clear_buffer()
for f in self.last_conv_layers:
try:
f.clear_buffer()
except AttributeError:
pass
|
// Copyright Jeroen Habraken 2011.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file ../../../LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_TEST_MODULE default_value
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
#include <boost/coerce.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(default_value) {
using namespace boost;
BOOST_CHECK_EQUAL(coerce::as_default<int>("XXX"), 0);
BOOST_CHECK_EQUAL(coerce::as_default<int>("XXX", 23), 23);
}
|
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.Plot.Figure.Plot
-- Copyright : (c) A. V. H. McPhail 2010
-- License : BSD3
--
-- Maintainer : haskell.vivian.mcphail <at> gmail <dot> com
-- Stability : provisional
-- Portability : portable
--
-- Creation and manipulation of 'Plot's
--
-----------------------------------------------------------------------------
module Graphics.Rendering.Plot.Figure.Plot (
Plot
-- * Plot elements
, Border
, setBorder
, setPlotBackgroundColour
, setPlotPadding
, withHeading
-- * Series data
, D.Abscissa(), D.Ordinate(), D.Dataset()
, SeriesLabel
, D.FormattedSeries()
, D.line, D.point, D.linepoint
, D.impulse, D.step
, D.area
, D.bar
, D.hist
, D.candle, D.whisker
, setDataset
-- * Annotations
, Location, Head, Fill
, AN.arrow
, AN.oval
, AN.rect
, AN.glyph
, AN.text
, AN.cairo
, withAnnotations
-- ** Plot type
, setSeriesType
, setAllSeriesTypes
-- ** Formatting
, D.PlotFormats(..)
, withSeriesFormat
, withAllSeriesFormats
-- * Range
, Scale(..)
, setRange
, setRangeFromData
-- * Axes
, AX.Axis
, AxisType(..),AxisSide(..),AxisPosn(..)
, clearAxes
, clearAxis
, addAxis
, withAxis
-- * BarSetting
, barSetting
-- * SampleData
, sampleData
-- * Legend
, L.Legend
, LegendBorder
, L.LegendLocation(..), L.LegendOrientation(..)
, clearLegend
, setLegend
, withLegendFormat
-- ** Formatting
, Tick(..), TickValues(..), GridLines
, TickFormat(..)
, AX.setTicks
, AX.setGridlines
, AX.setTickLabelFormat
, AX.setTickLabels
, AX.withTickLabelsFormat
, AX.withAxisLabel
, AX.withAxisLine
, AX.withGridLine
) where
-----------------------------------------------------------------------------
--import Data.Eq.Unicode
--import Data.Bool.Unicode
--import Data.Ord.Unicode
import Numeric.LinearAlgebra.Data hiding(Range)
import qualified Data.Array.IArray as A
import Control.Monad.State
import Control.Monad.Reader
--import Control.Monad.Supply
import Prelude hiding(min,max)
import qualified Prelude as Prelude
import Graphics.Rendering.Plot.Types
import Graphics.Rendering.Plot.Defaults
import qualified Graphics.Rendering.Plot.Figure.Text as T
import qualified Graphics.Rendering.Plot.Figure.Plot.Data as D
import qualified Graphics.Rendering.Plot.Figure.Plot.Axis as AX
import qualified Graphics.Rendering.Plot.Figure.Plot.Legend as L
import qualified Graphics.Rendering.Plot.Figure.Plot.Annotation as AN
-----------------------------------------------------------------------------
-- | whether to draw a boundary around the plot area
setBorder :: Border -> Plot ()
setBorder b = modify $ \s -> s { _border = b }
-- | set the plot background colour
setPlotBackgroundColour :: Color -> Plot ()
setPlotBackgroundColour c = modify $ \s -> s { _back_colr = c }
-- | set the padding of the subplot
setPlotPadding :: Double -> Double -> Double -> Double -> Plot ()
setPlotPadding l r b t = modify $ \s -> s { _plot_pads = Padding l r b t }
-- | set the heading of the subplot
withHeading :: Text () -> Plot ()
withHeading m = do
o <- asks _textoptions
modify $ \s -> s { _heading = execText m o (_heading s) }
-----------------------------------------------------------------------------
-- | set the axis range
setRange :: AxisType -> AxisSide -> Scale -> Double -> Double -> Plot ()
setRange XAxis sd sc min max = modify $ \s -> s { _ranges = setXRanges' (_ranges s) }
where setXRanges' r
| sc == Log && min <= 0 = error "non-positive logarithmic range"
| otherwise = setXRanges sd r
setXRanges Lower (Ranges (Left _) yr) = Ranges (Left (Range sc min max)) yr
setXRanges Lower (Ranges (Right (_,xr)) yr) = Ranges (Right ((Range sc min max,xr))) yr
setXRanges Upper (Ranges (Left xr) yr) = Ranges (Right (xr,Range sc min max)) yr
setXRanges Upper (Ranges (Right (_,xr)) yr) = Ranges (Right (Range sc min max,xr)) yr
setRange YAxis sd sc min max = modify $ \s -> s { _ranges = setYRanges' (_ranges s) }
where setYRanges' r
| sc == Log && min <= 0 = error "non-positive logarithmic range"
| otherwise = setYRanges sd r
setYRanges Lower (Ranges xr (Left _)) = Ranges xr (Left (Range sc min max))
setYRanges Lower (Ranges xr (Right (_,yr))) = Ranges xr (Right ((Range sc min max,yr)))
setYRanges Upper (Ranges xr (Left yr)) = Ranges xr (Right (yr,Range sc min max))
setYRanges Upper (Ranges xr (Right (_,yr))) = Ranges xr (Right ((Range sc min max,yr)))
-- | set the axis ranges to values based on dataset
setRangeFromData :: AxisType -> AxisSide -> Scale -> Plot ()
setRangeFromData ax sd sc = do
ds <- gets _data
let ((xmin,xmax),(ymin,ymax)) = calculateRanges ds
case ax of
XAxis -> setRange ax sd sc (if sc == Log then if xmin == 0 then 1 else xmin else xmin) xmax
YAxis -> setRange ax sd sc (if sc == Log then if ymin == 0 then 1 else ymin else ymin) ymax
-----------------------------------------------------------------------------
withAnnotations :: Annote () -> Plot ()
withAnnotations = annoteInPlot
-----------------------------------------------------------------------------
-- | clear the axes of a subplot
clearAxes :: Plot ()
clearAxes = modify $ \s -> s { _axes = [] }
-- | clear an axis of a subplot
clearAxis :: AxisType -> AxisPosn -> Plot ()
clearAxis at axp = do
ax <- gets _axes
modify $ \s -> s { _axes =
filter (\(Axis at' axp' _ _ _ _ _ _) -> not (at == at' && axp == axp')) ax }
-- | add an axis to the subplot
addAxis :: AxisType -> AxisPosn -> AX.Axis () -> Plot ()
addAxis at axp m = do
ax' <- gets _axes
o <- ask
let ax = execAxis m o (defaultAxis at axp)
modify $ \s -> s { _axes = ax : ax' }
-- | operate on the given axis
withAxis :: AxisType -> AxisPosn -> AX.Axis () -> Plot ()
withAxis at axp m = do
axes' <- gets _axes
o <- ask
modify $ \s -> s { _axes =
map (\a@(Axis at' ap' _ _ _ _ _ _) -> if at == at' && axp == ap'
then execAxis m o a
else a) axes' }
-----------------------------------------------------------------------------
barSetting :: BarSetting -> Plot ()
barSetting bc = modify $ \s -> s { _barconfig = bc }
-----------------------------------------------------------------------------
sampleData :: SampleData -> Plot ()
sampleData sd = modify $ \s -> s { _sampledata = sd }
-----------------------------------------------------------------------------
-- | clear the legend
clearLegend :: Plot ()
clearLegend = withLegend $ L.clearLegend
-- | set the legend location and orientation
setLegend :: L.LegendBorder -> L.LegendLocation -> L.LegendOrientation -> Plot ()
setLegend b l o = withLegend $ L.setLegend b l o
-- | format the legend text
withLegendFormat :: T.Text () -> Plot ()
withLegendFormat f = withLegend $ L.withLegendFormat f
-- | operate on the legend
withLegend :: L.Legend () -> Plot ()
withLegend = legendInPlot
-----------------------------------------------------------------------------
-- | operate on the data
withData :: D.Data () -> Plot ()
withData = dataInPlot
{- | set the data series of the subplot
The data series are either 'FormattedSeries' or plain data series.
A plain data series must carry a 'SeriesType'.
A dataset may or may not have an abscissa series, and if so, it is paired
with either a list of ordinate series or a single ordinate series.
The abscissa series (if present) is of type 'Vector Double'.
An ordinate series be a function (@Double -> Double@) or a series of points,
a 'Vector Double' with optional error series, y axis preference, and labels.
To specify decoration options for an ordinate series, use the appropriate function, such
as 'linespoints', with the ordinate series and decoration formatting ('LineFormat',
'PointFormat', and 'BarFormat') as arguments.
> setDataset (ts,[linespoints (xs,(le,ue),Upper,"data") (([Dash,Dash],3,blue),(Diamond,green))])
has abscissa @ts@ paired with a list of ordinate series, the single element of which is a
'FormattedSeries', @linespoints@ where the ordinate is @xs@ with error series @le@ and @ue@,
to be graphed against the upper y-range with label \"data\". The line element is formatted
to be dashed, of width 3, and blue and the point element is to be a green diamond.
-}
setDataset :: D.Dataset a => a -> Plot ()
setDataset d = withData $ D.setDataSeries d
-- | set the plot type of a given data series
setSeriesType :: Int -> SeriesType -> Plot ()
setSeriesType i t = withData $ D.setSeriesType t i
-- | change the plot type of all data series
setAllSeriesTypes :: SeriesType -> Plot ()
setAllSeriesTypes t = withData $ D.setAllSeriesTypes t
-- | format the plot elements of a given series
withSeriesFormat :: D.PlotFormats m => Int -> m () -> Plot ()
withSeriesFormat i f = withData $ D.withSeriesFormat i f
{- |
format the plot elements of all series
the operation to modify the formats is passed the series index.
This allows, for example, colours to be selected from a list
that gets indexed by the argument
> setColour = withAllSeriesFormats (\i -> do
> setLineColour $ [black,blue,red,green,yellow] !! i
> setLineWidth 1.0)
-}
withAllSeriesFormats :: D.PlotFormats m => (Int -> m ()) -> Plot ()
withAllSeriesFormats f = withData $ D.withAllSeriesFormats f
-----------------------------------------------------------------------------
findMinMax :: Abscissae -> Ordinates -> (Double,Double)
findMinMax (AbsFunction _) (OrdFunction _ f _) =
let v = f (linspace 100 (-1,1))
in (minElement v,maxElement v)
findMinMax (AbsPoints _ x) (OrdFunction _ f _) =
let v = f x
in (minElement v,maxElement v)
-- what if errors go beyond plot?
findMinMax _ (OrdPoints _ (Plain o) _) = (minElement o,maxElement o)
findMinMax _ (OrdPoints _ (Error o _) _) = (minElement o,maxElement o)
findMinMax _ (OrdPoints _ (MinMax (o,p) _) _) =
(Prelude.min (minElement o) (minElement p)
,Prelude.max (maxElement o) (maxElement p))
abscMinMax :: Abscissae -> (Double,Double)
abscMinMax (AbsFunction _) = defaultXAxisSideLowerRange
abscMinMax (AbsPoints _ x) = (minElement x,maxElement x)
ordDim :: Ordinates -> Int
ordDim (OrdFunction _ _ _) = 1
ordDim (OrdPoints _ o _) = size $ getOrdData o
calculateRanges :: DataSeries -> ((Double,Double),(Double,Double))
calculateRanges (DS_Y ys) =
let xmax = maximum $ map (\(DecSeries o _) ->
fromIntegral $ ordDim o) $ A.elems ys
ym = unzip $ map (\(DecSeries o _) ->
findMinMax (AbsFunction id) o) $ A.elems ys
ymm = (minimum $ fst ym,maximum $ snd ym)
in ((0,xmax),ymm)
calculateRanges (DS_1toN x ys) =
let ym = unzip $ map (\(DecSeries o _) -> findMinMax x o) $ A.elems ys
ymm = (minimum $ fst ym,maximum $ snd ym)
xmm = abscMinMax x
in (xmm,ymm)
calculateRanges (DS_1to1 ys) =
let (xm',ym') = unzip $ A.elems ys
ym = unzip $ map (\(x,(DecSeries o _)) -> findMinMax x o) (zip xm' ym')
ymm = (minimum $ fst ym,maximum $ snd ym)
xm = unzip $ map abscMinMax xm'
xmm = (minimum $ fst xm,maximum $ snd xm)
in (xmm,ymm)
calculateRanges (DS_Surf m) =
((0,fromIntegral $ cols m),(fromIntegral $ rows m,0))
-----------------------------------------------------------------------------
|
\cleardoublepage
\def\pageLang{c}
\section{Procedure Declarations in C} % (fold)
\label{sec:procedure_declaration_in_c}
% Concept overview
\input{topics/program-creation/c/c-morse-calling}
% Parts of the syntax
% section procedure_declaration_in_c (end)
|
%%\documentclass[handout]{beamer}
%\documentclass[aspectratio=169,13pt]{beamer}
%\input{./preamble}
\subtitle{Numerical Integration and Differentiation}
\date{}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\section{Introduction to Numerical Integration}
\begin{frame}{Integrability and Sensitivity}
\begin{itemize}
\item Seek to compute $\mathcal{I}(f)=\int_{a}^b f(x) dx$:
\mdcond{
\begin{itemize}
\item $f$ is integrable if continuous and bounded.
\mitem Finite number of discontinuities is also often permissible.
\end{itemize}
}
\item The condition number of integration is bounded by the distance $b-a$:
\lgcond{
Suppose the input function is perturbed $\hat{f}=f+ \delta f$, then
\begin{align*}
\delta I &= |\mathcal{I}(\hat{f}) - \mathcal{I}(f)| \\
&\leq |\mathcal{I}(\delta f)| \\
&\leq (b-a) ||\delta f||_\infty, \quad \text{where} \quad |f||_\infty = \max_{x\in[a,b]} | f(x)|.
%\left|\int_{a}^b \hat{f}(x) dx - \int^b_a f(x) dx\right| \\
% &\leq |\int_{a}^b \underbrace{|\hat{f}(x) dx - \int^b_a f(x)|}_{\leq||\hat{f}-f||_\infty = \delta f}dx \\
% &\leq (b-a) \delta f
\end{align*}
Note that this result {\it does not depend on the magnitude of $f$ or its derivatives}, which means integration is generally very well-conditioned, which makes sense since integration corresponds to averaging.
}
\end{itemize}
\end{frame}
\section{Quadrature Rules}
\begin{frame}{Quadrature Rules}
\begin{itemize}
\item Approximate the integral $\mathcal{I}(f)$ by a weighted sum of function values:
\lgcond{
\[\mathcal{I}(f) \approx Q_n(f)= \sum_{i=1}^n w_i f(x_i)\]
\begin{itemize}
\item $\{x_i\}_{i=1}^n$ are quadrature \coloremph{nodes} or \coloremph{abscissas},
%\item
$\{w_i\}_{i=1}^n$ are quadrature \coloremph{weights}.
\mitem Quadrature rule %defined by $(\{x_i\}_{i=1}^n,\{w_i\}_{i=1}^n)$
is \coloremph{closed} if $x_1=a,x_n=b$ and \coloremph{open} otherwise.
\mitem Rule is \coloremph{progressive} if nodes of $Q_n$ are a subset of those of $Q_{n+1}$.
\end{itemize}
}
\sitem For a fixed set of $n$ nodes, polynomial interpolation followed by integration give \coloremph{$(n-1)$-degree quadrature rule}:
\lgcond{
\begin{itemize}
\item Accuracy depends on interpolant, is exact for all $(n-1)$-degree polynomials.
\mitem Can obtain weights by expressing the unique $(n-1)$-degree polynomial interpolant in the Lagrange basis
$p(x)=\sum_{i=1}^{n} \phi_i(x)f(x_i)$, so that
%, the coefficients are then % of $f$ is given by the Vandermonde system,
%\[\B y = \B y, \quad \text{where} \quad y_i= f(x_i) \quad \text{and} \quad d_{ii}=\phi_i(x_i).\]
%The quadrature rule is defined by
\[Q_n(f)=\mathcal{I}(p)= \sum_{i=1}^{n} \underbrace{\mathcal{I}(\phi_i)}_{w_i}f(x_i).\]
\end{itemize}
}
\end{itemize}
\end{frame}
\begin{frame}{Determining Weights in a General Basis}
\begin{itemize}
\item A quadrature rule provides $\B x$ and $\B w$ so as to approximate
\lgcond{
\[\mathcal{I}(f)\approx Q_n(f)=\langle \B w, \B y \rangle, \quad \text{where} \quad y_i=f(x_i)\]
$Q_n$ is the integral of the polynomial interpolant $p$ of $(x_1,y_1),\ldots,(x_n,y_n)$.
%\begin{itemize}
%\item
%\end{itemize}
}
\item \coloremph{Method of undetermined coefficients} obtains $\B y$ from \coloremph{moment equations} based on Vandermonde system:
\lgcond{
\[
\mathcal{I}(p) = \mathcal{I}(\langle \{\phi_i(x)\}_{i=1}^n, \underbrace{\B V(\B x, \{\phi_i\}_{i=1}^n)^{-1} \B y}_\text{interpolant coefficients}\rangle) =
\langle \underbrace{\B V(\B x, \{\phi_i\}_{i=1}^n)^{-T}\{\mathcal{I}(\phi_i(x))\}_{i=1}^n}_{\B w}, \B y\rangle\]
%\begin{bmatrix} \int_a^b \phi_1(x) dx & \cdots &\int_a^b \phi_n(x)dx \end{bmatrix} \B V(\B x, \{\phi_i\}_{i=1}^n)^{-1} \B y.\]
%\begin{bmatrix} \int_a^b \phi_1(x) dx & \cdots &\int_a^b \phi_n(x)dx \end{bmatrix} \B V(\B x, \{\phi_i\}_{i=1}^n)^{-1} \B y.\]
\begin{itemize}
\item Thus to obtain $\B w$, we need to solve the linear system,
\[\B V(\B x, \{\phi_i\}_{i=1}^n)^T\B w = \begin{bmatrix} \int_a^b \phi_1(x) dx & \cdots &\int_a^b \phi_n(x)dx \end{bmatrix}^T,\]
\item Note that the weights $\B w$ are \coloremph{independent} of the function values $\B y$.
\end{itemize}
}
\end{itemize}
\end{frame}
\begin{frame}{Newton-Cotes Quadrature}
\urcornerlinkdemo{08-quadrature-and-differentiation}{Newton-Cotes weight finder}
\begin{itemize}
\item \coloremph{Newton-Cotes} quadrature rules are defined by equispaced nodes on $[a,b]$:
\mdcond{
open: $x_i=a+i(b-a)/(n+1)$, closed: $x_i=a+(i-1)(b-a)/(n-1)$.
}
\item The \coloremph{midpoint rule} is the $n=1$ open Newton-Cotes rule:
\mdcond{
\[M(f) = (b-a)f\left(\frac{a+b}{2}\right)\]
}
\item The \coloremph{trapezoid rule} is the $n=2$ closed Newton-Cotes rule:
\mdcond{
\[T(f) = \frac{(b-a)}{2}(f(a) + f(b))\]
}
\item \coloremph{Simpson's rule} is the $n=3$ closed Newton-Cotes rule:
\mdcond{
\[S(f)=\frac{b-a}{6}\left(f(a) + 4f\left(\frac{a+b}{2}\right) + f(b)\right)\]
}
\end{itemize}
\end{frame}
\subsection{Error and Conditioning of Quadrature Rules}
\begin{frame}[fragile]{Error in Newton-Cotes Quadrature}
\urcornerlinkdemo{08-quadrature-and-differentiation}{Accuracy of Newton-Cotes}
\begin{itemize}
\item Consider the Taylor expansion of $f$ about the midpoint of the integration interval $m=(a+b)/2$:
\mdcond{
\[f(x) = f(m) + f'(m)(x-m) + \frac{f''(m)}{2}(x-m)^2 +\ldots\]
}
Integrating the Taylor approximation of $f$, we note that the odd terms drop:
\lgcond{
\[\mathcal{I}(f) = \underbrace{f(m)(b-a)}_{M(f)} + \underbrace{\frac{f''(m)}{24}(b-a)^3}_{E(f)} + O((b-a)^5)\]
Consequently, the midpoint rule is third-order accurate (first degree).
}
\end{itemize}
\end{frame}
\begin{frame}{Error Estimation}
\begin{itemize}
%\item Quadrature weights can be alternatively determined for a rule by solving the moment equations:
%\lgcond{
%\begin{align*}
%\B V(\B x, \{\phi_i\}_{i=1}^n) \B w = \B y(\{\phi_i\}_{i=1}^n), \quad \text{where} \quad y_i = \mathcal{I}(\phi_i)
%\end{align*}
%}
\item The trapezoid rule is also first degree, despite using higher-degree polynomial interpolant approximation, since
\lgcond{
\begin{align*}
f(m) = \frac{1}{2}\bigg(&f(a) - f'(m)(a-m) - \frac{f''(m)}{2}(a-m)^2 +\ldots \\
+&f(b) - f'(m)(b-m) - \frac{f''(m)}{2}(b-m)^2 +\ldots \bigg) \\
\mathcal{I}(f)= T(f) -& \underbrace{\frac{f''(m)}{12}(b-a)^3}_{2E(f)} - O((b-a)^5)
\end{align*}
}
\item The above derivation allows us to obtain an error approximation via a difference of midpoint and trapezoidal rules:
\lgcond{
\[T(f)-M(f)\approx 3E(f).\]
This approximation rapidly becomes accurate as $b-a$ decreases.
}
\end{itemize}
\end{frame}
\begin{frame}{Error in Polynomial Quadrature Rules}
\begin{itemize}
\item We can bound the error for a an arbitrary polynomial quadrature rule by
\lgcond{
\begin{align*}
|\mathcal{I}(f)-Q_n(f)| &= |\mathcal{I}(f-p)| \\
&\leq (b-a) || f-p||_\infty \\
&\leq \frac{b-a}{4n}h^n || f^{(n)}||_\infty
\end{align*}
where $h=\max_i(x_{i+1}-x_i)$.
}
\lgcond{
}
\end{itemize}
\end{frame}
\begin{frame}{Conditioning of Newton-Cotes Quadrature}
\begin{itemize}
\item We can ascertain stability of quadrature rules, by considering the amplification of a perturbation $\hat{f} = f+ \delta f$:
\lgcond {
\begin{align*}
|Q_n(\hat{f})-Q_n(f)| &= |Q_n(\delta f)| \\
&= \sum_{i=1}^n w_i \delta f(x_i) \\
&\leq ||\B w||_1 ||\delta f||_\infty.
\end{align*}
Note that we always have $\sum_i w_i=b-a$, since the quadrature rule must be correct for a constant function.
So if $\B w$ is positive $||\B w||_1=b-a$, the quadrature rule is stable, i.e. it matches the conditioning of the problem.
}
\item Newton-Cotes quadrature rules have at least one negative weight for any $n\geq 11$:
\lgcond{
More generally, $||\B w||_1\to \infty$ as $n \to \infty$ for fixed $b-a$. This means that the Newton-Cotes rules can be ill-conditioned.
}
\end{itemize}
\end{frame}
\subsection{Chebyshev Quadrature}
\begin{frame}{Clenshaw-Curtis Quadrature}
\begin{itemize}
\item To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:
\lgcond{
\begin{itemize}
\mitem Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.
\mitem Formally, it can be shown that $w_i>0$ for the Chebyshev-node ({\color{red} Clenshaw-Curtis}) quadrature.
\mitem The weights for Clenshaw-Curtis quadrature rules can be obtained by solutions to Vandermonde systems on $[-1,1]$ with Chebyshev-spaced nodes, then translating to a desired integration interval.
\end{itemize}
}
\end{itemize}
\end{frame}
%\begin{frame}{Gaussian Quadrature}
%
%\begin{itemize}
%\item So far, we have only considered quadrature rules based on a fixed set of nodes, but we can also choose a set of nodes to improve accuracy:
%
%\lgcond{
%Choice of nodes gives additional $n$ parameters for a total of $2n$ degrees of freedom, permitting representation of polynomials of degree $2n-1$.
%}
%\item The \coloremph{unique} $n$-point \coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \textit{both} $\B x$ and $\B w$:
%\lgcond{
%Given any complete basis, we seek to solve the nonlinear equations,
%\[\B V(\B x, \{\phi_i\}_{i=1}^{2n+1}) \B w = \B y(\{\phi_i\}_{i=1}^{2n+1}), \quad \text{where} \quad y_i = \mathcal{I}(\phi_i)\]
%For fixed $\B x$, we have an overdetermined system of linear equations for $\B w$.
%}
%%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:
%%
%%\lgcond {
%%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.
%%
%%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.
%%}
%\end{itemize}
%
%\end{frame}
%
%\begin{frame}{Using Gaussian Quadrature Rules}
%
%\begin{itemize}
%\item Gaussian quadrature rules are hard to determine and usually, but can be enumerated for a fixed interval, e.g. $a=0,b=1$, so it suffices to transform the integral to $[0,1]$
%
%\lgcond{
%We have that
%\[\mathcal{I}(f) = \int_{a}^b f(x)dx = \int_0^1 g(t) dt \quad \text{where} \quad g(x) = f(t), t=\frac{x+b-a}{b-a}\]
%
%Choice of nodes gives additional $n$ parameters for a total of $2n$ degrees od freedom, permitting representation of polynomials of degree $2n-1$.
%}
%\item The \coloremph{unique} $n$-point \coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \textit{both} $\B x$ and $\B w$:
%\lgcond{
%Given any complete basis, we seek to solve the nonlinear equations,
%\[\B V(\B x, \{\phi_i\}_{i=1}^{2n+1}) \B w = \B y(\{\phi_i\}_{i=1}^{2n+1}), \quad \text{where} \quad y_i = \mathcal{I}(\phi_i)\]
%For fixed $\B x$, we have an overdetermined system of linear equations for $\B w$.
%}
%%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:
%%
%%\lgcond {
%%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.
%%
%%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.
%%}
%\end{itemize}
%
%\end{frame}
%
%\begin{frame}{Improvements to Gaussian Quadrature}
%
%\begin{itemize}
%\item Gaussian quadrature rules are are accurate and stable but not progressive (nodes cannot be reused to obtain higher-degree approximation):
%
%\mdcond{}
%
%\item \coloremph{Kronod} quadrature rules construct $(2n+1)$-point quadrature $K_{2n+1}$ that is progressive w.r.t. Gaussian quadrature rule $G_n$
%
%\mdcond{}
%
%\item Gaussian quadrature rules are in general open, but Gauss-Radau and Gauss-Lobatto rules permit including end-points:
%
%\mdcond{
%Gauss-Radau uses one of two end-points as a node, while Gauss-Lobatto quadrature uses both.
%}
%
%\end{itemize}
%
%
%\end{frame}
%
%
%\begin{frame}{Composite and Adaptive Quadrature}
%
%\begin{itemize}
%\item Composite quadrature rules are obtained by integrating a piecewise interpolant of $f$:
%
%\lgcond{}
%
%\item Adaptive quadrature corresponds to using composite quadrature with adaptive refinement:
%
%\lgcond{
%Introduce new nodes where error estimate is large.
%Error estimate can be obtained by e.g. comparing trapezoid and midpoint rules, but can be completely wrong if function is insufficiently smooth.
%}
%
%\end{itemize}
%
%
%\end{frame}
%\end{document}
\subsection{Gaussian Quadrature}
\begin{frame}{Gaussian Quadrature}
\urcornerlinkdemo{08-quadrature-and-differentiation}{Gaussian quadrature weight finder}
\begin{itemize}
\item So far, we have only considered quadrature rules based on a fixed set of nodes, but we may also be able to choose nodes to maximize accuracy:
\lgcond{
\begin{itemize}
\item Choice of nodes gives additional $n$ parameters for total $2n$ degrees of freedom.
\mitem Permits exact integration of degree-$(2n-1)$ polynomials and corresponding general accuracy.
\end{itemize}
}
\item The \coloremph{unique} $n$-point \coloremph{Gaussian quadrature rule} is defined by the solution of the nonlinear form of the moment equations in terms of \textit{both} $\B x$ and $\B w$:
\lgcond{
Given any complete basis, we seek to solve the nonlinear equations for $\B x,\B w$,
\[\B V(\B x, \{\phi_i\}_{i=1}^{2n+1})^T \B w = \B y, \quad \text{where} \quad y_i = \mathcal{I}(\phi_i).\]
\begin{itemize}
\item These nonlinear equations generally have a unique solution $(\B x^*, \B w^*)$.
\mitem For fixed $\B x$, we have an overdetermined system of linear equations for $\B w$.
\end{itemize}
}
%To obtain a more stable quadrature rule, we need to ensure the integrated interpolant is well-behaved as $n$ increases:
%
%\lgcond {
%Chebyshev quadrature nodes ensure that interpolant polynomial has bounded coefficients so long as $f$ is bounded, since the Vandermonde system defining its coefficients is well-conditioned.
%
%Formally, it can be shown that $w_i>0$ for Chebyshev-node (Clenshaw-Curtis) quadrature.
%}
\end{itemize}
\end{frame}
\begin{frame}{Using Gaussian Quadrature Rules}
\begin{itemize}
\item Gaussian quadrature rules are hard to compute, but can be enumerated for a fixed interval, e.g. $a=0,b=1$, so it suffices to transform the integral to $[0,1]$
\lgcond{
\begin{itemize}
\item We can transform a given integral using variable substitution $t=\frac{x-a}{b-a}$,
\[\mathcal{I}(f) = \int_{a}^b f(x)dx = (b-a)\int_0^1 g(t) dt \quad \text{where} \quad g(t) = f(t(b-a)+a)).\]
\item For quadrature rules defined on $[-1,1]$, we can transform via the substitution $t=2\frac{x-a}{b-a}-1$,
\[\mathcal{I}(f) = \int_{a}^b f(x)dx = \frac{b-a}{2}\int_{-1}^1 g(t) dt \quad \text{where} \quad g(t) = f((t+1)(b-a)/2+a).\]
\end{itemize}
}
\item Gaussian quadrature rules are accurate and stable but not progressive (nodes cannot be reused to obtain higher-degree approximation):
\mdcond{
\begin{itemize}
\item maximal degree is obtained
\sitem weights are always positive (perfect conditioning)
\end{itemize}
}
\end{itemize}
\end{frame}
\begin{frame}{Progressive Gaussian-like Quadrature Rules}
\begin{itemize}
\item \coloremph{Kronod} quadrature rules construct $(2n+1)$-point $(3n+1)$-degree quadrature $K_{2n+1}$ that is progressive with respect to Gaussian quadrature rule $G_n$:
\lgcond{
\begin{itemize}
\item Gaussian quadrature rule $G_{2n+1}$ would use same number of points and have degree $4n+1$.
\mitem Kronod rule points are optimal chosen to reuse all points of $G_n$, so $n+1$ rather than $2n+1$ new evaluations are necessary.
\end{itemize}
}
\item \coloremph{Patterson} quadrature rules use $2n+2$ more points to extend $(2n+1)$-point Kronod rule to degree $6n+4$, while reusing all $2n+1$ points.
\item Gaussian quadrature rules are in general open, but \coloremph{Gauss-Radau} and \coloremph{Gauss-Lobatto} rules permit including end-points:
\lgcond{
Gauss-Radau uses one of two end-points as a node, while Gauss-Lobatto quadrature uses both.
}
\end{itemize}
\end{frame}
\begin{frame}{Composite and Adaptive Quadrature}
\begin{itemize}
\item \coloremph{Composite quadrature rules} are obtained by integrating a piecewise interpolant of $f$:
\lgcond{
For example, we can derive simple composite Newton-Cotes rules by partitioning the domain into sub-intervals $[x_i,x_{i+1}]$:
\begin{itemize}
\sitem composite midpoint rule
\[\mathcal{I}(f) = \sum_{i=1}^{n-1} \int_{x_i}^{x_{i+1}} f(x)dx \approx \sum_{i=1}^{n-1} (x_{i+1}-x_i)f((x_{i+1}+x_i)/2)\]
\item composite trapezoid rule
\[\mathcal{I}(f) = \sum_{i=1}^{n-1} \int_{x_i}^{x_{i+1}} f(x)dx \approx \sum_{i=1}^{n-1} \frac{(x_{i+1}-x_i)}2 (f(x_{i+1})+f(x_i))\]
\end{itemize}
}
\item Composite quadrature can be done with adaptive refinement:
\lgcond{
Introduce new nodes where error estimate is large.
Error estimate can be obtained by e.g. comparing trapezoid and midpoint rules, but can be completely wrong if function is insufficiently smooth.
}
\end{itemize}
\end{frame}
\begin{frame}{More Complicated Integration Problems}
\begin{itemize}
\item To handle improper integrals can either transform integral to get rid of infinite limit or use appropriate open quadrature rules.
\mdcond{}
\item Double integrals can simply be computed by successive 1-D integration.
\mdcond{
Composite multidimensional rules are also possible by partitioning the domain into chunks.
}
\item High-dimensional integration is often effectively done by \coloremph{Monte Carlo}:
\lgcond{
\[\int_\Omega f(\B x) d\B x = E[Y], \quad Y = \frac{|\Omega|}{N} \sum_{i=1}^N Y_i, \quad Y_i = f(\B x_i), \quad \B x_i \ \ \text{chosen randomly from $\Omega$}.\]
\begin{itemize}
\item Convergence rate is independent of function (effective polynomial degree approximation) or dimension of integration domain.
\mitem Instead, it depends on number of samples ($N$), with error scaling as $O(1/\sqrt{N})$.
\end{itemize}
}
\end{itemize}
\end{frame}
\begin{frame}{Integral Equations}
\begin{itemize}
\item Rather than evaluating an integral, in solving an \coloremph{integral equation} we seek to compute the integrand. A typical linear integral equation has the form
\[\int_a^b K(s,t)u(t) dt = f(s), \quad \text{where} \quad K \quad \text{and} \quad f \quad \text{are known}.\]
\lgcond{
\begin{itemize}
\item Useful for recovering signal $u$ given response function with kernel $K$ and measurements of $f$.
\mitem Also arise from solve equations arising from Green's function methods for PDEs.
\end{itemize}
}
\item Using a quadrature rule with weights $w_1,\ldots, w_n$ and nodes $t_1,\ldots, t_n$ obtain
\lgcond{
\[\sum_{j=1}^n w_jK(s,t_j)u(t_j) = f(s).\]
Discrete sample of $f$ on $s_1,\ldots, s_n$ yields a linear system of equations,
\[\sum_{j=1}^n w_jK(s_i,t_j)u(t_j) = f(s_i).\]
%The resulting matrix $\B A$ can be ill-conditioned for many kernels $K$.
}
\end{itemize}
\end{frame}
%\begin{frame}{Challenges in Solving Integral Equations}
%
%\begin{itemize}
%\item Integral equations based on response functions tend to be ill-conditioned, which is resolved using
%
%\begin{itemize}
%\item truncated singular value decomposition of $\B A$, where $a_{ij}=w_jK(s_i,t_j)$
%
%\mdcond{}
%
%\item replacing the linear system with a regularized linear least squares problem,
%
%\mdcond{}
%
%\item expressing the solution using a basis
%
%\mdcond{Let $u(t)\approx \sum_{j=1}^n c_j \phi_j(t)$ and derive equations for the coefficients.}
%
%\end{itemize}
%\end{itemize}
%
%
%\end{frame}
\begin{frame}{Numerical Differentiation}
\urcornerlinkdemo{08-quadrature-and-differentiation}{Taking Derivatives with Vandermonde Matrices}
\begin{itemize}
\item Automatic (symbolic) differentiation is a surprisingly viable option:
\lgcond{
\begin{itemize}
\item Any computer program is differentiable, since it is an assembly of basic arithmetic operations.
\item Existing software packages can automatically differentiate whole programs.
\end{itemize}
}
\item Numerical differentiation can be done by interpolation or finite differencing:
\lgcond{
\begin{itemize}
\item Given polynomial interpolant, its derivative is easy to obtain by differentiating the basis in which it is expressed,
\[f'(x)\approx p'(x) = \begin{bmatrix} \phi'_1(x) & \cdots &\phi'_n(x) \end{bmatrix}^T\B V(\B t, \{\phi_i\}_{i=1}^n)^{-1} \B y, \ \text{where} \ y_i=f(t_i).\]
\item Obtaining the values of the derivative at the interpolation nodes, can be done via
\[\underbrace{\B V(\B t, \{\phi_i'\}_{i=1}^n)\B V(\B t, \{\phi_i\}_{i=1}^n)^{-1}}_\text{Differentiation matrix} \B y, \ \text{where} \ y_i=f(t_i).\]
\item Finite-differencing formulas effectively use linear interpolant.
\end{itemize}
}
\end{itemize}
\end{frame}
\begin{frame}{Accuracy of Finite Differences}
\dblurcornerlinkdemo{08-quadrature-and-differentiation}{Finite Differences vs Noise}{08-quadrature-and-differentiation}{Floating point vs Finite Differences}
\begin{itemize}
\item \coloremph{Forward and backward differencing} provide first-order accuracy:
\lgcond{
These can be derived, respectively from forward and backward Taylor expansions of $f$ about $x$,
\begin{align*}
f(x+h) &= f(x) + f'(x)h + f''(x) h^2 /2 + \ldots \\
f(x-h) &= f(x) - f'(x)h + f''(x) h^2 /2 - \ldots
\end{align*}
For forward differencing, we obtain an approximation from the first equation,
\[f'(x) = \frac{f(x+h)- f(x)}h + f''(x) h /2 + \ldots.\]
}
\item \coloremph{Centered differencing} provides second-order accuracy.
\lgcond{
Subtracting the backward Taylor expansion from the forward, we obtain centered differencing,
\[f'(x) = \frac{f(x+h)- f(x-h)}{2h} + O(h^2).\]
Second order accuracy is due to cancellation of odd terms like $f''(x)h/2$.
}
\end{itemize}
\end{frame}
\begin{frame}{Extrapolation Techniques}
\urcornerlinkdemoinclass{08-quadrature-and-differentiation}{Richardson with Finite Differences}{inclass-richardson}{Richardson Extrapolation}
\begin{itemize}
\item Given a series of approximate solutions produced by an iterative procedure, a more accurate approximation may be obtained by \coloremph{extrapolating} this series.
\lgcond{
For example, as we lower the step size $h$ in a finite-difference formula, we can try to extrapolate the series to $h=0$, if we know that
\[F(h)=a_0 + a_1h^p + O(h^r) \ \text{as} \ h\to 0 \ \text{and seek to determine $F(0)=a_0$},\]
for example in centered differences $p=2$ and $r=4$.
}
\item In particular, given two guesses, \coloremph{Richardson extrapolation} eliminates the leading order error term.
\lgcond{
Seek to eliminate $a_1h^p$ term in $F(h)$, $F(h/2)$ to improve approximation of $a_0$,
\begin{align*}
F(h) &= a_0 + a_1h^p + O(h^r), \\
F(h/2) &= a_0 + a_1h^p/2^p + O(h^r), \\
a_0 &= F(h) - \frac{F(h)-F(h/2)}{1-1/2^{p}} + O(h^r).
\end{align*}
}
\end{itemize}
\end{frame}
\begin{frame}{High-Order Extrapolation}
\begin{itemize}
\item Given a series of $k$ approximations, \coloremph{Romberg integration} applies $(k-1)$-levels of Richardson extrapolation.
\lgcond{
Can apply Richardson extrapolation to each of $k-1$ pairs of consecutive nodes, then proceed recursively on the $k-1$ resulting approximations.
}
\item Extrapolation can be used within an iterative procedure at each step:
\lgcond{
For example, Steffensen's method for finding roots of nonlinear equations,
\[x_{n+1} = x_n + \frac{f(x_n)}{1-f(x_n+f(x_n))/f(x_n)},\]
derived from Aitken's delta-squared extrapolation process:
\begin{itemize}
\item achieves quadratic convergence,
\sitem requires no derivative,
\sitem competes with the Secant method (quadratic versus superlinear convergence, but an extra function evaluation necessary).
\end{itemize}
}
\end{itemize}
\end{frame}
%\end{document}
|
[GOAL]
B : Type u_1
F : Type u_2
inst✝¹ : TopologicalSpace B
inst✝ : TopologicalSpace F
⊢ topologicalSpace B F = induced (↑(TotalSpace.toProd B F)) instTopologicalSpaceProd
[PROOFSTEP]
simp only [instTopologicalSpaceProd, induced_inf, induced_compose]
[GOAL]
B : Type u_1
F : Type u_2
inst✝¹ : TopologicalSpace B
inst✝ : TopologicalSpace F
⊢ topologicalSpace B F =
induced (Prod.fst ∘ ↑(TotalSpace.toProd B F)) inst✝¹ ⊓ induced (Prod.snd ∘ ↑(TotalSpace.toProd B F)) inst✝
[PROOFSTEP]
rfl
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
let f₁ : TotalSpace (F₁ × F₂) (E₁ ×ᵇ E₂) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ := fun p ↦
((⟨p.1, p.2.1⟩ : TotalSpace F₁ E₁), (⟨p.1, p.2.2⟩ : TotalSpace F₂ E₂))
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
let f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p ↦ ⟨e₁ p.1, e₂ p.2⟩
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
let f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p ↦ ⟨p.1.1, p.1.2, p.2.2⟩
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
have hf₁ : Continuous f₁ := (Prod.inducing_diag F₁ E₁ F₂ E₂).continuous
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
have hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source) :=
e₁.toLocalHomeomorph.continuousOn.prod_map e₂.toLocalHomeomorph.continuousOn
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
have hf₃ : Continuous f₃ := (continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd)
[GOAL]
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ ContinuousOn (toFun' e₁ e₂) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
refine' ((hf₃.comp_continuousOn hf₂).comp hf₁.continuousOn _).congr _
[GOAL]
case refine'_1
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)) (e₁.source ×ˢ e₂.source)
[PROOFSTEP]
rw [e₁.source_eq, e₂.source_eq]
[GOAL]
case refine'_1
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ MapsTo f₁ (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
((TotalSpace.proj ⁻¹' e₁.baseSet) ×ˢ (TotalSpace.proj ⁻¹' e₂.baseSet))
[PROOFSTEP]
exact mapsTo_preimage _ _
[GOAL]
case refine'_2
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
⊢ EqOn (toFun' e₁ e₂) ((f₃ ∘ f₂) ∘ f₁) (TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet))
[PROOFSTEP]
rintro ⟨b, v₁, v₂⟩ ⟨hb₁, _⟩
[GOAL]
case refine'_2.mk.mk.intro
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₁.baseSet
right✝ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₂.baseSet
⊢ toFun' e₁ e₂ { proj := b, snd := (v₁, v₂) } = ((f₃ ∘ f₂) ∘ f₁) { proj := b, snd := (v₁, v₂) }
[PROOFSTEP]
simp only [Prod.toFun', Prod.mk.inj_iff, Function.comp_apply, and_true_iff]
[GOAL]
case refine'_2.mk.mk.intro
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₁.baseSet
right✝ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₂.baseSet
⊢ b = (↑e₁ { proj := b, snd := v₁ }).fst
[PROOFSTEP]
rw [e₁.coe_fst]
[GOAL]
case refine'_2.mk.mk.intro
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₁.baseSet
right✝ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₂.baseSet
⊢ { proj := b, snd := v₁ } ∈ e₁.source
[PROOFSTEP]
rw [e₁.source_eq, mem_preimage]
[GOAL]
case refine'_2.mk.mk.intro
B : Type u_1
inst✝⁴ : TopologicalSpace B
F₁ : Type u_2
inst✝³ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝² : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝¹ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝ : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
f₁ : (TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x) → TotalSpace F₁ E₁ × TotalSpace F₂ E₂ :=
fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })
f₂ : TotalSpace F₁ E₁ × TotalSpace F₂ E₂ → (B × F₁) × B × F₂ := fun p => (↑e₁ p.fst, ↑e₂ p.snd)
f₃ : (B × F₁) × B × F₂ → B × F₁ × F₂ := fun p => (p.fst.fst, p.fst.snd, p.snd.snd)
hf₁ : Continuous f₁
hf₂ : ContinuousOn f₂ (e₁.source ×ˢ e₂.source)
hf₃ : Continuous f₃
b : B
v₁ : E₁ b
v₂ : E₂ b
hb₁ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₁.baseSet
right✝ : { proj := b, snd := (v₁, v₂) }.proj ∈ e₂.baseSet
⊢ { proj := b, snd := v₁ }.proj ∈ e₁.baseSet
[PROOFSTEP]
exact hb₁
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x
h : x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)
⊢ invFun' e₁ e₂ (toFun' e₁ e₂ x) = x
[PROOFSTEP]
obtain ⟨x, v₁, v₂⟩ := x
[GOAL]
case mk.mk
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : B
v₁ : E₁ x
v₂ : E₂ x
h : { proj := x, snd := (v₁, v₂) } ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet)
⊢ invFun' e₁ e₂ (toFun' e₁ e₂ { proj := x, snd := (v₁, v₂) }) = { proj := x, snd := (v₁, v₂) }
[PROOFSTEP]
obtain ⟨h₁ : x ∈ e₁.baseSet, h₂ : x ∈ e₂.baseSet⟩ := h
[GOAL]
case mk.mk.intro
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : B
v₁ : E₁ x
v₂ : E₂ x
h₁ : x ∈ e₁.baseSet
h₂ : x ∈ e₂.baseSet
⊢ invFun' e₁ e₂ (toFun' e₁ e₂ { proj := x, snd := (v₁, v₂) }) = { proj := x, snd := (v₁, v₂) }
[PROOFSTEP]
simp only [Prod.toFun', Prod.invFun', symm_apply_apply_mk, h₁, h₂]
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : B × F₁ × F₂
h : x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ
⊢ toFun' e₁ e₂ (invFun' e₁ e₂ x) = x
[PROOFSTEP]
obtain ⟨x, w₁, w₂⟩ := x
[GOAL]
case mk.mk
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : B
w₁ : F₁
w₂ : F₂
h : (x, w₁, w₂) ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ
⊢ toFun' e₁ e₂ (invFun' e₁ e₂ (x, w₁, w₂)) = (x, w₁, w₂)
[PROOFSTEP]
obtain ⟨⟨h₁ : x ∈ e₁.baseSet, h₂ : x ∈ e₂.baseSet⟩, -⟩ := h
[GOAL]
case mk.mk.intro.intro
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : B
w₁ : F₁
w₂ : F₂
h₁ : x ∈ e₁.baseSet
h₂ : x ∈ e₂.baseSet
⊢ toFun' e₁ e₂ (invFun' e₁ e₂ (x, w₁, w₂)) = (x, w₁, w₂)
[PROOFSTEP]
simp only [Prod.toFun', Prod.invFun', apply_mk_symm, h₁, h₂]
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
⊢ ContinuousOn (invFun' e₁ e₂) ((e₁.baseSet ∩ e₂.baseSet) ×ˢ univ)
[PROOFSTEP]
rw [(Prod.inducing_diag F₁ E₁ F₂ E₂).continuousOn_iff]
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
⊢ ContinuousOn ((fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })) ∘ invFun' e₁ e₂)
((e₁.baseSet ∩ e₂.baseSet) ×ˢ univ)
[PROOFSTEP]
have H₁ : Continuous fun p : B × F₁ × F₂ ↦ ((p.1, p.2.1), (p.1, p.2.2)) :=
(continuous_id.prod_map continuous_fst).prod_mk (continuous_id.prod_map continuous_snd)
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
H₁ : Continuous fun p => ((p.fst, p.snd.fst), p.fst, p.snd.snd)
⊢ ContinuousOn ((fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })) ∘ invFun' e₁ e₂)
((e₁.baseSet ∩ e₂.baseSet) ×ˢ univ)
[PROOFSTEP]
refine' (e₁.continuousOn_symm.prod_map e₂.continuousOn_symm).comp H₁.continuousOn _
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
H₁ : Continuous fun p => ((p.fst, p.snd.fst), p.fst, p.snd.snd)
⊢ MapsTo (fun p => ((p.fst, p.snd.fst), p.fst, p.snd.snd)) ((e₁.baseSet ∩ e₂.baseSet) ×ˢ univ)
((e₁.baseSet ×ˢ univ) ×ˢ e₂.baseSet ×ˢ univ)
[PROOFSTEP]
exact fun x h ↦ ⟨⟨h.1.1, mem_univ _⟩, ⟨h.1.2, mem_univ _⟩⟩
[GOAL]
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
⊢ IsOpen
{ toFun := Prod.toFun' e₁ e₂, invFun := Prod.invFun' e₁ e₂, source := TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet),
target := (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) →
(Prod.toFun' e₁ e₂ x).fst ∈ e₁.baseSet ∩ e₂.baseSet ∧ (Prod.toFun' e₁ e₂ x).snd ∈ univ),
map_target' :=
(_ : ∀ (x : B × F₁ × F₂), x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → x.fst ∈ e₁.baseSet ∩ e₂.baseSet),
left_inv' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) → Prod.invFun' e₁ e₂ (Prod.toFun' e₁ e₂ x) = x),
right_inv' :=
(_ :
∀ (x : B × F₁ × F₂),
x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → Prod.toFun' e₁ e₂ (Prod.invFun' e₁ e₂ x) = x) }.source
[PROOFSTEP]
convert (e₁.open_source.prod e₂.open_source).preimage (FiberBundle.Prod.inducing_diag F₁ E₁ F₂ E₂).continuous
[GOAL]
case h.e'_3
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
⊢ { toFun := Prod.toFun' e₁ e₂, invFun := Prod.invFun' e₁ e₂, source := TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet),
target := (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) →
(Prod.toFun' e₁ e₂ x).fst ∈ e₁.baseSet ∩ e₂.baseSet ∧ (Prod.toFun' e₁ e₂ x).snd ∈ univ),
map_target' :=
(_ : ∀ (x : B × F₁ × F₂), x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → x.fst ∈ e₁.baseSet ∩ e₂.baseSet),
left_inv' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) → Prod.invFun' e₁ e₂ (Prod.toFun' e₁ e₂ x) = x),
right_inv' :=
(_ :
∀ (x : B × F₁ × F₂),
x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → Prod.toFun' e₁ e₂ (Prod.invFun' e₁ e₂ x) = x) }.source =
(fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })) ⁻¹' e₁.source ×ˢ e₂.source
[PROOFSTEP]
ext x
[GOAL]
case h.e'_3.h
B : Type u_1
inst✝⁶ : TopologicalSpace B
F₁ : Type u_2
inst✝⁵ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁴ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝³ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝² : TopologicalSpace (TotalSpace F₂ E₂)
e₁ : Trivialization F₁ TotalSpace.proj
e₂ : Trivialization F₂ TotalSpace.proj
inst✝¹ : (x : B) → Zero (E₁ x)
inst✝ : (x : B) → Zero (E₂ x)
x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x
⊢ x ∈
{ toFun := Prod.toFun' e₁ e₂, invFun := Prod.invFun' e₁ e₂,
source := TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet), target := (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) →
(Prod.toFun' e₁ e₂ x).fst ∈ e₁.baseSet ∩ e₂.baseSet ∧ (Prod.toFun' e₁ e₂ x).snd ∈ univ),
map_target' :=
(_ : ∀ (x : B × F₁ × F₂), x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → x.fst ∈ e₁.baseSet ∩ e₂.baseSet),
left_inv' :=
(_ :
∀ (x : TotalSpace (F₁ × F₂) fun x => E₁ x × E₂ x),
x ∈ TotalSpace.proj ⁻¹' (e₁.baseSet ∩ e₂.baseSet) → Prod.invFun' e₁ e₂ (Prod.toFun' e₁ e₂ x) = x),
right_inv' :=
(_ :
∀ (x : B × F₁ × F₂),
x ∈ (e₁.baseSet ∩ e₂.baseSet) ×ˢ univ → Prod.toFun' e₁ e₂ (Prod.invFun' e₁ e₂ x) = x) }.source ↔
x ∈
(fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })) ⁻¹' e₁.source ×ˢ e₂.source
[PROOFSTEP]
simp only [Trivialization.source_eq, mfld_simps]
[GOAL]
B : Type u_1
inst✝¹⁰ : TopologicalSpace B
F₁ : Type u_2
inst✝⁹ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁸ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝⁷ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝⁶ : TopologicalSpace (TotalSpace F₂ E₂)
inst✝⁵ : (x : B) → Zero (E₁ x)
inst✝⁴ : (x : B) → Zero (E₂ x)
inst✝³ : (x : B) → TopologicalSpace (E₁ x)
inst✝² : (x : B) → TopologicalSpace (E₂ x)
inst✝¹ : FiberBundle F₁ E₁
inst✝ : FiberBundle F₂ E₂
b : B
⊢ Inducing (TotalSpace.mk b)
[PROOFSTEP]
rw [(Prod.inducing_diag F₁ E₁ F₂ E₂).inducing_iff]
[GOAL]
B : Type u_1
inst✝¹⁰ : TopologicalSpace B
F₁ : Type u_2
inst✝⁹ : TopologicalSpace F₁
E₁ : B → Type u_3
inst✝⁸ : TopologicalSpace (TotalSpace F₁ E₁)
F₂ : Type u_4
inst✝⁷ : TopologicalSpace F₂
E₂ : B → Type u_5
inst✝⁶ : TopologicalSpace (TotalSpace F₂ E₂)
inst✝⁵ : (x : B) → Zero (E₁ x)
inst✝⁴ : (x : B) → Zero (E₂ x)
inst✝³ : (x : B) → TopologicalSpace (E₁ x)
inst✝² : (x : B) → TopologicalSpace (E₂ x)
inst✝¹ : FiberBundle F₁ E₁
inst✝ : FiberBundle F₂ E₂
b : B
⊢ Inducing ((fun p => ({ proj := p.proj, snd := p.snd.fst }, { proj := p.proj, snd := p.snd.snd })) ∘ TotalSpace.mk b)
[PROOFSTEP]
exact (totalSpaceMk_inducing F₁ E₁ b).prod_map (totalSpaceMk_inducing F₂ E₂ b)
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f : B' → B
inst✝ : (x : B) → TopologicalSpace (E x)
⊢ (x : B') → TopologicalSpace ((f *ᵖ E) x)
[PROOFSTEP]
intro x
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f : B' → B
inst✝ : (x : B) → TopologicalSpace (E x)
x : B'
⊢ TopologicalSpace ((f *ᵖ E) x)
[PROOFSTEP]
rw [Bundle.Pullback]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f : B' → B
inst✝ : (x : B) → TopologicalSpace (E x)
x : B'
⊢ TopologicalSpace (E (f x))
[PROOFSTEP]
infer_instance
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ Continuous TotalSpace.proj
[PROOFSTEP]
rw [continuous_iff_le_induced, Pullback.TotalSpace.topologicalSpace, pullbackTopology_def]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ induced TotalSpace.proj inst✝¹ ⊓ induced (Pullback.lift f) inst✝ ≤ induced TotalSpace.proj inst✝¹
[PROOFSTEP]
exact inf_le_left
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ Continuous (Pullback.lift f)
[PROOFSTEP]
rw [continuous_iff_le_induced, Pullback.TotalSpace.topologicalSpace, pullbackTopology_def]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ induced TotalSpace.proj inst✝¹ ⊓ induced (Pullback.lift f) inst✝ ≤ induced (Pullback.lift f) inst✝
[PROOFSTEP]
exact inf_le_right
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ Inducing (pullbackTotalSpaceEmbedding f)
[PROOFSTEP]
constructor
[GOAL]
case induced
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ Pullback.TotalSpace.topologicalSpace F E f = induced (pullbackTotalSpaceEmbedding f) instTopologicalSpaceProd
[PROOFSTEP]
simp_rw [instTopologicalSpaceProd, induced_inf, induced_compose, Pullback.TotalSpace.topologicalSpace,
pullbackTopology_def]
[GOAL]
case induced
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝¹ : TopologicalSpace B'
inst✝ : TopologicalSpace (TotalSpace F E)
f : B' → B
⊢ induced TotalSpace.proj inst✝¹ ⊓ induced (Pullback.lift f) inst✝ =
induced (Prod.fst ∘ pullbackTotalSpaceEmbedding f) inst✝¹ ⊓ induced (Prod.snd ∘ pullbackTotalSpaceEmbedding f) inst✝
[PROOFSTEP]
rfl
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (x : B) → TopologicalSpace (E x)
inst✝ : FiberBundle F E
f : B' → B
x : B'
⊢ Continuous (TotalSpace.mk x)
[PROOFSTEP]
simp only [continuous_iff_le_induced, Pullback.TotalSpace.topologicalSpace, induced_compose, induced_inf, Function.comp,
induced_const, top_inf_eq, pullbackTopology_def]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (x : B) → TopologicalSpace (E x)
inst✝ : FiberBundle F E
f : B' → B
x : B'
⊢ instForAllTopologicalSpacePullback E f x ≤ induced (fun x_1 => Pullback.lift f { proj := x, snd := x_1 }) inst✝⁴
[PROOFSTEP]
exact le_of_eq (FiberBundle.totalSpaceMk_inducing F E (f x)).induced
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : TotalSpace F (↑f *ᵖ E)
h : x ∈ Pullback.lift ↑f ⁻¹' e.source
⊢ (fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ
[PROOFSTEP]
simp_rw [e.source_eq, mem_preimage, Pullback.lift_proj] at h
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : TotalSpace F (↑f *ᵖ E)
h : ↑f x.proj ∈ e.baseSet
⊢ (fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ
[PROOFSTEP]
simp_rw [prod_mk_mem_set_prod_eq, mem_univ, and_true_iff, mem_preimage, h]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
y : B' × F
h : y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ
⊢ (fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈ Pullback.lift ↑f ⁻¹' e.source
[PROOFSTEP]
rw [mem_prod, mem_preimage] at h
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
y : B' × F
h : ↑f y.fst ∈ e.baseSet ∧ y.snd ∈ univ
⊢ (fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈ Pullback.lift ↑f ⁻¹' e.source
[PROOFSTEP]
simp_rw [e.source_eq, mem_preimage, Pullback.lift_proj, h.1]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : TotalSpace F (↑f *ᵖ E)
h : x ∈ Pullback.lift ↑f ⁻¹' e.source
⊢ (fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x
[PROOFSTEP]
simp_rw [mem_preimage, e.mem_source, Pullback.lift_proj] at h
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : TotalSpace F (↑f *ᵖ E)
h : ↑f x.proj ∈ e.baseSet
⊢ (fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x
[PROOFSTEP]
simp_rw [Pullback.lift, e.symm_apply_apply_mk h]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : B' × F
h : x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ
⊢ (fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x
[PROOFSTEP]
simp_rw [mem_prod, mem_preimage, mem_univ, and_true_iff] at h
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
x : B' × F
h : ↑f x.fst ∈ e.baseSet
⊢ (fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x
[PROOFSTEP]
simp_rw [Pullback.lift_mk, e.apply_mk_symm h]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ IsOpen
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.source
[PROOFSTEP]
simp_rw [e.source_eq, ← preimage_comp]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ IsOpen (TotalSpace.proj ∘ Pullback.lift ↑f ⁻¹' e.baseSet)
[PROOFSTEP]
exact e.open_baseSet.preimage ((map_continuous f).comp <| Pullback.continuous_proj F E f)
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ ContinuousOn
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.invFun
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.target
[PROOFSTEP]
dsimp only
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ ContinuousOn (fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) ((↑f ⁻¹' e.baseSet) ×ˢ univ)
[PROOFSTEP]
simp_rw [(inducing_pullbackTotalSpaceEmbedding F E f).continuousOn_iff, Function.comp, pullbackTotalSpaceEmbedding]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ ContinuousOn (fun x => (x.fst, { proj := ↑f x.fst, snd := Trivialization.symm e (↑f x.fst) x.snd }))
((↑f ⁻¹' e.baseSet) ×ˢ univ)
[PROOFSTEP]
refine'
continuousOn_fst.prod (e.continuousOn_symm.comp ((map_continuous f).prod_map continuous_id).continuousOn Subset.rfl)
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ {
toLocalEquiv :=
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) },
open_source :=
(_ :
IsOpen
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.source),
open_target := (_ : IsOpen ((↑f ⁻¹' e.baseSet) ×ˢ univ)),
continuous_toFun :=
(_ :
ContinuousOn (fun x => (x.proj, (↑e (Pullback.lift (↑f) x)).snd))
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.source),
continuous_invFun :=
(_ :
ContinuousOn
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.invFun
{ toFun := fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd),
invFun := fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd },
source := Pullback.lift ↑f ⁻¹' e.source, target := (↑f ⁻¹' e.baseSet) ×ˢ univ,
map_source' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ),
map_target' :=
(_ :
∀ (y : B' × F),
y ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) y ∈
Pullback.lift ↑f ⁻¹' e.source),
left_inv' :=
(_ :
∀ (x : TotalSpace F (↑f *ᵖ E)),
x ∈ Pullback.lift ↑f ⁻¹' e.source →
(fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd })
((fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd)) x) =
x),
right_inv' :=
(_ :
∀ (x : B' × F),
x ∈ (↑f ⁻¹' e.baseSet) ×ˢ univ →
(fun z => (z.proj, (↑e (Pullback.lift (↑f) z)).snd))
((fun y => { proj := y.fst, snd := Trivialization.symm e (↑f y.fst) y.snd }) x) =
x) }.target) }.toLocalEquiv.source =
TotalSpace.proj ⁻¹' (↑f ⁻¹' e.baseSet)
[PROOFSTEP]
dsimp only
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ Pullback.lift ↑f ⁻¹' e.source = TotalSpace.proj ⁻¹' (↑f ⁻¹' e.baseSet)
[PROOFSTEP]
rw [e.source_eq]
[GOAL]
B : Type u
F : Type v
E : B → Type w₁
B' : Type w₂
f✝ : B' → B
inst✝⁵ : TopologicalSpace B'
inst✝⁴ : TopologicalSpace (TotalSpace F E)
inst✝³ : TopologicalSpace F
inst✝² : TopologicalSpace B
inst✝¹ : (_b : B) → Zero (E _b)
K : Type U
inst✝ : ContinuousMapClass K B' B
e : Trivialization F TotalSpace.proj
f : K
⊢ Pullback.lift ↑f ⁻¹' (TotalSpace.proj ⁻¹' e.baseSet) = TotalSpace.proj ⁻¹' (↑f ⁻¹' e.baseSet)
[PROOFSTEP]
rfl
|
\chapter{Chapter 1 - The Fourth House}
\begin{itemize}
\item Difficulty: Normal/Casual
\item Male \Byleth
\end{itemize}
\begin{battle}{The Fourth House}
\begin{multicols}{2}
\battleinfo{commander}{9}{\Byleth, \Ashe, \Linhardt, \Dimitri, \Claude}
\prep{
\item Options:
\begin{itemize}
\item Combat Animations: Off \arrow{right}{1}
\item Assist Animations: Off
\item Battle Speed: Fast
\item Action Skip: On
\item Automatic Cursor: Off
\end{itemize}
\abilities{
\Bylethf
\removeAbility{Battalion Vantage}
\addAbility{HP+5}
\Dimitrif \arrow{right}{2}
\removeAbility{Authority Level 3, Battalion Wrath}
\addAbility{HP+5, Dexterity+4}
\Claudef \arrow{right}{1}
\addAbility{Authority Level 3, Battalion Desparation}
\removeAbility{HP+5, Dexterity+4}
}
\armory{
\Dimitrif
\buy{2 Silver Lances}
\Claudef
\buy{1 Silver Bow}
}
}
\begin{enumerate}
\turn{
\Ashef \arrow{left}{2}
\movegambit{3L, 2D}{Retribution}{\Hilda}{1R}
\Dimitrif \arrow{\right}{3}
\movegambit{1U, 7R}{Assault Troop}{\enemy{Rogue}}{1R}
\turnend
}
\turn{
\Linhardtf \arrow{right}{1}
\movephysic{4R}{\Dimitri}{}
\Dimitrif \arrow{left}{1}
\moveattack{1R}{\Balthus}{1R with Silver Lance}
\movewait{5D, 2R}
\autoCharge
}
\turn{
\Linhardtf \arrow{right}{2}
\movephysic{4R}{\Dimitri}{}
\autoCharge
}
\columnbreak
\turn{
\Claudef
\movewait{5R - 1D, 1L from the Gate, which is 2D, 4L from \Hapi. Actual travelling will be different based on where Charge placed everyone.}
\autoCharge
\Dimitrif
\begin{itemize}
\item When the Door Key is picked up, send the Iron Lance into the Convoy.
\end{itemize}
}
\turn{
\Dimitrif \arrow{right}{2}
\moveattack{2R, 4U}{\enemy{Rogue}}{1U, with the more worn-down Silver Lance}
\Linhardtf \arrow{left}{2}
\movephysic{Upper-Right Corner}{\Dimitri}{\arrow{right}{1}}
\turnend
}
\turn{
\Dimitrif \arrow{right}{2}
\moveattack{1R, 5U}{\enemy{Archer}}{1L}
\Linhardtf \arrow{right}{1}
\begin{itemize}\physic{\Dimitri}{\arrow{left}{1}}\end{itemize}
\turnend
}
\turn{
\Dimitrif \arrow{left}{1}
\movewait{4L, 1U}
\begin{itemize}
\item If there are any remaining enemies, kill them and then Canto to the avoid tile to the right of the left hole.
\end{itemize}
\Linhardtf \arrow{right}{1}
\begin{itemize}\physic{\Dimitri}{\arrow{right}{1}}\end{itemize}
\turnend
}
\turn{
\Dimitrif \arrow{left}{1}
\moveattack{1U}{\Constance}{1U with Javelin and Tempest Lance}
\movewait{1U}
\Linhardtf \arrow{right}{1}
\begin{itemize}\physic{\Dimitri}{\arrow{right}{1}}\end{itemize}
\turnend
}
\turn{
\Dimitrif \arrow{left}{1}
\moveattack{3U}{\Yuri}{1R with Silver Lance and Knightkneeler. If it isn't a one-shot, use Tempest Lance instead.}
\ifc{\Dimitri\ fails to kill \Yuri}{\item \divinepulse \item Burn a RN with \Linhardt's Physic}
\ifc{\Dimitri\ still fails to kill \Yuri}{\item \divinepulse \item Try Gambiting \Yuri\ instead from 1U above \Yuri}
}
\end{enumerate}
\end{multicols}
\end{battle} |
data Nat : Set where
O : Nat
S : Nat → Nat
syntax S x = suc x
test : Nat → Nat
test _ = suc O
syntax lim (λ n → m) = limit n at m
data lim (f : Nat → Nat) : Set where
syntax foo (λ _ → n) = const-foo n
postulate
foo : (Nat → Nat) → Nat
|
# 自定义生成包的工具。
# 基于LibraryTools。
# 增加了不存在包文件则直接创建文件的功能。
LibMaker:=module()
option package;
export MakeLib;
(*
将package保存到文件
如果文件不存在则创建文件
如果文件不含后缀名则补全后缀名
默认文件名为 lib.mla
*)
MakeLib:=proc(mName,fName:="lib.mla")
if not StringTools:-RegMatch(".*\\.mla",fName) then
fName:=cat(fName,".mla");
end if;
if not FileTools:-Exists(fName) then
LibraryTools:-Create(fName);
end if;
LibraryTools:-Save(mName,fNmae);
end proc:
end module: |
[STATEMENT]
lemma ifTrue_deterministic [simp]:
assumes
s_r: "s r = Some (\<sigma>, \<tau>, \<E> [Ite (VE (CV T)) e1 e2])"
shows "(revision_step r s s') = (s' = (s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1]))))" (is "?l = ?r")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. revision_step r s s' = (s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1])))
[PROOF STEP]
proof (rule iffI)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. revision_step r s s' \<Longrightarrow> s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1]))
2. s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1])) \<Longrightarrow> revision_step r s s'
[PROOF STEP]
assume ?l
[PROOF STATE]
proof (state)
this:
revision_step r s s'
goal (2 subgoals):
1. revision_step r s s' \<Longrightarrow> s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1]))
2. s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1])) \<Longrightarrow> revision_step r s s'
[PROOF STEP]
thus ?r
[PROOF STATE]
proof (prove)
using this:
revision_step r s s'
goal (1 subgoal):
1. s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1]))
[PROOF STEP]
by (cases rule: revision_stepE) (use s_r in auto)
[PROOF STATE]
proof (state)
this:
s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1]))
goal (1 subgoal):
1. s' = s(r \<mapsto> (\<sigma>, \<tau>, \<E> [e1])) \<Longrightarrow> revision_step r s s'
[PROOF STEP]
qed (simp add: s_r revision_step.ifTrue) |
From LogRel.AutoSubst Require Import core unscoped Ast Extra.
From LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening
DeclarativeTyping GenericTyping LogicalRelation Validity.
From LogRel.LogicalRelation Require Import Escape Reflexivity Neutral Weakening Irrelevance.
From LogRel.Substitution Require Import Irrelevance Properties.
From LogRel.Substitution.Introductions Require Import Universe Pi Application.
Set Universe Polymorphism.
Section SimpleArrValidity.
Context `{GenericTypingProperties}.
Lemma simpleArrValid {l Γ F G} (VΓ : [||-v Γ])
(VF : [Γ ||-v< l > F | VΓ ])
(VG : [Γ ||-v< l > G | VΓ]) :
[Γ ||-v<l> arr F G | VΓ].
Proof.
unshelve eapply PiValid; tea.
replace G⟨↑⟩ with G⟨@wk1 Γ F⟩ by now bsimpl.
now eapply wk1ValidTy.
Qed.
Lemma simpleArrCongValid {l Γ F F' G G'} (VΓ : [||-v Γ])
(VF : [Γ ||-v< l > F | VΓ ])
(VF' : [Γ ||-v< l > F' | VΓ ])
(VeqF : [Γ ||-v< l > F ≅ F' | VΓ | VF])
(VG : [Γ ||-v< l > G | VΓ ])
(VG' : [Γ ||-v< l > G' | VΓ ])
(VeqG : [Γ ||-v< l > G ≅ G' | VΓ | VG]) :
[Γ ||-v<l> arr F G ≅ arr F' G' | VΓ | simpleArrValid _ VF VG].
Proof.
eapply irrelevanceEq.
unshelve eapply PiCong; tea.
+ replace G⟨↑⟩ with G⟨@wk1 Γ F⟩ by now bsimpl.
now eapply wk1ValidTy.
+ replace G'⟨↑⟩ with G'⟨@wk1 Γ F'⟩ by now bsimpl.
now eapply wk1ValidTy.
+ replace G'⟨↑⟩ with G'⟨@wk1 Γ F⟩ by now bsimpl.
eapply irrelevanceEq'.
2: now eapply wk1ValidTyEq.
now bsimpl.
Unshelve. 2: tea.
Qed.
Lemma simple_appValid {Γ t u F G l}
(VΓ : [||-v Γ])
{VF : [Γ ||-v<l> F | VΓ]}
(VG : [Γ ||-v<l> G | VΓ])
(VΠ : [Γ ||-v<l> arr F G | VΓ])
(Vt : [Γ ||-v<l> t : arr F G | _ | VΠ])
(Vu : [Γ ||-v<l> u : F | _ | VF]) :
[Γ ||-v<l> tApp t u : G| _ | VG].
Proof.
eapply irrelevanceTm'.
2: eapply appValid; tea.
now bsimpl.
Unshelve. all: tea.
Qed.
End SimpleArrValidity.
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory signedoverflow
imports "../CTranslation"
begin
install_C_file "signedoverflow.c"
context signedoverflow
begin
thm f_body_def
(* painful lemma about sint and word arithmetic results...
lemma j0: "\<Gamma> \<turnstile> \<lbrace> True \<rbrace> Call f_'proc \<lbrace> \<acute>ret__int = 0 \<rbrace>"
apply vcg
apply simp_all
apply auto
*)
thm g_body_def
lemma "\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL g(1) \<lbrace> \<acute>ret__int = - 1 \<rbrace>"
apply vcg
apply (simp add: word_sle_def)
done
lemma "\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL g(- 2147483648) \<lbrace> \<acute>ret__int = - 1 \<rbrace>"
apply vcg
apply (simp add: word_sle_def)
done
lemma "\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== CALL g(- 2147483647) \<lbrace> \<acute>ret__int = 2147483647 \<rbrace>"
apply vcg
apply (simp add: word_sle_def)
done
end (* context *)
end (* theory *)
|
[GOAL]
α β : DistLatCat
e : ↑α ≃o ↑β
⊢ { toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) } ≫
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) } =
𝟙 α
[PROOFSTEP]
ext
[GOAL]
case w
α β : DistLatCat
e : ↑α ≃o ↑β
x✝ : (forget DistLatCat).obj α
⊢ ↑({ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) } ≫
{
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) })
x✝ =
↑(𝟙 α) x✝
[PROOFSTEP]
exact e.symm_apply_apply _
[GOAL]
α β : DistLatCat
e : ↑α ≃o ↑β
⊢ {
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) } ≫
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) } =
𝟙 β
[PROOFSTEP]
ext
[GOAL]
case w
α β : DistLatCat
e : ↑α ≃o ↑β
x✝ : (forget DistLatCat).obj β
⊢ ↑({
toSupHom :=
{ toFun := ↑(OrderIso.symm e),
map_sup' :=
(_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊔ b) = ↑(OrderIso.symm e) a ⊔ ↑(OrderIso.symm e) b) },
map_inf' := (_ : ∀ (a b : ↑β), ↑(OrderIso.symm e) (a ⊓ b) = ↑(OrderIso.symm e) a ⊓ ↑(OrderIso.symm e) b) } ≫
{ toSupHom := { toFun := ↑e, map_sup' := (_ : ∀ (a b : ↑α), ↑e (a ⊔ b) = ↑e a ⊔ ↑e b) },
map_inf' := (_ : ∀ (a b : ↑α), ↑e (a ⊓ b) = ↑e a ⊓ ↑e b) })
x✝ =
↑(𝟙 β) x✝
[PROOFSTEP]
exact e.apply_symm_apply _
|
From stdpp Require Export strings.
From stdpp Require Import relations numbers.
From Coq Require Import Ascii.
From stdpp Require Import options.
Class Pretty A := pretty : A → string.
Global Hint Mode Pretty ! : typeclass_instances.
Definition pretty_N_char (x : N) : ascii :=
match x with
| 0 => "0" | 1 => "1" | 2 => "2" | 3 => "3" | 4 => "4"
| 5 => "5" | 6 => "6" | 7 => "7" | 8 => "8" | _ => "9"
end%char%N.
Lemma pretty_N_char_inj x y :
(x < 10)%N → (y < 10)%N → pretty_N_char x = pretty_N_char y → x = y.
Proof. compute; intros. by repeat (discriminate || case_match). Qed.
Fixpoint pretty_N_go_help (x : N) (acc : Acc (<)%N x) (s : string) : string :=
match decide (0 < x)%N with
| left H => pretty_N_go_help (x `div` 10)%N
(Acc_inv acc (N.div_lt x 10 H eq_refl))
(String (pretty_N_char (x `mod` 10)) s)
| right _ => s
end.
Definition pretty_N_go (x : N) : string → string :=
pretty_N_go_help x (wf_guard 32 N.lt_wf_0 x).
Instance pretty_N : Pretty N := λ x,
if decide (x = 0)%N then "0" else pretty_N_go x "".
Lemma pretty_N_go_0 s : pretty_N_go 0 s = s.
Proof. done. Qed.
Lemma pretty_N_go_help_irrel x acc1 acc2 s :
pretty_N_go_help x acc1 s = pretty_N_go_help x acc2 s.
Proof.
revert x acc1 acc2 s; fix FIX 2; intros x [acc1] [acc2] s; simpl.
destruct (decide (0 < x)%N); auto.
Qed.
Lemma pretty_N_go_step x s :
(0 < x)%N → pretty_N_go x s
= pretty_N_go (x `div` 10) (String (pretty_N_char (x `mod` 10)) s).
Proof.
unfold pretty_N_go; intros; destruct (wf_guard 32 N.lt_wf_0 x).
destruct (wf_guard _ _). (* this makes coqchk happy. *)
unfold pretty_N_go_help at 1; fold pretty_N_go_help.
by destruct (decide (0 < x)%N); auto using pretty_N_go_help_irrel.
Qed.
(** Helper lemma to prove [pretty_N_inj] and [pretty_Z_inj]. *)
Lemma pretty_N_go_ne_0 x s : s ≠ "0" → pretty_N_go x s ≠ "0".
Proof.
revert s. induction (N.lt_wf_0 x) as [x _ IH]; intros s ?.
assert (x = 0 ∨ 0 < x < 10 ∨ 10 ≤ x)%N as [->|[[??]|?]] by lia.
- by rewrite pretty_N_go_0.
- rewrite pretty_N_go_step by done. apply IH.
{ by apply N.div_lt. }
assert (x = 1 ∨ x = 2 ∨ x = 3 ∨ x = 4 ∨ x = 5 ∨ x = 6
∨ x = 7 ∨ x = 8 ∨ x = 9)%N by lia; naive_solver.
- rewrite 2!pretty_N_go_step by (try apply N.div_str_pos_iff; lia).
apply IH; [|done].
trans (x `div` 10)%N; apply N.div_lt; auto using N.div_str_pos with lia.
Qed.
(** Helper lemma to prove [pretty_Z_inj]. *)
Lemma pretty_N_go_ne_dash x s s' : s ≠ "-" +:+ s' → pretty_N_go x s ≠ "-" +:+ s'.
Proof.
revert s. induction (N.lt_wf_0 x) as [x _ IH]; intros s ?.
assert (x = 0 ∨ 0 < x)%N as [->|?] by lia.
- by rewrite pretty_N_go_0.
- rewrite pretty_N_go_step by done. apply IH.
{ by apply N.div_lt. }
unfold pretty_N_char. by repeat case_match.
Qed.
Instance pretty_N_inj : Inj (=@{N}) (=) pretty.
Proof.
cut (∀ x y s s', pretty_N_go x s = pretty_N_go y s' →
String.length s = String.length s' → x = y ∧ s = s').
{ intros help x y. unfold pretty, pretty_N. intros.
repeat case_decide; simplify_eq/=; [done|..].
- by destruct (pretty_N_go_ne_0 y "").
- by destruct (pretty_N_go_ne_0 x "").
- by apply (help x y "" ""). }
assert (∀ x s, ¬String.length (pretty_N_go x s) < String.length s) as help.
{ setoid_rewrite <-Nat.le_ngt.
intros x; induction (N.lt_wf_0 x) as [x _ IH]; intros s.
assert (x = 0 ∨ 0 < x)%N as [->|?] by lia; [by rewrite pretty_N_go_0|].
rewrite pretty_N_go_step by done.
etrans; [|by eapply IH, N.div_lt]; simpl; lia. }
intros x; induction (N.lt_wf_0 x) as [x _ IH]; intros y s s'.
assert ((x = 0 ∨ 0 < x) ∧ (y = 0 ∨ 0 < y))%N as [[->|?] [->|?]] by lia;
rewrite ?pretty_N_go_0, ?pretty_N_go_step, ?(pretty_N_go_step y) by done.
{ done. }
{ intros -> Hlen. edestruct help; rewrite Hlen; simpl; lia. }
{ intros <- Hlen. edestruct help; rewrite <-Hlen; simpl; lia. }
intros Hs Hlen.
apply IH in Hs as [? [= Hchar]];
[|auto using N.div_lt_upper_bound with lia|simpl; lia].
split; [|done].
apply pretty_N_char_inj in Hchar; [|by auto using N.mod_lt..].
rewrite (N.div_mod x 10), (N.div_mod y 10) by done. lia.
Qed.
Instance pretty_nat : Pretty nat := λ x, pretty (N.of_nat x).
Instance pretty_nat_inj : Inj (=@{nat}) (=) pretty.
Proof. apply _. Qed.
Instance pretty_Z : Pretty Z := λ x,
match x with
| Z0 => "0" | Zpos x => pretty (Npos x) | Zneg x => "-" +:+ pretty (Npos x)
end%string.
Instance pretty_Z_inj : Inj (=@{Z}) (=) pretty.
Proof.
unfold pretty, pretty_Z.
intros [|x|x] [|y|y] Hpretty; simplify_eq/=; try done.
- by destruct (pretty_N_go_ne_0 (N.pos y) "").
- by destruct (pretty_N_go_ne_0 (N.pos x) "").
- by edestruct (pretty_N_go_ne_dash (N.pos x) "").
- by edestruct (pretty_N_go_ne_dash (N.pos y) "").
Qed.
|
MODULE open79_I
INTERFACE
!...Generated by Pacific-Sierra Research 77to90 4.3E 14:44:54 12/27/06
SUBROUTINE open79 (I)
integer, INTENT(IN) :: I
!...This routine performs I/O.
END SUBROUTINE
END INTERFACE
END MODULE
|
lemma Schottky_lemma3: fixes z::complex assumes "z \<in> (\<Union>m \<in> Ints. \<Union>n \<in> {0<..}. {Complex m (ln(n + sqrt(real n ^ 2 - 1)) / pi)}) \<union> (\<Union>m \<in> Ints. \<Union>n \<in> {0<..}. {Complex m (-ln(n + sqrt(real n ^ 2 - 1)) / pi)})" shows "cos(pi * cos(pi * z)) = 1 \<or> cos(pi * cos(pi * z)) = -1" |
If you love the Toyota Tacoma, then our Christian Trucker Men`s Tank Top is a must have! This shirt is just incredibly cool, and is perfect for every occasion.
Our Toyota Tacoma Christian Trucker Men`s Tank Top is the softest, smoothest, best-looking tank top tee shirt available anywhere! It features original artwork of the Toyota Tacoma on the highest quality Men`s Tank Top. Our Toyota Tacoma Christian Trucker Men`s Tank Top is the ultimate HOT gift for the Toyota Tacoma fan on birthdays, holidays, anniversaries, retirement, or for no reason at all. A fashion necessity for everyone.
If you love the Toyota Tacoma, or know someone who does, then our Christian Trucker Men`s Tank Top is the thing to have! |
lemma cauchy_isometric:\<comment> \<open>TODO: rename lemma to \<open>Cauchy_isometric\<close>\<close> assumes e: "e > 0" and s: "subspace s" and f: "bounded_linear f" and normf: "\<forall>x\<in>s. norm (f x) \<ge> e * norm x" and xs: "\<forall>n. x n \<in> s" and cf: "Cauchy (f \<circ> x)" shows "Cauchy x" |
module menu_
using IUP
export
menu
include("../src/libiup_h.jl")
#------------------------example html/examples/C/menu.c ----------------------------------
function menu()
IupOpen() #Initializes IUP
item_open = IupItem ("Open", "");
IupSetAttribute(item_open, "KEY", "O");
item_save = IupItem ("Save", "");
IupSetAttribute(item_save, "KEY", "S");
item_undo = IupItem ("Undo", "");
IupSetAttribute(item_undo, "KEY", "U");
IupSetAttribute(item_undo, "ACTIVE", "NO");
item_exit = IupItem ("Exit", "");
IupSetAttribute(item_exit, "KEY", "x");
IupSetCallback(item_exit, "ACTION", cfunction(exit_cb, Cint, (Ptr{Ihandle},)))
file_menu = IupMenu(item_open,
item_save,
IupSeparator(),
item_undo,
item_exit)
sub1_menu = IupSubmenu("File", file_menu);
thismenu = IupMenu(sub1_menu)
IupSetHandle("mymenu", thismenu)
dlg = IupDialog(IupCanvas(""))
IupSetAttribute(dlg, "MENU", "mymenu")
IupSetAttribute(dlg, "TITLE", "IupMenu")
IupShow(dlg)
IupMainLoop() # Initializes IUP main loop
IupClose() # And close it when ready
end
function exit_cb(h::Ptr{Ihandle})
return convert(Cint, IUP_CLOSE)
end
end # module |
[STATEMENT]
lemma rat_floor_code [code]: "\<lfloor>p\<rfloor> = (let (a, b) = quotient_of p in a div b)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lfloor>p\<rfloor> = (let (a, b) = quotient_of p in a div b)
[PROOF STEP]
by (cases p) (simp add: quotient_of_Fract floor_Fract) |
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ring.pi
import Mathlib.algebra.big_operators.basic
import Mathlib.data.fintype.basic
import Mathlib.algebra.group.prod
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Big operators for Pi Types
This file contains theorems relevant to big operators in binary and arbitrary product
of monoids and groups
-/
namespace pi
theorem list_sum_apply {α : Type u_1} {β : α → Type u_2} [(a : α) → add_monoid (β a)] (a : α)
(l : List ((a : α) → β a)) :
list.sum l a = list.sum (list.map (fun (f : (a : α) → β a) => f a) l) :=
add_monoid_hom.map_list_sum (add_monoid_hom.apply β a) l
theorem multiset_sum_apply {α : Type u_1} {β : α → Type u_2} [(a : α) → add_comm_monoid (β a)]
(a : α) (s : multiset ((a : α) → β a)) :
multiset.sum s a = multiset.sum (multiset.map (fun (f : (a : α) → β a) => f a) s) :=
add_monoid_hom.map_multiset_sum (add_monoid_hom.apply β a) s
end pi
@[simp] theorem finset.sum_apply {α : Type u_1} {β : α → Type u_2} {γ : Type u_3}
[(a : α) → add_comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → (a : α) → β a) :
finset.sum s (fun (c : γ) => g c) a = finset.sum s fun (c : γ) => g c a :=
add_monoid_hom.map_sum (add_monoid_hom.apply β a) (fun (c : γ) => g c) s
@[simp] theorem fintype.prod_apply {α : Type u_1} {β : α → Type u_2} {γ : Type u_3} [fintype γ]
[(a : α) → comm_monoid (β a)] (a : α) (g : γ → (a : α) → β a) :
finset.prod finset.univ (fun (c : γ) => g c) a = finset.prod finset.univ fun (c : γ) => g c a :=
finset.prod_apply a finset.univ g
theorem prod_mk_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β]
(s : finset γ) (f : γ → α) (g : γ → β) :
(finset.prod s fun (x : γ) => f x, finset.prod s fun (x : γ) => g x) =
finset.prod s fun (x : γ) => (f x, g x) :=
sorry
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
theorem finset.univ_sum_single {I : Type u_1} [DecidableEq I] {Z : I → Type u_2}
[(i : I) → add_comm_monoid (Z i)] [fintype I] (f : (i : I) → Z i) :
(finset.sum finset.univ fun (i : I) => pi.single i (f i)) = f :=
sorry
theorem add_monoid_hom.functions_ext {I : Type u_1} [DecidableEq I] {Z : I → Type u_2}
[(i : I) → add_comm_monoid (Z i)] [fintype I] (G : Type u_3) [add_comm_monoid G]
(g : ((i : I) → Z i) →+ G) (h : ((i : I) → Z i) →+ G)
(w : ∀ (i : I) (x : Z i), coe_fn g (pi.single i x) = coe_fn h (pi.single i x)) : g = h :=
sorry
-- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances
-- on `Π i, f i`
theorem ring_hom.functions_ext {I : Type u_1} [DecidableEq I] {f : I → Type u_2}
[(i : I) → semiring (f i)] [fintype I] (G : Type u_3) [semiring G] (g : ((i : I) → f i) →+* G)
(h : ((i : I) → f i) →+* G)
(w : ∀ (i : I) (x : f i), coe_fn g (pi.single i x) = coe_fn h (pi.single i x)) : g = h :=
sorry
namespace prod
theorem fst_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β]
{s : finset γ} {f : γ → α × β} :
fst (finset.prod s fun (c : γ) => f c) = finset.prod s fun (c : γ) => fst (f c) :=
monoid_hom.map_prod (monoid_hom.fst α β) f s
theorem snd_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β]
{s : finset γ} {f : γ → α × β} :
snd (finset.prod s fun (c : γ) => f c) = finset.prod s fun (c : γ) => snd (f c) :=
monoid_hom.map_prod (monoid_hom.snd α β) f s
end Mathlib |
lemma int_imp_algebraic_int: assumes "x \<in> \<int>" shows "algebraic_int x" |
[STATEMENT]
lemma ltl_models_equiv_prop_entailment:
"w \<Turnstile>\<^sub>n \<phi> \<longleftrightarrow> {\<psi>. w \<Turnstile>\<^sub>n \<psi>} \<Turnstile>\<^sub>P \<phi>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. w \<Turnstile>\<^sub>n \<phi> = {\<psi>. w \<Turnstile>\<^sub>n \<psi>} \<Turnstile>\<^sub>P \<phi>
[PROOF STEP]
by (induction \<phi>) auto |
The difference between the infdist of $x$ and $y$ to a set $A$ is bounded by the distance between $x$ and $y$. |
data Nat : Set where
zero : Nat
suc : Nat → Nat
interleaved mutual
data Even : Nat → Set
data Odd : Nat → Set
-- base cases: 0 is Even, 1 is Odd
constructor
even-zero : Even zero
odd-one : Odd (suc zero)
-- step case: suc switches the even/odd-ness
constructor
even-suc : ∀ {n} → Odd n → Even (suc n)
odd-suc : ∀ {n} → Even n → Odd (suc n)
|
------------------------------------------------------------------------
-- Higher lenses, defined using the requirement that the remainder
-- function should be surjective
------------------------------------------------------------------------
{-# OPTIONS --cubical --safe #-}
import Equality.Path as P
module Lens.Non-dependent.Higher.Surjective-remainder
{e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where
open P.Derived-definitions-and-properties eq
open import Logical-equivalence using (_⇔_)
open import Prelude
open import Bijection equality-with-J using (_↔_)
open import Equality.Path.Isomorphisms eq hiding (univ)
open import Equivalence equality-with-J as Eq using (_≃_; Is-equivalence)
open import Function-universe equality-with-J as F
open import H-level equality-with-J
open import H-level.Closure equality-with-J
open import H-level.Truncation.Propositional eq
open import Lens.Non-dependent eq
import Lens.Non-dependent.Higher eq as Higher
private
variable
a b : Level
A B : Set a
-- A variant of the lenses defined in Lens.Non-dependent.Higher. In
-- this definition the function called inhabited is replaced by a
-- requirement that the remainder function should be surjective.
Lens : Set a → Set b → Set (lsuc (a ⊔ b))
Lens {a = a} {b = b} A B =
∃ λ (get : A → B) →
∃ λ (R : Set (a ⊔ b)) →
∃ λ (remainder : A → R) →
Is-equivalence (λ a → remainder a , get a) ×
Surjective remainder
instance
-- The lenses defined above have getters and setters.
has-getter-and-setter :
Has-getter-and-setter (Lens {a = a} {b = b})
has-getter-and-setter = record
{ get = λ (get , _) → get
; set = λ (_ , _ , rem , equiv , _) a b →
_≃_.from Eq.⟨ _ , equiv ⟩ (rem a , b)
}
-- Higher.Lens A B is isomorphic to Lens A B.
Higher-lens↔Lens : Higher.Lens A B ↔ Lens A B
Higher-lens↔Lens {A = A} {B = B} =
Higher.Lens A B ↝⟨ Higher.Lens-as-Σ ⟩
(∃ λ (R : Set _) →
(A ≃ (R × B)) ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ _ → Eq.≃-as-Σ ×-cong F.id) ⟩
(∃ λ (R : Set _) →
(∃ λ (f : A → R × B) → Eq.Is-equivalence f) ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ _ → inverse Σ-assoc) ⟩
(∃ λ (R : Set _) →
∃ λ (f : A → R × B) →
Eq.Is-equivalence f ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ _ → Σ-cong ΠΣ-comm λ _ → F.id) ⟩
(∃ λ (R : Set _) →
∃ λ (rg : (A → R) × (A → B)) →
Eq.Is-equivalence (λ a → proj₁ rg a , proj₂ rg a) ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ _ → inverse Σ-assoc) ⟩
(∃ λ (R : Set _) →
∃ λ (remainder : A → R) →
∃ λ (get : A → B) →
Eq.Is-equivalence (λ a → remainder a , get a) ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ _ → ∃-comm) ⟩
(∃ λ (R : Set _) →
∃ λ (get : A → B) →
∃ λ (remainder : A → R) →
Eq.Is-equivalence (λ a → remainder a , get a) ×
(R → ∥ B ∥)) ↝⟨ ∃-comm ⟩
(∃ λ (get : A → B) →
∃ λ (R : Set _) →
∃ λ (remainder : A → R) →
Eq.Is-equivalence (λ a → remainder a , get a) ×
(R → ∥ B ∥)) ↝⟨ (∃-cong λ get → ∃-cong λ R → ∃-cong λ rem → ∃-cong λ eq →
∀-cong ext λ _ → ∥∥-cong $
lemma get R rem eq _) ⟩□
(∃ λ (get : A → B) →
∃ λ (R : Set _) →
∃ λ (remainder : A → R) →
Eq.Is-equivalence (λ a → remainder a , get a) ×
Surjective remainder) □
where
lemma : ∀ _ _ _ _ _ → _
lemma = λ _ _ remainder eq r →
B ↝⟨ (inverse $ drop-⊤-right λ _ →
_⇔_.to contractible⇔↔⊤ $
singleton-contractible _) ⟩
B × Singleton r ↝⟨ Σ-assoc ⟩
(∃ λ { (_ , r′) → r′ ≡ r }) ↝⟨ (Σ-cong ×-comm λ _ → F.id) ⟩
(∃ λ { (r′ , _) → r′ ≡ r }) ↝⟨ (inverse $ Σ-cong Eq.⟨ _ , eq ⟩ λ _ → F.id) ⟩□
(∃ λ a → remainder a ≡ r) □
-- The isomorphism preserves getters and setters.
Higher-lens↔Lens-preserves-getters-and-setters :
Preserves-getters-and-setters-⇔ A B
(_↔_.logical-equivalence Higher-lens↔Lens)
Higher-lens↔Lens-preserves-getters-and-setters =
Preserves-getters-and-setters-→-↠-⇔
(_↔_.surjection Higher-lens↔Lens)
(λ _ → refl _ , refl _)
|
module Data.Unit.Instance where
open import Class.Monoid
open import Data.Unit.Polymorphic
instance
Unit-Monoid : ∀ {a} → Monoid {a} ⊤
Unit-Monoid = record { mzero = tt ; _+_ = λ _ _ -> tt }
|
#' Intersects a lits of arrays for common dimension names
#'
#' @param l. List of arrays to perform operations on
#' @param along The axis along which to intersect
#' @param drop Drop unused dimensions on result
#' @param fail_if_empty Stop if intersection yields empty set
#' @export
intersect_list = function(l., along=1, drop=FALSE, fail_if_empty=TRUE) {
if (!is.list(l.))
stop("`intersect_list()` expects a list as first argument, found: ",
class(l.))
red_int = function(...) Reduce(base::intersect, list(...))
common = do.call(red_int, dimnames(l., along=along))
if (length(common) == 0 && fail_if_empty)
stop("Intersection is empty and fail_if_empty is TRUE")
lapply(l., function(e) subset(e, index=common, along=along, drop=drop))
}
|
\chapter{Swapping order with Lebesgue integrals}
\section{Motivating limit interchange}
\prototype{$\mathbf{1}_\QQ$ is good!}
One of the issues with the Riemann integral is
that it behaves badly with respect to convergence of functions,
and the Lebesgue integral deals with this.
This is therefore often given as a poster child
or why the Lebesgue integral has better behaviors than the Riemann one.
We technically have already seen this:
consider the indicator function $\mathbf{1}_\QQ$,
which is not Riemann integrable by \Cref{prob:1QQ}.
But we can readily compute its Lebesgue integral over $[0,1]$, as
\[ \int_{[0,1]} \mathbf{1}_\QQ \; d\mu
= \mu\left( [0,1] \cap \QQ \right) = 0 \]
since it is countable.
This \emph{could} be thought of as a failure of convergence
for the Riemann integral.
\begin{example}
[$\mathbf{1}_\QQ$ is a limit of finitely supported functions]
\label{ex:1QQindicator}
We can define the sequence of functions $g_1$, $g_2$, \dots\ by
\[ g_n(x) = \begin{cases}
1 & (n!)x \text{ is an integer} \\
0 & \text{else}.
\end{cases} \]
Then each $g_n$ is piecewise continuous
and hence Riemann integrable on $[0,1]$ (with integral zero),
but $\lim_{n \to \infty} g_n = \mathbf{1}_\QQ$ is not.
\end{example}
The limit here is defined in the following sense:
\begin{definition}
Let $f$ and $f_1, f_2, \dots \colon \Omega \to \RR$ be a sequence of functions.
Suppose that for each $\omega \in \Omega$, the sequence
\[ f_1(\omega), \; f_2(\omega), \; f_3(\omega), \;, \dots \]
converges to $f(\omega)$.
Then we say $(f_n)_n$ \vocab{converges pointwise}
to the limit $f$, written $\lim_{n \to \infty} f_n = f$.
We can define $\liminf_{n \to \infty} f_n$
and $\limsup_{n \to \infty} f_n$ similarly.
\end{definition}
This is actually a fairly weak notion of convergence, for example:
\begin{exercise}
[Witch's hat]
Find a sequence of continuous function on $[-1,1] \to \RR$
which converges pointwise to the function $f$ given by
\[ f(x) = \begin{cases}
1 & x = 0 \\
0 & \text{otherwise}.
\end{cases} \]
\end{exercise}
This is why when thinking about the Riemann integral
it is commonplace to work with stronger conditions like
``uniformly convergent'' and the like.
However, with the Lebesgue integral, we can mostly not think about these!
\section{Overview}
The three big-name results for exchanging
pointwise limits with Lebesgue integrals is:
\begin{itemize}
\ii Fatou's lemma: the most general statement possible,
for any nonnegative measurable functions.
\ii Monotone convergence: ``increasing limits'' just work.
\ii Dominated convergence (actually Fatou-Lebesgue):
limits that are not too big
(bounded by some absolutely integrable function) just work.
\end{itemize}
\section{Fatou's lemma}
Without further ado:
\begin{lemma}
[Fatou's lemma]
Let $f_1, f_2, \dots \colon \Omega \to [0,+\infty]$
be a sequence of \emph{nonnegative} measurable functions.
Then $\liminf_n \colon \Omega \to [0,+\infty]$ is measurable and
\[ \int_\Omega \left( \liminf_{n \to \infty} f_n \right) \; d\mu
\le \liminf_{n \to \infty} \left( \int_\Omega f_n \; d\mu \right). \]
Here we allow either side to be $+\infty$.
\end{lemma}
Notice that there are \emph{no extra hypothesis}
on $f_n$ other than nonnegative: which makes this quite surprisingly versatile
if you ever are trying to prove some general result.
\section{Everything else}
The big surprise is how quickly all the ``big-name''
theorem follows from Fatou's lemma.
Here is the so-called ``monotone convergence theorem''.
\begin{corollary}
[Monotone convergence theorem]
Let $f$ and $f_1, f_2, \dots \colon \Omega \to [0,+\infty]$
be a sequence of \emph{nonnegative}
measurable functions such that $\lim_n f_n = f$
and $f_n(\omega) \le f(\omega)$ for each $n$.
Then $f$ is measurable and
\[ \lim_{n \to \infty} \left( \int_\Omega f_n \; d\mu \right)
= \int_\Omega f \; d\mu. \]
Here we allow either side to be $+\infty$.
\end{corollary}
\begin{proof}
We have
\begin{align*}
\int_\Omega f \; d\mu
&= \int_\Omega \left( \liminf_{n \to \infty} f_n \right) \; d\mu \\
&\le \liminf_{n \to \infty} \int_\Omega f_n \; d\mu \\
&\le \limsup_{n \to \infty} \int_\Omega f_n \; d\mu \\
&\le \int_\Omega f \; d\mu
\end{align*}
where the first $\le$ is by Fatou lemma,
and the second by the fact that
$\int_\Omega f_n \le \int_\Omega f$ for every $n$.
This implies all the inequalities are equalities and we are done.
\end{proof}
\begin{remark}
[The monotone convergence theorem does not require monotonicity!]
In the literature it is much more common
to see the hypothesis $f_1(\omega) \le f_2(\omega) \le \dots \le f(\omega)$
rather than just $f_n(\omega) \le f(\omega)$ for all $n$,
which is where the theorem gets its name.
However as we have shown this hypothesis is superfluous!
This is pointed out in \url{https://mathoverflow.net/a/296540/70654},
as a response to a question entitled
``Do you know of any very important theorems that remain unknown?''.
\end{remark}
\begin{example}
[Monotone convergence gives $\mathbf{1}_\QQ$]
This already implies \Cref{ex:1QQindicator}.
Letting $g_n$ be the indicator function for $\frac1{n!}\ZZ$
as described in that example, we have $g_n \le \mathbf{1}_\QQ$
and $\lim_{n \to \infty} g_n(x) = \mathbf{1}_\QQ(x)$,
for each individual $x$.
So since $\int_{[0,1]} g_n \; d\mu = 0$ for each $n$,
this gives $\int_{[0,1]} \mathbf{1}_\QQ = 0$ as we already knew.
\end{example}
The most famous result, though is the following.
\begin{corollary}
[Fatou–Lebesgue theorem]
Let $f$ and $f_1, f_2, \dots \colon \Omega \to \RR$
be a sequence of measurable functions.
Assume that $g \colon \Omega \to \RR$ is an
\emph{absolutely integrable} function for which
$|f_n(\omega)| \le |g(\omega)|$ for all $\omega \in \Omega$.
Then the inequality
\begin{align*}
\int_\Omega \left( \liminf_{n \to \infty} f_n \right) \; d\mu
&\le \liminf_{n \to \infty} \left( \int_\Omega f_n \; d\mu \right) \\
&\le \limsup_{n \to \infty} \left( \int_\Omega f_n \; d\mu \right)
\le \int_\Omega \left( \limsup_{n \to \infty} f_n \right) \; d\mu.
\end{align*}
\end{corollary}
\begin{proof}
There are three inequalities:
\begin{itemize}
\ii The first inequality follows by Fatou on $g + f_n$ which is nonnegative.
\ii The second inequality is just $\liminf \le \limsup$.
(This makes the theorem statement easy to remember!)
\ii The third inequality follows by Fatou on $g - f_n$ which is nonnegative.
\qedhere
\end{itemize}
\end{proof}
\begin{exercise}
Where is the fact that $g$ is absolutely integrable used in this proof?
\end{exercise}
\begin{corollary}
[Dominated convergence theorem]
Let $f_1, f_2, \dots \colon \Omega \to \RR$
be a sequence of measurable functions
such that $f = \lim_{n \to \infty} f_n$ exists.
Assume that $g \colon \Omega \to \RR$ is an
\emph{absolutely integrable} function for which
$|f_n(\omega)| \le |g(\omega)|$ for all $\omega \in \Omega$.
Then
\[ \int_\Omega f \; d \mu
= \lim_{n \to \infty} \left( \int_\Omega f_n \; d\mu \right). \]
\end{corollary}
\begin{proof}
If $f(\omega) = \lim_{n \to \infty} f_n(\omega)$,
then $f(\omega) = \liminf_{n \to \infty} f_n(\omega)
= \limsup_{n \to \infty} f_n(\omega)$.
So all the inequalities in the Fatou-Lebesgue theorem
become equalities, since the leftmost and rightmost sides are equal.
\end{proof}
Note this gives yet another way to verify \Cref{ex:1QQindicator}.
In general, the dominated convergence theorem
is a favorite clich\'{e} for undergraduate exams,
because it is easy to create questions for it.
Here is one example showing how they all look.
\begin{example}
[The usual Lebesgue dominated convergence examples]
Suppose one wishes to compute
\[ \lim_{n \to \infty}
\left( \int_{(0,1)} \frac{n\sin(n\inv x)}{\sqrt x} \right) \; dx \]
then one starts by observing that
the inner term is bounded by the absolutely integrable function $x^{-1/2}$.
Therefore it equals
\begin{align*}
\int_{(0,1)} \lim_{n \to \infty}
\left( \frac{n\sin(n\inv x)}{\sqrt x} \right) \; dx
&= \int_{(0,1)} \frac{x}{\sqrt x} \; dx \\
&= \int_{(0,1)} \sqrt{x} \; dx = \frac23.
\end{align*}
\end{example}
\section{Fubini and Tonelli}
\todo{TO BE WRITTEN}
\section{\problemhead}
\todo{problems}
|
Until election day, Pasadena ISD will be producing a series of articles and materials to provide our community and stakeholders with a detailed look at both Propositions A & B. Additionally, parent, civic, and community presentations will be held to provide further information regarding these two Propositions. Our goal is to inform our Pasadena ISD community on the facts that have led the Board of Trustees and Administration to call for these two election items. Check back regularly to our website and social media channels for more information. |
Formal statement is: lemma rel_frontier_deformation_retract_of_punctured_convex: fixes S :: "'a::euclidean_space set" assumes "convex S" "convex T" "bounded S" and arelS: "a \<in> rel_interior S" and relS: "rel_frontier S \<subseteq> T" and affS: "T \<subseteq> affine hull S" obtains r where "homotopic_with_canon (\<lambda>x. True) (T - {a}) (T - {a}) id r" "retraction (T - {a}) (rel_frontier S) r" Informal statement is: If $S$ is a convex set with nonempty interior, $T$ is a convex set, and $T$ is contained in the affine hull of $S$, then $T - \{a\}$ is a deformation retract of $S - \{a\}$. |
function res = chanlabels(this, varargin)
% Method for getting/setting the channel labels
% FORMAT res = chanlabels(this, ind, label)
% _______________________________________________________________________
% Copyright (C) 2008-2012 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: chanlabels.m 5933 2014-03-28 13:22:28Z vladimir $
if this.montage.Mind == 0
if nargin == 3
ind = varargin{1};
label = varargin{2};
if iscell(label) && length(label)>1
if isnumeric(ind) && length(ind)~=length(label)
error('Indices and values do not match');
end
if length(label)>1
for i = 1:length(label)
for j = (i+1):length(label)
if strcmp(label{i}, label{j})
error('All labels must be different');
end
end
end
end
end
end
res = getset(this, 'channels', 'label', varargin{:});
else
% case with an online montage applied
if nargin == 3
ind = varargin{1};
label = varargin{2};
if iscell(label) && length(label)>1
if isnumeric(ind) && length(ind)~=length(label)
error('Indices and values do not match');
end
if length(label)>1
for i = 1:length(label)
for j = (i+1):length(label)
if strcmp(label{i}, label{j})
error('All labels must be different');
end
end
end
end
end
this.montage.M(this.montage.Mind) = getset(this.montage.M(this.montage.Mind), 'channels', 'label', varargin{:});
res = this;
else
res = getset(this.montage.M(this.montage.Mind), 'channels', 'label', varargin{:});
end
end |
lemma complex_cnj_zero [simp]: "cnj 0 = 0" |
"""
Module: SymbolicDiff (Symbolic Operation for Arithmetic)
"""
"""
seval(f, dvar, env, cache)
Return the first derivative of expr f with respect to dvar
"""
function seval(f, dvar::Symbol)
seval(f, dvar, globalenv, SymbolicCache())
end
function seval(f, dvar::Symbol, env::SymbolicEnv)
seval(f, dvar, env, SymbolicCache())
end
function seval(f, dvar::Symbol, cache::SymbolicCache)
seval(f, dvar, globalenv, cache)
end
###
function seval(f, dvar::SymbolicVariable{Tv}) where Tv
seval(f, dvar.var)
end
function seval(f, dvar::SymbolicVariable{Tv}, env::SymbolicEnv) where Tv
seval(f, dvar.var, env)
end
function seval(f, dvar::SymbolicVariable{Tv}, cache::SymbolicCache) where Tv
seval(f, dvar.var, cache)
end
function seval(f, dvar::SymbolicVariable{Tv}, env::SymbolicEnv, cache::SymbolicCache) where Tv
seval(f, dvar.var, env, cache)
end
###
function seval(f::SymbolicValue{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
Tv(0)
end
function seval(f::SymbolicVariable{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
f.var == dvar ? 1 : 0
end
function seval(f::AbstractNumberSymbolic{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
(dvar in f.params) || return 0
get(cache, (f,dvar)) do
retval = _eval(Val(f.op), f, dvar, env, cache)
cache[(f,dvar)] = retval
end
end
"""
_eval(::Val{xx}, dvar, f, env, cache)
Dispached function to evaluate the first derivative of f
"""
function _eval(::Val{:+}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
args = [seval(x, dvar, env, cache) for x = f.args]
+(args...)
end
function _eval(::Val{:-}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
args = [seval(x, dvar, env, cache) for x = f.args]
-(args...)
end
function _eval(::Val{:*}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
args = [seval(x, env, cache) for x = f.args]
dargs = [seval(x, dvar, env, cache) for x = f.args]
ret = dargs[1]
s = args[1]
for i = 2:length(args)
ret *= args[i]
ret += s * dargs[i]
(i == length(args)) && break
s *= args[i]
end
ret
end
function _eval(::Val{:/}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x,y = [seval(x, env, cache) for x = f.args]
dx,dy = [seval(x, dvar, env, cache) for x = f.args]
(dx * y - x * dy) / y^2
end
function _eval(::Val{:^}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x,y = [seval(x, env, cache) for x = f.args]
dx,dy = [seval(x, dvar, env, cache) for x = f.args]
x^(y-1) * (x * log(x) * dy + y * dx)
end
function _eval(::Val{:exp}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x, = [seval(x, env, cache) for x = f.args]
dx, = [seval(x, dvar, env, cache) for x = f.args]
exp(x) * dx
end
function _eval(::Val{:log}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x, = [seval(x, env, cache) for x = f.args]
dx, = [seval(x, dvar, env, cache) for x = f.args]
dx / x
end
function _eval(::Val{:sqrt}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x, = [seval(x, env, cache) for x = f.args]
dx, = [seval(x, dvar, env, cache) for x = f.args]
dx /(2 * sqrt(x))
end
function _eval(::Val{:sum}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
dx, = [seval(x, dvar, env, cache) for x = f.args]
sum(dx)
end
function _eval(::Val{:dot}, f::SymbolicExpression{Tv}, dvar::Symbol, env::SymbolicEnv, cache::SymbolicCache)::Tv where Tv
x,y = [seval(x, env, cache) for x = f.args]
dx,dy = [seval(x, dvar, env, cache) for x = f.args]
dot(x,dy) + dot(dx,y)
end
|
/-
Copyright (c) 2021 James Gallicchio.
Authors: James Gallicchio
-/
import LeanColls.AuxLemmas
/-!
# Finger Trees
TODO: Describe
## References
See [Matthieu2007], section 4
-/
inductive Digit (τ : Type u) (msr : τ → M) [Monoid M]
| Digit1 : (a : τ) →
Cached (msr a) → Digit τ msr
| Digit2 : (a : τ) → (b : τ) →
Cached (msr a ++ msr b) → Digit τ msr
| Digit3 : (a : τ) → (b : τ) → (c : τ) →
Cached (msr a ++ msr b ++ msr c) → Digit τ msr
| Digit4 : (a : τ) → (b : τ) → (c : τ) → (d : τ) →
Cached (msr a ++ msr b ++ msr c ++ msr d) → Digit τ msr
namespace Digit
variable {msr : τ → M} [Monoid M] (d : Digit τ msr)
@[inline]
def tryAddLeft (a : τ) (av : Cached (msr a)) (sc : Digit τ msr → α) (fc : τ → τ → τ → τ → α) : α :=
match d with
| Digit1 b v => sc (Digit2 a b ⟨av.1 ++ v.1,by simp [av.2]⟩)
| Digit2 b c v => sc (Digit3 a b c ⟨av.1 ++ v.1,by simp [av.2]⟩)
| Digit3 b c d v => sc (Digit4 a b c d ⟨av.1 ++ v.1,by simp [av.2]⟩)
| Digit4 b c d e _ => fc b c d e
@[inline]
def tryFront (sc : τ → Digit τ msr → α) (fc : (a : τ) → Cached (msr a) → α) : α :=
match d with
| Digit1 a v => fc a v
| Digit2 a b _ => sc a (Digit1 b (cached (msr b)))
| Digit3 a b c _ => sc a (Digit2 b c (cached (msr b ++ msr c)))
| Digit4 a b c d _ => sc a (Digit3 b c d (cached (msr b ++ msr c ++ msr d)))
@[inline]
def tryAddRight (z : τ) (zv : Cached (msr z)) (sc : Digit τ msr → α) (fc : τ → τ → τ → τ → α) : α :=
match h':d with
| Digit1 y v => sc (Digit2 y z ⟨v.1 ++ zv.1,by simp [zv.2]⟩)
| Digit2 x y v => sc (Digit3 x y z ⟨v.1 ++ zv.1,by simp [zv.2]⟩)
| Digit3 w x y v => sc (Digit4 w x y z ⟨v.1 ++ zv.1,by simp [zv.2]⟩)
| Digit4 v w x y _ => fc v w x y
@[inline]
def tryBack (sc : τ → Digit τ msr → α) (fc : (a : τ) → Cached (msr a) → α) : α :=
match d with
| Digit1 z v => fc z v
| Digit2 y z v => sc z (Digit1 y (cached (msr y)))
| Digit3 x y z v => sc z (Digit2 x y (cached (msr x ++ msr y)))
| Digit4 w x y z v => sc z (Digit3 w x y (cached (msr w ++ msr x ++ msr y)))
def toList : Digit τ msr → List τ
| Digit1 a _ => [a]
| Digit2 a b _ => [a,b]
| Digit3 a b c _ => [a,b,c]
| Digit4 a b c d _ => [a,b,c,d]
end Digit
open Digit
inductive Node (τ : Type u) (msr : τ → M) [Monoid M]
| Node2 : (a : τ) → (b : τ) →
Cached (msr a ++ msr b) → Node τ msr
| Node3 : (a : τ) → (b : τ) → (c : τ) →
Cached (msr a ++ msr b ++ msr c) → Node τ msr
namespace Node
def toDigit {msr : τ → M} [Monoid M] : Node τ msr → Digit τ msr
| Node2 a b => Digit.Digit2 a b (cached (msr a ++ msr b))
| Node3 a b c => Digit.Digit3 a b c (cached (msr a ++ msr b ++ msr c))
def toList {msr : τ → M} [Monoid M] : Node τ msr → List τ
| Node2 a b => [a,b]
| Node3 a b c => [a,b,c]
end Node
open Node
inductive FingerTree [Monoid M] : (τ : Type u) → (msr : τ → M) → Type (u+3000)
| Empty : FingerTree τ msr
| Single : (t : τ) → FingerTree τ msr
| Deep : Digit τ msr → FingerTree (Node τ) msr → Digit τ msr → FingerTree τ msr
namespace FingerTree
def toList : FingerTree τ → List τ
| Empty => []
| Single x => [x]
| Deep pr tr sf => pr.toList ++ (tr.toList.bind Node.toList) ++ sf.toList
@[inline]
def cons (f : FingerTree τ) (a : τ) : FingerTree τ :=
match f with
| Empty => Single a
| Single b => Deep (Digit1 a) Empty (Digit1 b)
| Deep pr tr sf =>
tryAddLeft pr a
(λ pr' => Deep pr' tr sf)
(λ b c d e => Deep (Digit2 a b) (tr.cons (Node3 c d e)) sf)
@[inline]
def front? (f : FingerTree τ) : Option (τ × FingerTree τ) :=
match f with
| Empty => none
| Single a => some (a, Empty)
| Deep pr tr sf => some (
tryFront pr
(λ a pr' => (a, Deep pr' tr sf))
(λ a => /- pr = Digit1 a -/ (a,
match front? tr with
| some (n, tr') => Deep n.toDigit tr' sf
| none => /- tr empty -/
tryFront sf
(λ b sf' => Deep (Digit1 b) Empty sf')
(λ b => /- sf = Digit1 b -/
Single b))))
theorem toList_cons (f : FingerTree τ) (a : τ)
: (f.cons a).toList = a :: f.toList
:= by
induction f
simp [cons, toList]
simp [cons, toList, Digit.toList, List.bind, List.map, List.join]
case Deep pr tr sf ih =>
simp [cons, tryAddLeft]
split
simp [toList, Digit.toList, List.bind, List.map, List.join]
simp [toList, Digit.toList, List.bind, List.map, List.join]
simp [toList, Digit.toList, List.bind, List.map, List.join]
case h_4 b c d e =>
simp [toList, Digit.toList, List.bind, List.map, List.join, ih]
split
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join]
theorem toList_front (f : FingerTree τ)
: f.front?.map (λ (a,f') => (a,f'.toList)) = f.toList.front?
:= by
induction f
simp [front?, toList, List.front?, Option.map, Option.bind]
simp [front?, toList, List.front?, Option.map, Option.bind]
case Deep pr tr sf ih =>
match pr with
| Digit2 a b => simp [front?, toList, List.front?, tryFront, Option.map, Option.bind, HAppend.hAppend, Append.append, List.append]
| Digit3 a b c => simp [front?, toList, List.front?, tryFront, Option.map, Option.bind, HAppend.hAppend, Append.append, List.append]
| Digit4 a b c d => simp [front?, toList, List.front?, tryFront, Option.map, Option.bind, HAppend.hAppend, Append.append, List.append]
| Digit1 a =>
match h:front? tr with
| some (t,tr') =>
rw [h] at ih
simp [Option.map, Option.bind, List.front?] at ih
split at ih
contradiction
case h_2 h_tr x =>
cases x
simp [h,h_tr,front?, toList, List.front?, tryFront, Option.map, Option.bind, HAppend.hAppend, Append.append, List.append, List.bind, List.map, List.join]
cases t
repeat {simp [Digit.toList, Node.toDigit, Node.toList]}
| none =>
rw [h] at ih
simp [Option.map, Option.bind, List.front?] at ih
split at ih
focus {
case h_1 h_tr x =>
simp [h,h_tr,front?, toList, List.front?, tryFront, Option.map, Option.bind, HAppend.hAppend, Append.append, List.append, List.bind, List.map, List.join]
split
simp [Digit.toList, toList, List.bind, List.join, List.map]
simp [Digit.toList, toList, List.bind, List.join, List.map]
simp [Digit.toList, toList, List.bind, List.join, List.map]
simp [Digit.toList, toList, List.bind, List.join, List.map]
}
contradiction
def snoc (f : FingerTree τ) (z : τ) : FingerTree τ :=
match f with
| Empty => Single z
| Single b => Deep (Digit1 b) Empty (Digit1 z)
| Deep pr tr sf =>
tryAddRight sf z
(λ sf' => Deep pr tr sf')
(λ a b c d => Deep pr (tr.snoc (Node3 a b c)) (Digit2 d z))
def back? (f : FingerTree τ) : Option (FingerTree τ × τ) :=
match f with
| Empty => none
| Single z => some (Empty, z)
| Deep pr tr sf => some (
tryBack pr
(λ z sf' => (Deep pr tr sf', z))
(λ z => /- sf = Digit1 z -/ (
match back? tr with
| some (tr', n) => Deep pr tr' n.toDigit
| none => /- tr empty -/
tryBack pr
(λ y pr' => Deep pr' Empty (Digit1 y))
(λ y => /- pr = Digit1 y -/
Single y),
z)))
theorem toList_snoc (f : FingerTree τ) (a : τ)
: (f.snoc a).toList = f.toList.concat a
:= by
induction f
simp [snoc, toList, List.concat]
simp [snoc, toList, Digit.toList, List.bind, List.map, List.join, List.concat]
case Deep pr tr sf ih =>
simp [snoc, tryAddRight]
split
simp [toList, Digit.toList, List.bind, List.map, List.join, List.concat_append, List.concat]
simp [toList, Digit.toList, List.bind, List.map, List.join, List.concat_append, List.concat]
simp [toList, Digit.toList, List.bind, List.map, List.join, List.concat_append, List.concat]
case h_4 b c d e =>
simp [toList, Digit.toList, List.bind, List.map, List.join, ih, List.concat_append, List.concat]
split
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join, List.concat_append, List.concat, List.map_concat, List.join_concat, List.append_assoc]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join, List.concat_append, List.concat, List.map_concat, List.join_concat, List.append_assoc]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join, List.concat_append, List.concat, List.map_concat, List.join_concat, List.append_assoc]
simp [toList, Digit.toList, Node.toList, List.bind, List.map, List.join, List.concat_append, List.concat, List.map_concat, List.join_concat, List.append_assoc]
theorem toList_back (f : FingerTree τ)
: f.back?.map (λ (f',a) => (f'.toList,a)) = f.toList.back?
:= by sorry
def append (f1 f2 : FingerTree τ) : FingerTree τ :=
match f1, f2 with
| f1, Empty => f1
| Empty, f2 => f2
| f1, Single z => f1.snoc z
| Single a, f1 => f1.cons a
| Deep pr1 tr1 sf1, Deep pr2 tr2 sf2 =>
let tr' := match sf1, pr2 with
| Digit1 a, Digit1 b => (tr1.snoc (Node2 a b)).append tr2
| Digit2 a b, Digit1 c => (tr1.snoc (Node3 a b c)).append tr2
| Digit1 a, Digit2 b c => tr1.append (tr2.cons (Node3 a b c))
| Digit3 a b c, Digit1 d => (tr1.snoc (Node2 a b)).append (tr2.cons (Node2 c d))
| Digit2 a b, Digit2 c d => (tr1.snoc (Node2 a b)).append (tr2.cons (Node2 c d))
| Digit1 a, Digit3 b c d => (tr1.snoc (Node2 a b)).append (tr2.cons (Node2 c d))
| Digit4 a b c d, Digit1 e => (tr1.snoc (Node3 a b c)).append (tr2.cons (Node2 d e))
| Digit3 a b c, Digit2 d e => (tr1.snoc (Node3 a b c)).append (tr2.cons (Node2 d e))
| Digit2 a b, Digit3 c d e => (tr1.snoc (Node2 a b)).append (tr2.cons (Node3 c d e))
| Digit1 a, Digit4 b c d e => (tr1.snoc (Node2 a b)).append (tr2.cons (Node3 c d e))
| Digit4 a b c d, Digit2 e f => (tr1.snoc (Node3 a b c)).append (tr2.cons (Node3 d e f))
| Digit3 a b c, Digit3 d e f => (tr1.snoc (Node3 a b c)).append (tr2.cons (Node3 d e f))
| Digit2 a b, Digit4 c d e f => (tr1.snoc (Node3 a b c)).append (tr2.cons (Node3 d e f))
| Digit4 a b c d, Digit3 e f g => (tr1.snoc (Node3 a b c)).append ((tr2.cons (Node2 f g)).cons (Node2 d e))
| Digit3 a b c, Digit4 d e f g => ((tr1.snoc (Node2 a b)).snoc (Node2 c d)).append (tr2.cons (Node3 e f g))
| Digit4 a b c d, Digit4 e f g h => (tr1.snoc (Node3 a b c)).append ((tr2.cons (Node3 f g h)).cons (Node2 d e))
Deep pr1 tr' sf2
end FingerTree |
lemma local_lipschitzI: assumes "\<And>t x. t \<in> T \<Longrightarrow> x \<in> X \<Longrightarrow> \<exists>u>0. \<exists>L. \<forall>t \<in> cball t u \<inter> T. L-lipschitz_on (cball x u \<inter> X) (f t)" shows "local_lipschitz T X f" |
../src/ff_d.sv
|
(*<*)
theory Hilbert
imports Main "HOL-Eisbach.Eisbach"
abbrevs
not="\<^bold>\<not>" and disj="\<^bold>\<or>" and conj="\<^bold>\<and>" and impl="\<^bold>\<rightarrow>" and equiv="\<^bold>\<leftrightarrow>"
and true="\<^bold>\<top>" and false="\<^bold>\<bottom>"
and ob="\<^bold>\<circle>" and perm="\<^bold>P" and forb="\<^bold>F"
and derivable="\<turnstile>"
begin
(*>*)
section \<open>Proving first theorems\<close>
subsection \<open>Hilbert Calculus for Classical Logic\<close>
text \<open>Technical remark at the beginning: In order to distinguish our connectives
from the usual logical connectives of the Isabelle/HOL system, we use @{text "\<^bold>b\<^bold>o\<^bold>l\<^bold>d"}-face written
versions of them. You may use the abbreviations at the top of the document (in the theory file)
to write things down, e.g. if you start writing "dis..." (the abbreviation is "disj"),
Isabelle should suggest the autocompletion for @{text "\<^bold>\<or>"}, etc.\<close>
typedecl \<sigma> \<comment> \<open>Introduce new type for syntactical formulae (propositions).\<close>
text \<open>
For our classical propositional language, we introduce two primitive symbols:
Implication and negation. The others can be defined in terms of these two.
\<close>
consts PLimpl :: "\<sigma> \<Rightarrow> \<sigma> \<Rightarrow> \<sigma>" (infixr "\<^bold>\<rightarrow>" 49)
PLnot :: "\<sigma> \<Rightarrow> \<sigma>" ("\<^bold>\<not>_" [52]53)
consts PLatomicProp :: "\<sigma>"
definition PLdisj :: "\<sigma> \<Rightarrow> \<sigma> \<Rightarrow> \<sigma>" (infixr "\<^bold>\<or>" 50) where "a \<^bold>\<or> b \<equiv> \<^bold>\<not>a \<^bold>\<rightarrow> b"
definition PLconj :: "\<sigma> \<Rightarrow> \<sigma> \<Rightarrow> \<sigma>" (infixr "\<^bold>\<and>" 51) where "a \<^bold>\<and> b \<equiv> \<^bold>\<not>(\<^bold>\<not>a \<^bold>\<or> \<^bold>\<not>b)"
definition PLequi :: "\<sigma> \<Rightarrow> \<sigma> \<Rightarrow> \<sigma>" (infix "\<^bold>\<leftrightarrow>" 48) where "a \<^bold>\<leftrightarrow> b \<equiv> (a \<^bold>\<rightarrow> b) \<^bold>\<and> (b \<^bold>\<rightarrow> a)"
definition PLtop :: "\<sigma>" ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> PLatomicProp \<^bold>\<or> \<^bold>\<not>PLatomicProp"
definition PLbot :: "\<sigma>" ("\<^bold>\<bottom>") where "\<^bold>\<bottom> \<equiv> \<^bold>\<not>\<^bold>\<top>"
text \<open>Next we define the notion of syntactical derivability and consequence: \<close>
consts derivable :: "\<sigma> \<Rightarrow> bool" ("\<turnstile> _" 40)
definition consequence :: "\<sigma> \<Rightarrow> \<sigma> \<Rightarrow> bool" ("_ \<turnstile> _" 40) where
"A \<turnstile> B \<equiv> \<turnstile> (A \<^bold>\<rightarrow> B)"
text \<open>We can now axiomatize the derivability relation using a Hilbert-style system:\<close>
axiomatization where
A2: "\<turnstile> A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)" and (* Three Hilbert-style axioms *)
A3: "\<turnstile> (A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> C)) \<^bold>\<rightarrow> ((A \<^bold>\<rightarrow> B) \<^bold>\<rightarrow> (A \<^bold>\<rightarrow> C))" and
A4: "\<turnstile> (\<^bold>\<not>A \<^bold>\<rightarrow> \<^bold>\<not>B) \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)" and
MP: "\<turnstile> (A \<^bold>\<rightarrow> B) \<Longrightarrow> \<turnstile> A \<Longrightarrow> \<turnstile> B" (* One inference rule: Modus ponens *)
paragraph \<open>Proof example.\<close>
text \<open>Now we are ready to proof first simple theorems:\<close>
lemma "\<turnstile> A \<^bold>\<rightarrow> A"
proof -
have 1: "\<turnstile> (A \<^bold>\<rightarrow> ((B \<^bold>\<rightarrow> A) \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> ((A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> (A \<^bold>\<rightarrow> A))" by (rule A3[of _ "B \<^bold>\<rightarrow> A" "A"])
have 2: "\<turnstile> A \<^bold>\<rightarrow> ((B \<^bold>\<rightarrow> A) \<^bold>\<rightarrow> A)" by (rule A2[of _ "B \<^bold>\<rightarrow> A"])
from 1 2 have 3: "\<turnstile> (A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> (A \<^bold>\<rightarrow> A)" by (rule MP)
have 4: "\<turnstile> A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)" by (rule A2[of _ _])
from 3 4 have "\<turnstile> A \<^bold>\<rightarrow> A" by (rule MP)
then show ?thesis .
qed
text \<open>The same proof a little bit nicer with syntactic sugar:\<close>
lemma "\<turnstile> A \<^bold>\<rightarrow> A"
proof -
have "\<turnstile> (A \<^bold>\<rightarrow> ((B \<^bold>\<rightarrow> A) \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> ((A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> (A \<^bold>\<rightarrow> A))" by (rule A3[of _ "B \<^bold>\<rightarrow> A" "A"])
moreover have "\<turnstile> A \<^bold>\<rightarrow> ((B \<^bold>\<rightarrow> A) \<^bold>\<rightarrow> A)" by (rule A2[of _ "B \<^bold>\<rightarrow> A"])
ultimately have "\<turnstile> (A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)) \<^bold>\<rightarrow> (A \<^bold>\<rightarrow> A)" by (rule MP)
moreover have "\<turnstile> A \<^bold>\<rightarrow> (B \<^bold>\<rightarrow> A)" by (rule A2[of _ _])
ultimately show "\<turnstile> A \<^bold>\<rightarrow> A" by (rule MP)
qed
subsection \<open>Exercises\<close>
paragraph \<open>Exercise 2.\<close>
text \<open>Prove one of the following statements by giving an explicit proof within
the given Hilbert calculus. Please make sure that every inference step in your
proof is fine-grained and annotated with the respective calculus rule name.
Hint: Find a proof first by pen-and-paper work and then formalize it within Isabelle.\<close>
text \<open>
\<^item> @{prop "\<turnstile> \<^bold>\<not>(F \<^bold>\<rightarrow> F) \<^bold>\<rightarrow> G"}
\<^item> @{prop "\<turnstile> \<^bold>\<not>\<^bold>\<not>F \<^bold>\<rightarrow> F"}
\<close>
text "We will later see that many proofs can in fact be done almost automatically by Isabelle,
see e.g. the example from further above:"
lemma PL1: "\<turnstile> A \<^bold>\<rightarrow> A" using A2 A3 MP by blast
lemma PL2: "\<turnstile> \<^bold>\<not>(F \<^bold>\<rightarrow> F) \<^bold>\<rightarrow> G" by (metis A2 A3 A4 MP)
lemma PL3: "\<turnstile> \<^bold>\<not>\<^bold>\<not>F \<^bold>\<rightarrow> F" by (metis A2 A3 A4 MP)
text \<open>Also, to make things look a bit nicer, we define a compound strategy @{text "PL"}
(for "Propositional Logic") that applies an internal automated theorem prover with the
respective axioms for propositional logic (A2, A3, A4 and MP)\<close>
(*<*)
named_theorems add \<comment> \<open>Needed for technical reasons\<close>
(*>*)
method PL declares add = (metis A2 A3 A4 MP add)
text \<open>In the following, we can simply use @{text "by PL"} for proving propositional
tautologies. However, as proofs can be arbitrarily complicated, this method may fail
for difficult formulas.\<close>
section \<open>Hilbert proofs for MDL\<close>
text "We augment the language PL with the new connectives of MDL:"
consts ob :: "\<sigma> \<Rightarrow> \<sigma>" ("\<^bold>\<circle>_" [52]53) \<comment> \<open>New atomic connective for obligation\<close>
text \<open>The other new deontic logic connective can be defined as usual:\<close>
definition perm :: "\<sigma> \<Rightarrow> \<sigma>" ("\<^bold>P_" [52]53) where "\<^bold>P a \<equiv> \<^bold>\<not>(\<^bold>\<circle>(\<^bold>\<not>a))"
definition forbidden :: "\<sigma> \<Rightarrow> \<sigma>" ("\<^bold>F_" [52]53) where "\<^bold>F a \<equiv> \<^bold>\<circle>(\<^bold>\<not>a)"
text \<open>Next, we additionally augment the axiomatization of our proof system for PL
with the rules of the system D for MDL:\<close>
axiomatization where
K: "\<turnstile> \<^bold>\<circle>(A \<^bold>\<rightarrow> B) \<^bold>\<rightarrow> (\<^bold>\<circle>A \<^bold>\<rightarrow> \<^bold>\<circle>B)" and
D: "\<turnstile> \<^bold>\<circle>A \<^bold>\<rightarrow> \<^bold>PA" and
NEC: "\<turnstile> A \<Longrightarrow> \<turnstile> (\<^bold>\<circle>A)"
subsection \<open>MDL Proof Examples\<close>
lemma "\<turnstile> \<^bold>\<circle>(p \<^bold>\<and> q) \<^bold>\<rightarrow> \<^bold>\<circle>p"
proof -
have 1: "\<turnstile> (p \<^bold>\<and> q) \<^bold>\<rightarrow> p" by (PL add: PLconj_def PLdisj_def)
from 1 have 2: "\<turnstile> \<^bold>\<circle>((p \<^bold>\<and> q) \<^bold>\<rightarrow> p)" by (rule NEC)
have 3: "\<turnstile> \<^bold>\<circle>((p \<^bold>\<and> q) \<^bold>\<rightarrow> p) \<^bold>\<rightarrow> \<^bold>\<circle>(p \<^bold>\<and> q) \<^bold>\<rightarrow> \<^bold>\<circle>p" by (rule K)
from 3 2 show "\<turnstile> \<^bold>\<circle>(p \<^bold>\<and> q) \<^bold>\<rightarrow> \<^bold>\<circle>p" by (rule MP)
qed
text \<open>Note that, although we have the necessitation rule @{thm "NEC"} , the formula
@{term "A \<^bold>\<rightarrow> \<^bold>\<circle>A"} is not generally valid:\<close>
lemma "\<turnstile> a \<^bold>\<rightarrow> \<^bold>\<circle>a" nitpick[user_axioms,expect=genuine] oops
subsection \<open>Exercises\<close>
paragraph \<open>Exercise 2.\<close>
text \<open>Prove the following statement by giving an explicit proof within
the given Hilbert calculus. Please make sure that every inference step in your
proof is fine-grained and annotated with the respective calculus rule name. You may use
the general @{method "PL"} method for inferring propositional tautologies.
Hint: Reuse your proof from the previous exercise sheet and formalize it within Isabelle.\<close>
text \<open>
\<^item> @{prop "\<turnstile> \<^bold>\<not>\<^bold>\<circle>\<^bold>\<bottom>"}
\<close>
(*<*)
end
(*>*) |
Require Export Iron.Language.SystemF2.TyBase.
(*******************************************************************)
(* Lift type indices that are at least a certain depth. *)
Fixpoint liftTT (n: nat) (d: nat) (tt: ty) : ty :=
match tt with
| TVar ix
=> if le_gt_dec d ix
then TVar (ix + n)
else tt
| TCon _ => tt
| TForall t
=> TForall (liftTT n (S d) t)
| TApp t1 t2
=> TApp (liftTT n d t1) (liftTT n d t2)
end.
Hint Unfold liftTT.
(********************************************************************)
(* Lifting and well-formedness *)
Lemma liftTT_wfT
: forall kn t d
, wfT kn t
-> wfT (S kn) (liftTT 1 d t).
Proof.
intros. gen kn d.
lift_burn t; inverts H; try burn.
Case "TVar".
repeat (simpl; lift_cases).
eapply WfT_TVar. burn.
eapply WfT_TVar. burn.
Qed.
Hint Resolve liftTT_wfT.
(********************************************************************)
(* Lifting and type utils *)
Lemma liftTT_getCtorOfType
: forall d ix t
, getCtorOfType (liftTT d ix t) = getCtorOfType t.
Proof.
lift_burn t.
Qed.
Hint Rewrite liftTT_getCtorOfType : global.
Lemma liftTT_takeTCon
: forall tt d ix
, liftTT d ix (takeTCon tt) = takeTCon (liftTT d ix tt).
Proof.
intros; lift_burn tt.
Qed.
Hint Rewrite liftTT_takeTCon : global.
Lemma liftTT_takeTCon'
: forall n d tt tCon
, takeTCon tt = tCon
-> takeTCon (liftTT n d tt) = liftTT n d tCon.
Proof.
intros. gen n d.
induction tt; intros; rewrite <- H; burn.
Qed.
Hint Resolve liftTT_takeTCon'.
Lemma liftTT_takeTArgs
: forall tt d ix
, map (liftTT d ix) (takeTArgs tt) = takeTArgs (liftTT d ix tt).
Proof.
intros.
induction tt; intros; simpl; auto.
lift_cases; auto.
rr. burn.
Qed.
Hint Rewrite liftTT_takeTArgs : global.
Lemma liftTT_takeTArgs'
: forall n d tt tsArgs
, takeTArgs tt = tsArgs
-> takeTArgs (liftTT n d tt) = map (liftTT n d) tsArgs.
Proof.
intros.
induction tt; intros; rewrite <- H; try burn.
Qed.
Hint Resolve liftTT_takeTArgs'.
Lemma liftTT_makeTApps
: forall n d t1 ts
, liftTT n d (makeTApps t1 ts)
= makeTApps (liftTT n d t1) (map (liftTT n d) ts).
Proof.
intros. gen t1.
induction ts; burn.
Qed.
Hint Rewrite liftTT_makeTApps : global.
(********************************************************************)
Lemma liftTT_zero
: forall d t
, liftTT 0 d t = t.
Proof.
intros. gen d. lift_burn t.
Qed.
Hint Rewrite liftTT_zero : global.
Lemma liftTT_comm
: forall n m d t
, liftTT n d (liftTT m d t)
= liftTT m d (liftTT n d t).
Proof.
intros. gen d. lift_burn t.
Qed.
Lemma liftTT_succ
: forall n m d t
, liftTT (S n) d (liftTT m d t)
= liftTT n d (liftTT (S m) d t).
Proof.
intros. gen d m n. lift_burn t.
Qed.
Hint Rewrite liftTT_succ : global.
Lemma liftTT_plus
: forall n m d t
, liftTT n d (liftTT m d t) = liftTT (n + m) d t.
Proof.
intros. gen n d.
induction m; intros.
rewrite liftTT_zero; burn.
rw (n + S m = S n + m).
rewrite liftTT_comm.
rewrite <- IHm.
rewrite liftTT_comm.
burn.
Qed.
Hint Rewrite <- liftTT_plus : global.
(******************************************************************************)
Lemma liftTT_wfT_1
: forall t n ix
, wfT n t
-> liftTT 1 (n + ix) t = t.
Proof.
intros. gen n ix.
induction t; intros; inverts H; simpl; auto.
Case "TVar".
lift_cases; burn.
Case "TForall".
f_equal. spec IHt H1.
rw (S (n + ix) = S n + ix).
burn.
Case "TApp".
rs. burn.
Qed.
Hint Resolve liftTT_wfT_1.
Lemma liftTT_closedT_id_1
: forall t d
, closedT t
-> liftTT 1 d t = t.
Proof.
intros.
rw (d = d + 0). eauto.
Qed.
Hint Resolve liftTT_closedT_id_1.
Lemma liftTT_closedT_10
: forall t
, closedT t
-> closedT (liftTT 1 0 t).
Proof.
intros. red.
rw (0 = 0 + 0).
rewrite liftTT_wfT_1; auto.
Qed.
Hint Resolve liftTT_closedT_10.
(********************************************************************)
(* Changing the order of lifting.
We build this up in stages.
Start out by only allow lifting by a single place for both
applications. Then allow lifting by multiple places in the first
application, then multiple places in both.
*)
Lemma liftTT_liftTT_11
: forall d d' t
, liftTT 1 d (liftTT 1 (d + d') t)
= liftTT 1 (1 + (d + d')) (liftTT 1 d t).
Proof.
intros. gen d d'.
induction t; intros; simpl; try burn.
Case "TVar".
repeat (lift_cases; unfold liftTT); burn.
Case "TForall".
rw (S (d + d') = (S d) + d').
burn.
Qed.
Lemma liftTT_liftTT_1
: forall n1 m1 n2 t
, liftTT m1 n1 (liftTT 1 (n2 + n1) t)
= liftTT 1 (m1 + n2 + n1) (liftTT m1 n1 t).
Proof.
intros. gen n1 m1 n2 t.
induction m1; intros; simpl.
burn.
rw (S m1 = 1 + m1).
rewrite <- liftTT_plus.
rs.
rw (m1 + n2 + n1 = n1 + (m1 + n2)).
rewrite liftTT_liftTT_11.
burn.
Qed.
Lemma liftTT_liftTT
: forall m1 n1 m2 n2 t
, liftTT m1 n1 (liftTT m2 (n2 + n1) t)
= liftTT m2 (m1 + n2 + n1) (liftTT m1 n1 t).
Proof.
intros. gen n1 m1 n2 t.
induction m2; intros.
burn.
rw (S m2 = 1 + m2).
rewrite <- liftTT_plus.
rewrite liftTT_liftTT_1.
rewrite IHm2.
burn.
Qed.
Hint Rewrite liftTT_liftTT : global.
Lemma liftTT_map_liftTT
: forall m1 n1 m2 n2 ts
, map (liftTT m1 n1) (map (liftTT m2 (n2 + n1)) ts)
= map (liftTT m2 (m1 + n2 + n1)) (map (liftTT m1 n1) ts).
Proof.
induction ts; simpl; burn.
Qed.
|
A function $f$ has a non-trivial limit at $x$ if and only if for every $\epsilon > 0$, there exists a point $y \in S$ such that $0 < |x - y| < \epsilon$. |
-- Forced constructor arguments don't count towards the size of the datatype
-- (only if not --withoutK).
data _≡_ {a} {A : Set a} : A → A → Set where
refl : ∀ x → x ≡ x
data Singleton {a} {A : Set a} : A → Set where
[_] : ∀ x → Singleton x
|
Anyone requiring specialist care will need a team of highly-trained staff to support them with living with their condition. For specialist care we gain further training from outside agencies to ensure that our care teams have the most relevant and up-to-date training, ensuring we become specialist in the required areas. This makes sure that any individual receives the highest quality care achievable.
Westcountry Home Care has experience within smaller and larger packages of care such as Learning Difficulties, Epilepsy, Motor Neurone Disease, Huntington's, Parkinson’s, Multiple Sclerosis and Spinal Injuries to name a few.
We ensure that our care packages are kept person-centred for all of our customers and reviewed on a 3-month basis.
Upon initial assessment we will assess the training requirements and care needs for the individual's care package. We then establish a team in which the customer has input into along with gaining more in-depth knowledge of the specialism and training. We encourage the individual to be involved with our training if they would like to.
"Your carers are excellent! Very professional and cheerful, they couldn’t be better and I look forward to their visit. I don’t know how we would manage without them." |
Our existence is not in isolation with the rest of the world. While this idea sounds spiritual, it is very pertinent to social and global situations that we see every now and then. When a house is on fire in the neighborhood, if we don’t act, it is only a matter of time before the fire reaches our own doorstep.
There is an idea found in many ancient cultures that this world is one organism. The microcosm is a reflection of the macrocosm. Just like within us there are billions of cells with their independent existence that collectively make up our existence, all the billions of people and other creatures make up the Being of this world.
Today, there are many parts of the world that are on fire. Many governments and authorities, like in Syria and Egypt, end up using force in conflict-zones. While sometimes necessary in extreme situations, such an approach is reactive and often leads to complications in the long term. Taking care of hygiene and preserving health is easier than to go through treatment after the onset of disease. Just as we need to be proactive in maintaining our health, we need to be proactive in maintaining harmony in the world. A healthy multi-cultural exposure to children can go a long way in eliminating religious fanaticism. An attitude of service cultivated in young minds can be a preventive approach to tackling corruption. Therefore, proper education – one that inculcates human values and honors diversity, is necessary for sustainable peace in the world.
Only a few people in the world cause terror, not the whole population. Of the seven billion people on this planet, there are hardly a few thousand who cause crime and the whole world is affected. With the same law, won’t the reverse also work? Just a few thousand of us, being really peaceful, loving and caring for the whole planet — can we not bring a transformation? One should not think, ‘What can I do?” or that one is insignificant. Everyone has a role to play when the world is in turmoil. A tiny homeopathic pill has the power to heal an 80 kg body. In the same way, every individual has an influence on this cosmos, on this planet.
When we radiate peace and good vibrations, it definitely makes an impact. Those of us who have been fortunate to find some peace within ourselves, now have a challenge to reach out to all those who are not at peace with themselves as well as to those countries and parts of the world where there is conflict. The knowledge of the oneness that we share with the world can bring people out of their narrow mindsets. A bigger vision of life can kindle human values, enabling one to see diversity in oneness and unity in diversity.
New York: We have known it for ages. Now Americans have woken up to the benefits meditation brings in life.
Meditations have different effects and that meditation can lead to non-dual or transcendental experiences – a sense of self-awareness without content, says a fascinating study.
According to Fred Travis, director of the centre for brain, consciousness, and cognition at Maharishi University of Management in the US, physiological measures and first-person descriptions of transcendental experiences and higher states have only been investigated during practice of the Transcendental Meditation (TM) technique.
After analyzing descriptions of transcendental consciousness from 52 people practicing TM, Travis found that they experienced “a state where thinking, feeling, and individual intention were missing, but self-awareness remained”.
A systematic analysis of their experiences revealed three themes – absence of time, space and body sense.
“This research focuses on the larger purpose of meditation practices – to develop higher states of consciousness,” explained Travis.
With regular meditation, experiences of transcendental consciousness begin to co-exist with sleeping, dreaming and even while one is awake.
This state is called cosmic consciousness in the Vedic tradition, said the paper published in the journal Annals of the New York Academy of Sciences.
Whereas people practicing TM describe themselves in relation to concrete cognitive and behavioral processes, those experiencing cosmic consciousness describe themselves in terms of a continuum of inner self-awareness that underlies their thoughts, feelings and actions, added the paper.
“The practical benefit of higher states is that you become more anchored to your inner self, and, therefore, less likely to be overwhelmed by the vicissitudes of daily life,” said Travis.
TM is an effortless technique for automatic self-transcending, different from the other categories of meditation – focused attention or open monitoring.
It allows the mind to settle inward beyond thought to experience the source of thought – pure awareness or transcendental consciousness.
This is the most silent and peaceful level of consciousness – one’s innermost self, said the study. |
Rural Rap and Jewelry is a booth run by Sally Parker at the Davis Farmers Market on Saturdays that sells jewelry to benefit Rural RAP. The jewelry is a mix of necklaces and bracelets, earrings, and small sculptures made with sculpting clay. Sally accepts Davis Dollars.
Rural R(R?)AP was incorporated as a nonprofit by Isao Fujimoto. Rural RAP stands for Rural Research Access Project.
|
module Network.Curl.Types.SSL
import Network.Curl.Types.Code
import Util
import Derive.Enum
%language ElabReflection
data CurlSSLBackend
= CURLSSLBACKEND_NONE -- 0,
| CURLSSLBACKEND_OPENSSL -- 1,
| CURLSSLBACKEND_GNUTLS -- 2,
| CURLSSLBACKEND_NSS -- 3,
| CURLSSLBACKEND_GSKIT -- 5,
| CURLSSLBACKEND_POLARSSL -- 6, /* deprecated */
| CURLSSLBACKEND_WOLFSSL -- 7,
| CURLSSLBACKEND_SCHANNEL -- 8,
| CURLSSLBACKEND_SECURETRANSPORT -- 9,
| CURLSSLBACKEND_AXTLS -- 10, /* deprecated */
| CURLSSLBACKEND_MBEDTLS -- 11,
| CURLSSLBACKEND_MESALINK -- 12,
| CURLSSLBACKEND_BEARSSL -- 13
Show CurlSSLBackend where
show = showEnum
Eq CurlSSLBackend where
(==) = eqEnum
Ord CurlSSLBackend where
compare = compareEnum
ToCode CurlSSLBackend where
toCode = enumTo [0,1,2,3, 5,6,7,8,9,10,11,12,13]
FromCode CurlSSLBackend where
unsafeFromCode = unsafeEnumFrom [0,1,2,3, 5,6,7,8,9,10,11,12,13]
fromCode = enumFrom [0,1,2,3, 5,6,7,8,9,10,11,12,13]
data CurlSSLSet
= CURLSSLSET_OK -- = 0
| CURLSSLSET_UNKNOWN_BACKEND
| CURLSSLSET_TOO_LATE
| CURLSSLSET_NO_BACKENDS
Show CurlSSLSet where
show = showEnum
Eq CurlSSLSet where
(==) = eqEnum
Ord CurlSSLSet where
compare = compareEnum
ToCode CurlSSLSet where
toCode = enumTo [0..3]
FromCode CurlSSLSet where
unsafeFromCode = unsafeEnumFrom [0..3]
fromCode = enumFrom [0..3]
{-
typedef struct {
curl_sslbackend id;
const char *name;
} curl_ssl_backend;
-} |
/-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import ring_theory.int.basic
import ring_theory.localization
/-!
# Gauss's Lemma
Gauss's Lemma is one of a few results pertaining to irreducibility of primitive polynomials.
## Main Results
- `polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map`:
A primitive polynomial is irreducible iff it is irreducible in a fraction field.
- `polynomial.is_primitive.int.irreducible_iff_irreducible_map_cast`:
A primitive polynomial over `ℤ` is irreducible iff it is irreducible over `ℚ`.
- `polynomial.is_primitive.dvd_iff_fraction_map_dvd_fraction_map`:
Two primitive polynomials divide each other iff they do in a fraction field.
- `polynomial.is_primitive.int.dvd_iff_map_cast_dvd_map_cast`:
Two primitive polynomials over `ℤ` divide each other if they do in `ℚ`.
-/
open_locale non_zero_divisors
variables {R : Type*} [comm_ring R] [is_domain R]
namespace polynomial
section normalized_gcd_monoid
variable [normalized_gcd_monoid R]
section
variables {S : Type*} [comm_ring S] [is_domain S] {φ : R →+* S} (hinj : function.injective φ)
variables {f : polynomial R} (hf : f.is_primitive)
include hinj hf
lemma is_primitive.is_unit_iff_is_unit_map_of_injective :
is_unit f ↔ is_unit (map φ f) :=
begin
refine ⟨(map_ring_hom φ).is_unit_map, λ h, _⟩,
rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩,
have hdeg := degree_C u.ne_zero,
rw [hu, degree_map_eq_of_injective hinj] at hdeg,
rw [eq_C_of_degree_eq_zero hdeg, is_primitive_iff_content_eq_one,
content_C, normalize_eq_one] at hf,
rwa [eq_C_of_degree_eq_zero hdeg, is_unit_C],
end
lemma is_primitive.irreducible_of_irreducible_map_of_injective (h_irr : irreducible (map φ f)) :
irreducible f :=
begin
refine ⟨λ h, h_irr.not_unit (is_unit.map ((map_ring_hom φ).to_monoid_hom) h), _⟩,
intros a b h,
rcases h_irr.is_unit_or_is_unit (by rw [h, map_mul]) with hu | hu,
{ left,
rwa (hf.is_primitive_of_dvd (dvd.intro _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj },
right,
rwa (hf.is_primitive_of_dvd (dvd.intro_left _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj
end
end
section fraction_map
variables {K : Type*} [field K] [algebra R K] [is_fraction_ring R K]
lemma is_primitive.is_unit_iff_is_unit_map {p : polynomial R} (hp : p.is_primitive) :
is_unit p ↔ is_unit (p.map (algebra_map R K)) :=
hp.is_unit_iff_is_unit_map_of_injective (is_fraction_ring.injective _ _)
open is_localization
lemma is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part
{p : polynomial K} (h0 : p ≠ 0) (h : is_unit (integer_normalization R⁰ p).prim_part) :
is_unit p :=
begin
rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩,
obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ p,
rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hc,
apply is_unit_of_mul_is_unit_right,
rw [← hc, (integer_normalization R⁰ p).eq_C_content_mul_prim_part, ← hu,
← ring_hom.map_mul, is_unit_iff],
refine ⟨algebra_map R K ((integer_normalization R⁰ p).content * ↑u),
is_unit_iff_ne_zero.2 (λ con, _), by simp⟩,
replace con := (algebra_map R K).injective_iff.1 (is_fraction_ring.injective _ _) _ con,
rw [mul_eq_zero, content_eq_zero_iff, is_fraction_ring.integer_normalization_eq_zero_iff] at con,
rcases con with con | con,
{ apply h0 con },
{ apply units.ne_zero _ con },
end
/-- **Gauss's Lemma** states that a primitive polynomial is irreducible iff it is irreducible in the
fraction field. -/
theorem is_primitive.irreducible_iff_irreducible_map_fraction_map
{p : polynomial R} (hp : p.is_primitive) :
irreducible p ↔ irreducible (p.map (algebra_map R K)) :=
begin
refine ⟨λ hi, ⟨λ h, hi.not_unit (hp.is_unit_iff_is_unit_map.2 h), λ a b hab, _⟩,
hp.irreducible_of_irreducible_map_of_injective (is_fraction_ring.injective _ _)⟩,
obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ a,
obtain ⟨⟨d, d0⟩, hd⟩ := integer_normalization_map_to_map R⁰ b,
rw [algebra.smul_def, algebra_map_apply, subtype.coe_mk] at hc hd,
rw mem_non_zero_divisors_iff_ne_zero at c0 d0,
have hcd0 : c * d ≠ 0 := mul_ne_zero c0 d0,
rw [ne.def, ← C_eq_zero] at hcd0,
have h1 : C c * C d * p = integer_normalization R⁰ a * integer_normalization R⁰ b,
{ apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _,
rw [map_mul, map_mul, map_mul, hc, hd, map_C, map_C, hab],
ring },
obtain ⟨u, hu⟩ : associated (c * d) (content (integer_normalization R⁰ a) *
content (integer_normalization R⁰ b)),
{ rw [← dvd_dvd_iff_associated, ← normalize_eq_normalize_iff, normalize.map_mul,
normalize.map_mul, normalize_content, normalize_content,
← mul_one (normalize c * normalize d), ← hp.content_eq_one, ← content_C, ← content_C,
← content_mul, ← content_mul, ← content_mul, h1] },
rw [← ring_hom.map_mul, eq_comm,
(integer_normalization R⁰ a).eq_C_content_mul_prim_part,
(integer_normalization R⁰ b).eq_C_content_mul_prim_part, mul_assoc,
mul_comm _ (C _ * _), ← mul_assoc, ← mul_assoc, ← ring_hom.map_mul, ← hu, ring_hom.map_mul,
mul_assoc, mul_assoc, ← mul_assoc (C ↑u)] at h1,
have h0 : (a ≠ 0) ∧ (b ≠ 0),
{ classical,
rw [ne.def, ne.def, ← decidable.not_or_iff_and_not, ← mul_eq_zero, ← hab],
intro con,
apply hp.ne_zero (map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _),
simp [con] },
rcases hi.is_unit_or_is_unit (mul_left_cancel₀ hcd0 h1).symm with h | h,
{ right,
apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.2
(is_unit_of_mul_is_unit_right h) },
{ left,
apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.1 h },
end
lemma is_primitive.dvd_of_fraction_map_dvd_fraction_map {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive)
(h_dvd : p.map (algebra_map R K) ∣ q.map (algebra_map R K)) : p ∣ q :=
begin
rcases h_dvd with ⟨r, hr⟩,
obtain ⟨⟨s, s0⟩, hs⟩ := integer_normalization_map_to_map R⁰ r,
rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hs,
have h : p ∣ q * C s,
{ use (integer_normalization R⁰ r),
apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _),
rw [map_mul, map_mul, hs, hr, mul_assoc, mul_comm r],
simp },
rw [← hp.dvd_prim_part_iff_dvd, prim_part_mul, hq.prim_part_eq,
associated.dvd_iff_dvd_right] at h,
{ exact h },
{ symmetry,
rcases is_unit_prim_part_C s with ⟨u, hu⟩,
use u,
rw hu },
iterate 2 { apply mul_ne_zero hq.ne_zero,
rw [ne.def, C_eq_zero],
contrapose! s0,
simp [s0, mem_non_zero_divisors_iff_ne_zero] }
end
variables (K)
lemma is_primitive.dvd_iff_fraction_map_dvd_fraction_map {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive) :
(p ∣ q) ↔ (p.map (algebra_map R K) ∣ q.map (algebra_map R K)) :=
⟨λ ⟨a,b⟩, ⟨a.map (algebra_map R K), b.symm ▸ map_mul (algebra_map R K)⟩,
λ h, hp.dvd_of_fraction_map_dvd_fraction_map hq h⟩
end fraction_map
/-- **Gauss's Lemma** for `ℤ` states that a primitive integer polynomial is irreducible iff it is
irreducible over `ℚ`. -/
theorem is_primitive.int.irreducible_iff_irreducible_map_cast
{p : polynomial ℤ} (hp : p.is_primitive) :
irreducible p ↔ irreducible (p.map (int.cast_ring_hom ℚ)) :=
hp.irreducible_iff_irreducible_map_fraction_map
lemma is_primitive.int.dvd_iff_map_cast_dvd_map_cast (p q : polynomial ℤ)
(hp : p.is_primitive) (hq : q.is_primitive) :
(p ∣ q) ↔ (p.map (int.cast_ring_hom ℚ) ∣ q.map (int.cast_ring_hom ℚ)) :=
hp.dvd_iff_fraction_map_dvd_fraction_map ℚ hq
end normalized_gcd_monoid
end polynomial
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_DEF_BUILDER_MAKE_MESSAGE_API_HPP
#define NBDL_DEF_BUILDER_MAKE_MESSAGE_API_HPP
#include <nbdl/concept/UpstreamMessage.hpp>
#include <nbdl/def/builder/entity_messages.hpp>
#include <nbdl/def/builder/producer_meta.hpp>
#include <boost/hana/functional/on.hpp>
#include <boost/hana/functional/partial.hpp>
#include <boost/hana/flatten.hpp>
#include <boost/hana/partition.hpp>
#include <boost/hana/type.hpp>
#include <boost/hana/unpack.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/integral.hpp>
namespace nbdl_def::builder
{
using namespace boost::mp11;
namespace hana = boost::hana;
template <
typename UpstreamMessageTypes
, typename DownstreamMessageTypes
>
struct message_api_meta
{
using upstream_types = UpstreamMessageTypes;
using downstream_types = DownstreamMessageTypes;
};
struct make_message_api_fn
{
template <typename T>
struct is_upstream_message
: mp_bool<nbdl::UpstreamMessage<T>>
{ };
// aggregate all entity messages
// and partition by upstream/downstream
template<typename ProducersMeta>
constexpr auto operator()(ProducersMeta) const
{
return
mp_apply<message_api_meta,
mp_partition<
mp_apply<mp_append,
mp_transform<builder::entity_messages,
mp_apply<mp_append,
mp_transform_q<mpdef::metastruct_get<decltype(producer_meta::access_points)>,
ProducersMeta
>>>>
, is_upstream_message
>>{};
}
};
constexpr make_message_api_fn make_message_api{};
}
#endif
|
State Before: a b : Nat
h : a ≤ b
⊢ max a b = b State After: no goals Tactic: simp [Nat.max_def, h, Nat.not_lt.2 h] |
import analysis.calculus.deriv
import algebra.group.pi
import analysis.normed_space.ordered
namespace asymptotics
open filter
open_locale topological_space
lemma is_o.tendsto_of_tendsto_const {α E 𝕜 : Type*} [normed_group E] [normed_field 𝕜] {u : α → E}
{v : α → 𝕜} {l : filter α} {y : 𝕜} (huv : is_o u v l) (hv : tendsto v l (𝓝 y)) :
tendsto u l (𝓝 0) :=
begin
suffices h : is_o u (λ x, (1 : 𝕜)) l,
{ rwa is_o_one_iff at h },
exact huv.trans_is_O (is_O_one_of_tendsto 𝕜 hv),
end
section normed_linear_ordered_group
variables {α β : Type*} [normed_linear_ordered_group β] {u v w : α → β} {l : filter α} {c : ℝ}
lemma is_O.trans_tendsto_norm_at_top (huv : is_O u v l)
(hu : tendsto (λ x, ∥u x∥) l at_top) :
tendsto (λ x, ∥v x∥) l at_top :=
begin
rcases huv.exists_pos with ⟨c, hc, hcuv⟩,
rw is_O_with at hcuv,
convert tendsto_at_top_div hc (tendsto_at_top_mono' l hcuv hu),
ext x,
rw mul_div_cancel_left _ hc.ne.symm,
end
end normed_linear_ordered_group
end asymptotics |
%
% OK
%
% setting up at Aug. third, 2009
% finished at Aug 5th, 2009
% seems to be OK
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Introduction to delta function}
\label{sec:delta_function}
As what we can see, in the discussion of quantum mechanics or even the
quantum chemistry, we always meet the situation that the delta
function has to be used (for example, the normalization of free
particle wave function, the discussion of position and momentum
operator in \ref{sec:PRAMR_in_position_representation} etc. For the
case of the continuous basis functions, the delta function is
frequently used). Hence in this part, we are going to give some
mathematical introduction for the delta function.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Definition of delta function}
\label{sec:definition_delta_function}
%
%
%
%
The delta function can be considered as some ``peculiar'' function
which has two features below:
\begin{equation}
\label{DELTAeq:1}
\delta (x) = \begin{cases}
\infty & x = 0 \\
0 & x \neq 0
\end{cases}
\end{equation}
\begin{equation}
\label{DELTAeq:2}
\int_{-\infty}^{+\infty}\delta (x)dx =
\int_{-\epsilon}^{+\epsilon}\delta (x)dx = 1
\end{equation}
Here $(-\epsilon, \epsilon)$ is some ``small enough'' open interval
around the $0$. The (\ref{DELTAeq:1}) and (\ref{DELTAeq:2}) are also
the definition for the delta function, which indicates that the
delta function is infinity at $0$, but quickly tends to $0$ as is
apart from the $0$ point.
Now let's give some examples. Firstly, consider the function below:
\begin{equation}\label{}
\Psi_{n}(x) = \frac{\sin nx}{\pi x} \quad \text{$n$ is some natural
number }
\end{equation}
Firstly, we can prove that:
\begin{align}\label{}
\lim_{x \rightarrow 0}\Psi_{n}(x) = \lim_{x \rightarrow 0}\frac{\sin
nx}{\pi x} = \lim_{x \rightarrow 0}\frac{\sin nx}{n x}\frac{n}{\pi}
= \frac{n}{\pi}
\end{align}
So we can think that $\Psi_{n}(0) = \frac{n}{\pi}$. Here as $n
\rightarrow +\infty$, $\Psi_{\infty}(0) \rightarrow +\infty$. Hence
the (\ref{DELTAeq:1}) is satisfied.
Secondly, from the improper integral theory, we can know that:
\begin{equation}\label{}
\int_{0}^{+\infty}\frac{\sin nx}{x}dx = \frac{\pi}{2}
\end{equation}
Hence we have the integral as:
\begin{align}\label{}
\int_{-\infty}^{+\infty}\frac{\sin nx}{\pi x}dx &=
2\frac{1}{\pi}\int_{0}^{+\infty}\frac{\sin nx}{x}dx \quad
\text{here the $\Psi_{n}(x)$ is even function}\nonumber \\
&=2\frac{1}{\pi}\times\frac{\pi}{2} \nonumber \\
&=1
\end{align}
So the (\ref{DELTAeq:2}) is satisfied. Thus we can have
$\Psi_{\infty}(x) = \delta(x)$.
From the definition of $\Psi_{n}(x)$, we can even prove that the
function below is also the delta function:
\begin{equation}\label{}
\Phi(x) = \frac{1}{2\pi}\int_{-\infty}^{+\infty} e^{ikx}dk
\end{equation}
This function is very important in discussing the property related
to plane wave functions. Firstly, as $x = 0$, it's easy to see tat
the $\Phi(0) = \frac{1}{2\pi}\int_{-\infty}^{+\infty} dk \Rightarrow
\infty$, so the (\ref{DELTAeq:1}) is satisfied.
As for the (\ref{DELTAeq:2}) since we have (suggest that $a$ is some
natural number):
\begin{align}\label{}
\Phi_{a}(x) = \frac{1}{2\pi}\int_{-a}^{+a} e^{ikx}dk &=
\frac{1}{i2x\pi}e^{ikx}\Big|^{a}_{-a} \nonumber \\
&=\frac{1}{i2x\pi}2i\sin ax \quad \cos(a) = \cos(-a)\nonumber \\
&=\frac{\sin ax}{x\pi}
\end{align}
Hence the integral for the $\Phi(x)$ in the whole real space has
been resorted to the $\Psi_{a\rightarrow \infty}(x)$; so we have:
\begin{equation}\label{}
\Phi(x) = \delta(x)
\end{equation}
Finally, let's consider the Gauss distribution function:
\begin{equation}\label{}
\Omega_{\sigma}(x) =
\frac{1}{\sqrt{2\pi\sigma}}e^{-\frac{x^{2}}{2\sigma}}
\end{equation}
Firstly, we can see that:
\begin{align}\label{}
\Omega_{\sigma}(0) &= \frac{1}{\sqrt{2\pi\sigma}}\times 1 \quad
\underrightarrow{\sigma \rightarrow 0} \nonumber
\\
\Omega_{\sigma \rightarrow 0 }(0) &= \infty
\end{align}
On the other hand, since from the improper integral theory, we have:
\begin{equation}\label{DELTAeq:20}
\int_{0}^{+\infty}e^{-x^{2}}dx = \frac{\sqrt{\pi}}{2}
\end{equation}
Then we have the integral for the $\Omega_{\sigma}(x)$ as:
\begin{align}\label{}
\int_{-\infty}^{+\infty}
\frac{1}{\sqrt{2\pi\sigma}}e^{-\frac{x^{2}}{2\sigma}} dx &=
\frac{1}{\sqrt{2\pi\sigma}}\int_{-\infty}^{+\infty}
e^{-\frac{x^{2}}{2\sigma}} dx \nonumber \\
&= \frac{2}{\sqrt{2\pi\sigma}}\int_{0}^{+\infty}\sqrt{2\sigma}
e^{-(\frac{x}{\sqrt{2\sigma}})^{2}} d\frac{x}{\sqrt{2\sigma}} \quad
\text{$\Omega_{\sigma}(x)$ is even} \nonumber \\
&=\frac{2}{\sqrt{\pi}}\times\frac{\sqrt{\pi}}{2} \quad
\text{From the \ref{DELTAeq:20}}\nonumber \\
&= 1
\end{align}
Hence we have $\Omega_{0}(x) = \delta(x)$.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Characters of delta function}
\label{sec:character_delta_function}
%
%
%
%
In this section let's state some characters of delta function.
\begin{theorem}
$\delta(x)$ is some even function: $\delta(x) = \delta(-x)$
\end{theorem}
\begin{proof}
the proof is straightforward. For (\ref{DELTAeq:1}), the
$\delta(-x)$ is naturally satisfied, and for the integral in the
(\ref{DELTAeq:2}) we have:
\begin{equation}\label{}
\int_{-\infty}^{+\infty}\delta(-x)dx =
-\int_{-\infty}^{+\infty}\delta(-x)d(-x) =
\int_{-\infty}^{+\infty}\delta(t)dt = 1
\end{equation}
Hence $\delta(x) = \delta(-x)$. \qedhere
\end{proof}
\begin{theorem}
$\delta(ax) = \frac{1}{|a|}\delta(x)$
\end{theorem}
\begin{proof}
Firstly suggest that $a>0$, then:
\begin{equation}\label{DELTAeq:3}
\begin{split}
\int_{-\infty}^{+\infty}\delta(ax)dx &=
\frac{1}{a}\int_{-\infty}^{+\infty}\delta(ax)d(ax) \\
&= \frac{1}{a}\delta(x)
\end{split}
\end{equation}
For the $a < 0$ (in this case, if we simply repeat the progress in
\ref{DELTAeq:3}; the upper limit and the lower limit in integral
should change), since we have $\delta(ax) = \delta(-ax)$; then we
can replace the $a$ with $|a|$ to repeat the demonstration in
(\ref{DELTAeq:3}). So finally we can get the conclusion. \qedhere
\end{proof}
\begin{theorem}
\label{DELTA:4}
$\int_{-\infty}^{+\infty}f(x)\delta(x)dx = f(0)$.
\end{theorem}
\begin{proof}
\begin{equation}\label{}
\begin{split}
\int_{-\infty}^{+\infty}f(x)\delta(x)dx &=
\int_{-\epsilon}^{+\epsilon}f(x)\delta(x)dx \\
&= f(0)\int_{-\epsilon}^{+\epsilon}\delta(x)dx \\
&= f(0)
\end{split}
\end{equation} \qedhere
\end{proof}
The theorem (\ref{DELTA:4}) is some important expression for delta
function. Now consider the delta function $\delta (x - x^{'})$,
where $x^{'}$ is some arbitrary number; it can be easily understood
that the (\ref{DELTAeq:1}) and (\ref{DELTAeq:2}) are converted as:
\begin{equation}
\label{DELTAeq:5} \delta (x - x^{'}) = \begin{cases}
\infty & x = x^{'} \\
0 & x \neq x^{'}
\end{cases}
\end{equation}
\begin{equation}
\label{DELTAeq:6}
\int_{-\infty}^{+\infty}\delta (x - x^{'})dx =
\int_{-\epsilon}^{+\epsilon}\delta (x - x^{'})dx = 1
\end{equation}
The (\ref{DELTAeq:1}) and (\ref{DELTAeq:2}) can be considered as the
special case while $x^{'} = 0$. Through this expansion, by using the
theorem (\ref{DELTA:4}) we can prove that the relation below is
true:
\begin{theorem}
\begin{equation}\label{DELTAeq:7}
\int_{-\infty}^{+\infty}f(x)\delta(x - x^{'})dx =
\int_{-\infty}^{+\infty}f(x^{'})\delta(x - x^{'})dx^{'} =f(x)
\end{equation}
\end{theorem}
\begin{proof}
For the first equation in the (\ref{DELTAeq:7}), we can directly use
the even function character to prove it. For the second equation in
(\ref{DELTAeq:7}), we have:
\begin{equation}\label{}
\begin{split}
\int_{-\infty}^{+\infty}f(x)\delta(x - x^{'})dx &=
\int_{-\infty}^{+\infty}f(t+x^{'})\delta(t)dt
\quad t = x - x^{'}\\
&= f(t+x^{'})\Big|_{t=0} \quad \text{From theorem \ref{DELTA:4}}\\
&= f(x^{'})
\end{split}
\end{equation}
\qedhere
\end{proof}
\begin{theorem}
$\delta(x) = \delta^{*}(x)$
\end{theorem}
\begin{proof}
Suggest that we have some arbitrary real function of $f(x)$,
\begin{equation}\label{}
\begin{split}
\left[\int_{-\infty}^{+\infty}f(x)\delta(x)dx\right]^{*} &=
\int_{-\infty}^{+\infty}f(x)\delta^{*}(x)dx \\
&=f^{*}(0) = f(0) \\
&= \int_{-\infty}^{+\infty}f(x)\delta(x)dx \Rightarrow \\
&= \int_{-\infty}^{+\infty}f(x)
\Big(\delta(x)-\delta^{*}(x)\Big)dx = 0
\end{split}
\end{equation}
Hence we have $\delta(x) = \delta^{*}(x)$. \qedhere
\end{proof}
\begin{theorem}
$\int_{-\infty}^{+\infty}\delta(x - x^{'}) \delta(x - x^{''})dx =
\delta(x^{'} - x^{''})$. Here $x^{'}$ and $x^{''}$ are both of
arbitrary real number.
\end{theorem}
\begin{proof}
From (\ref{DELTAeq:7}), we set the $f(x) = \delta(x)$ so according
to the (\ref{DELTAeq:7}):
\begin{equation}\label{}
\begin{split}
\int_{-\infty}^{+\infty}f(x- x^{''})\delta(x - x^{'})dx
&= f(x- x^{''})\Big|_{x =x^{'}} \\
&= f(x^{'}- x^{''})
\end{split}
\end{equation}
\qedhere
\end{proof}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Example to use delta function:
the normalization of plane wave functions}
\label{sec:normalization_delta_function}
%
%
%
%
Now by using the delta function let's solve some important problem
in quantum mechanics: how to normalize the plane wave function?
According to the (\ref{BASICeq:14}), the plane wave function can be
expressed as:
\begin{equation}\label{}
\Psi_{p}(x) = e^{\frac{ipx}{\hbar}}
\end{equation}
Actually it's the eigen state for the $\hat{p}$:
\begin{equation}\label{}
\hat{p}\Psi_{p}(x) = p\Psi_{p}(x)
\end{equation}
Now let's go to see how to normalize this function:
\begin{equation}\label{}
\begin{split}
\langle \Psi_{p}(x^{'})|\Psi_{p}(x)\rangle
=\int_{-\infty}^{+\infty}\Psi^{*}(x')\Psi(x)dp
&= \int_{-\infty}^{+\infty} e^{\frac{ip(x-x^{'})}{\hbar}}dp \\
&= \hbar\int_{-\infty}^{+\infty} e^{\frac{ip(x-x^{'})}{\hbar}}
d\left(\frac{p}{\hbar}\right) \\
&= 2\pi\hbar\delta(x-x^{'})
\end{split}
\end{equation}
Hence if we integrate over all the $x$:
\begin{equation}\label{}
\begin{split}
\int_{-\infty}^{+\infty}
\langle \Psi_{p}(x^{'})|\Psi_{p}(x)\rangle dx
&= \int_{-\infty}^{+\infty} 2\pi\hbar\delta(x-x^{'}) dx \\
&= 2\pi\hbar
\end{split}
\end{equation}
Thus finally we can express the plane wave function as:
\begin{equation}\label{}
\Psi_{p}(x) = \frac{1}{\sqrt{2\pi\hbar}}e^{\frac{ipx}{\hbar}}
\end{equation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../main"
%%% End:
|
(*
I hereby assign copyright in my past and future contributions
to the Software Foundations project to the Author of Record of
each volume or component, to be licensed under the same terms
as the rest of Software Foundations. I understand that, at present,
the Authors of Record are as follows: For Volumes 1 and 2, known
until 2016 as "Software Foundations" and from 2016 as (respectively)
"Logical Foundations" and "Programming Foundations," and for Volume 4,
"QuickChick: Property-Based Testing in Coq," the Author of Record is
Benjamin C. Pierce. For Volume 3, "Verified Functional Algorithms",
the Author of Record is Andrew W. Appel. For components outside of
designated volumes (e.g., typesetting and grading tools and other
software infrastructure), the Author of Record is Benjamin Pierce.
*)
Inductive day : Type :=
| monday : day
| tuesday : day
| wednesday : day
| thursday : day
| friday : day
| saturday : day
| sunday : day.
Definition next_weekday (d:day) : day :=
match d with
| monday => tuesday
| tuesday => wednesday
| wednesday => thursday
| thursday => friday
| friday => monday
| saturday => monday
| sunday => monday
end.
Compute (next_weekday friday).
(* ==> monday : day *)
Compute (next_weekday (next_weekday saturday)).
(* ==> tuesday : day *)
Example test_next_weekday:
(next_weekday (next_weekday saturday)) = tuesday.
Proof. simpl. reflexivity. Qed.
(** ** Booleans *)
Inductive bool : Type :=
| true : bool
| false : bool.
Definition negb (b:bool) : bool :=
match b with
| true => false
| false => true
end.
Definition andb (b1:bool) (b2:bool) : bool :=
match b1 with
| true => b2
| false => false
end.
Definition orb (b1:bool) (b2:bool) : bool :=
match b1 with
| true => true
| false => b2
end.
Example test_orb1: (orb true false) = true.
Proof. simpl. reflexivity. Qed.
Example test_orb2: (orb false false) = false.
Proof. simpl. reflexivity. Qed.
Example test_orb3: (orb false true) = true.
Proof. simpl. reflexivity. Qed.
Example test_orb4: (orb true true) = true.
Proof. simpl. reflexivity. Qed.
Notation "x && y" := (andb x y).
Notation "x || y" := (orb x y).
Example test_orb5: false || false || true = true.
Proof. simpl. reflexivity. Qed.
(** **** Exercise: 1 star (nandb) *)
(** Remove "[Admitted.]" and complete the definition of the following
function; then make sure that the [Example] assertions below can
each be verified by Coq. (Remove "[Admitted.]" and fill in each
proof, following the model of the [orb] tests above.) The function
should return [true] if either or both of its inputs are
[false]. *)
Definition nandb (b1:bool) (b2:bool) : bool
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Example test_nandb1: (nandb true false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb2: (nandb false false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb3: (nandb false true) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb4: (nandb true true) = false.
(* FILL IN HERE *) Admitted.
(** [] *)
(** **** Exercise: 1 star (andb3) *)
(** Do the same for the [andb3] function below. This function should
return [true] when all of its inputs are [true], and [false]
otherwise. *)
Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Example test_andb31: (andb3 true true true) = true.
(* FILL IN HERE *) Admitted.
Example test_andb32: (andb3 false true true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb33: (andb3 true false true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb34: (andb3 true true false) = false.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ================================================================= *)
(** ** Function Types *)
Check true.
(* ===> true : bool *)
Check (negb true).
(* ===> negb true : bool *)
Check negb.
(* ===> negb : bool -> bool *)
(* ================================================================= *)
(** ** Compound Types *)
Inductive rgb : Type :=
| red : rgb
| green : rgb
| blue : rgb.
Inductive color : Type :=
| black : color
| white : color
| primary : rgb -> color.
(*
Exercise : What is the type of primary? What about primary blue?
Write appropriate commands that print the types of these expressions.
*)
Definition monochrome (c : color) : bool :=
match c with
| black => true
| white => true
| primary p => false
end.
Definition isred (c : color) : bool :=
match c with
| black => false
| white => false
| primary red => true
| primary _ => false
end.
(*
Exercise: What is the type of each of these functions?
Write appropriate commands that print the types of these expressions.
*)
(*
Exercise: Prove that isred returns false when the color is blue.
You need to write an assertion that specifies this, and then
prove it.
*)
(* ================================================================= *)
(** ** Modules *)
Module NatPlayground.
(* ================================================================= *)
(** ** Numbers *)
Inductive nat : Type :=
| O : nat
| S : nat -> nat.
Definition pred (n : nat) : nat :=
match n with
| O => O
| S n' => n'
end.
End NatPlayground.
Check (S (S (S (S O)))).
(* ===> 4 : nat *)
Definition minustwo (n : nat) : nat :=
match n with
| O => O
| S O => O
| S (S n') => n'
end.
Compute (minustwo 4).
(* ===> 2 : nat *)
Check S.
Check pred.
Check minustwo.
Compute (S (minustwo (S (S O)))).
(*New Session!*)
Fixpoint evenb (n:nat) : bool :=
match n with
| O => true
| S O => false
| S (S n') => evenb n'
end.
Definition oddb (n:nat) : bool := negb (evenb n).
Example test_oddb1: oddb 1 = true.
Proof. simpl. reflexivity. Qed.
Example test_oddb2: oddb 4 = false.
Proof. simpl. reflexivity. Qed.
Module NatPlayground2.
Fixpoint plus (n : nat) (m : nat) : nat :=
match n with
| O => m
| S n' => S (plus n' m)
end.
Compute (plus 3 2).
Fixpoint mult (n m : nat) : nat :=
match n with
| O => O
| S n' => plus m (mult n' m)
end.
Example test_mult1: (mult 3 3) = 9.
Proof. simpl. reflexivity. Qed.
Fixpoint minus (n m:nat) : nat :=
match n, m with
| O , _ => O
| S _ , O => n
| S n', S m' => minus n' m'
end.
End NatPlayground2.
Fixpoint exp (base power : nat) : nat :=
match power with
| O => S O
| S p => mult base (exp base p)
end.
(** **** Exercise: 1 star (factorial) *)
(** Recall the standard mathematical factorial function:
factorial(0) = 1
factorial(n) = n * factorial(n-1) (if n>0)
Translate this into Coq. *)
Fixpoint factorial (n:nat) : nat
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Example test_factorial1: (factorial 3) = 6.
(* FILL IN HERE *) Admitted.
Example test_factorial2: (factorial 5) = (mult 10 12).
(* FILL IN HERE *) Admitted.
(** [] *)
Notation "x + y" := (plus x y)
(at level 50, left associativity)
: nat_scope.
Notation "x - y" := (minus x y)
(at level 50, left associativity)
: nat_scope.
Notation "x * y" := (mult x y)
(at level 40, left associativity)
: nat_scope.
Check ((0 + 1) + 1).
Fixpoint beq_nat (n m : nat) : bool :=
match n with
| O => match m with
| O => true
| S m' => false
end
| S n' => match m with
| O => false
| S m' => beq_nat n' m'
end
end.
Fixpoint leb (n m : nat) : bool :=
match n with
| O => true
| S n' =>
match m with
| O => false
| S m' => leb n' m'
end
end.
Example test_leb1: (leb 2 2) = true.
Proof. simpl. reflexivity. Qed.
Example test_leb2: (leb 2 4) = true.
Proof. simpl. reflexivity. Qed.
Example test_leb3: (leb 4 2) = false.
Proof. simpl. reflexivity. Qed.
(** **** Exercise: 1 star (blt_nat) *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
yielding a [b]oolean. Instead of making up a new [Fixpoint] for
this one, define it in terms of a previously defined function. *)
Definition blt_nat (n m : nat) : bool
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Example test_blt_nat1: (blt_nat 2 2) = false.
(* FILL IN HERE *) Admitted.
Example test_blt_nat2: (blt_nat 2 4) = true.
(* FILL IN HERE *) Admitted.
Example test_blt_nat3: (blt_nat 4 2) = false.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ################################################################# *)
(** * Proof by Simplification *)
Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
intros n. simpl. reflexivity. Qed.
Theorem plus_O_n' : forall n : nat, 0 + n = n.
Proof.
intros n. reflexivity. Qed.
Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
intros n. reflexivity. Qed.
Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
intros n. reflexivity. Qed.
(* ################################################################# *)
(** * Proof by Rewriting *)
Theorem plus_id_example : forall n m:nat,
n = m ->
n + n = m + m.
Proof.
(* move both quantifiers into the context: *)
intros n m.
(* move the hypothesis into the context: *)
intros H.
(* rewrite the goal using the hypothesis: *)
rewrite -> H.
reflexivity. Qed.
Theorem mult_0_plus : forall n m : nat,
(0 + n) * m = n * m.
Proof.
intros n m.
rewrite -> plus_O_n.
reflexivity. Qed.
(** **** Exercise: 1 star (plus_id_exercise) *)
(** Remove "[Admitted.]" and fill in the proof. *)
Theorem plus_id_exercise : forall n m o : nat,
n = m -> m = o -> n + m = m + o.
Proof.
intros n m o.
intros H J.
rewrite -> H.
rewrite <- J.
reflexivity. Qed.
(** **** Exercise: 2 stars (mult_S_1) *)
Theorem mult_S_1 : forall n m : nat,
m = S n ->
m * (1 + n) = m * m.
Proof.
intros n m.
intros H.
rewrite -> H.
reflexivity. Qed.
(* ################################################################# *)
(** * Proof by Case Analysis *)
Theorem plus_1_neq_0_firsttry : forall n : nat,
beq_nat (n + 1) 0 = false.
Proof.
intros n.
simpl. (* does nothing! *)
Abort.
Theorem plus_1_neq_0 : forall n : nat,
beq_nat (n + 1) 0 = false.
Proof.
intros n. destruct n as [| n'].
- reflexivity.
- reflexivity. Qed.
Theorem negb_involutive : forall b : bool,
negb (negb b) = b.
Proof.
intros b. destruct b.
- reflexivity.
- reflexivity. Qed.
Theorem andb_commutative : forall b c, andb b c = andb c b.
Proof.
intros b c. destruct b.
- destruct c.
+ reflexivity.
+ reflexivity.
- destruct c.
+ reflexivity.
+ reflexivity.
Qed.
Theorem andb_commutative' : forall b c, andb b c = andb c b.
Proof.
intros b c. destruct b.
{ destruct c.
{ reflexivity. }
{ reflexivity. } }
{ destruct c.
{ reflexivity. }
{ reflexivity. } }
Qed.
Theorem andb3_exchange :
forall b c d, andb (andb b c) d = andb (andb b d) c.
Proof.
intros b c d. destruct b.
- destruct c.
{ destruct d.
- reflexivity.
- reflexivity. }
{ destruct d.
- reflexivity.
- reflexivity. }
- destruct c.
{ destruct d.
- reflexivity.
- reflexivity. }
{ destruct d.
- reflexivity.
- reflexivity. }
Qed.
Theorem plus_1_neq_0' : forall n : nat,
beq_nat (n + 1) 0 = false.
Proof.
intros [|n].
- reflexivity.
- reflexivity. Qed.
Theorem andb_commutative'' :
forall b c, andb b c = andb c b.
Proof.
intros [] [].
- reflexivity.
- reflexivity.
- reflexivity.
- reflexivity.
Qed.
(** **** Exercise: 2 stars (andb_true_elim2) *)
(** Prove the following claim, marking cases (and subcases) with
bullets when you use [destruct]. *)
Theorem andb_true_elim2 : forall b c : bool,
andb b c = true -> c = true.
Proof.
intros b c. intros H. destruct c. - reflexivity. - destruct b. + simpl in H. rewrite -> H. reflexivity. + simpl in H. rewrite -> H. reflexivity. Qed.
(** [] *)
(** **** Exercise: 1 star (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
beq_nat 0 (n + 1) = false.
Proof.
intros [|n].
reflexivity.
reflexivity.
Qed.
|
[STATEMENT]
lemma p2r_conj_hom [simp]: "\<lceil>P\<rceil> \<inter> \<lceil>Q\<rceil> = \<lceil>\<lambda>s. P s \<and> Q s\<rceil>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lceil>P\<rceil> \<inter> \<lceil>Q\<rceil> = \<lceil>\<lambda>s. P s \<and> Q s\<rceil>
[PROOF STEP]
by auto |
# 16 PDEs: Waves
(See *Computational Physics* Ch 21 and *Computational Modeling* Ch 6.5.)
## Background: waves on a string
Assume a 1D string of length $L$ with mass density per unit length $\rho$ along the $x$ direction. It is held under constant tension $T$ (force per unit length). Ignore frictional forces and the tension is so high that we can ignore sagging due to gravity.
### 1D wave equation
The string is displaced in the $y$ direction from its rest position, i.e., the displacement $y(x, t)$ is a function of space $x$ and time $t$.
For small relative displacements $y(x, t)/L \ll 1$ and therefore small slopes $\partial y/\partial x$ we can describe $y(x, t)$ with a *linear* equation of motion:
Newton's second law applied to short elements of the string with length $\Delta x$ and mass $\Delta m = \rho \Delta x$: the left hand side contains the *restoring force* that opposes the displacement, the right hand side is the acceleration of the string element:
\begin{align}
\sum F_{y}(x) &= \Delta m\, a(x, t)\\
T \sin\theta(x+\Delta x) - T \sin\theta(x) &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2}
\end{align}
The angle $\theta$ measures by how much the string is bent away from the resting configuration.
Because we assume small relative displacements, the angles are small ($\theta \ll 1$) and we can make the small angle approximation
$$
\sin\theta \approx \tan\theta = \frac{\partial y}{\partial x}
$$
and hence
\begin{align}
T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x} &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2}\\
\frac{T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x}}{\Delta x} &= \rho \frac{\partial^2 y}{\partial t^2}
\end{align}
or in the limit $\Delta x \rightarrow 0$ a linear hyperbolic PDE results:
\begin{gather}
\frac{\partial^2 y(x, t)}{\partial x^2} = \frac{1}{c^2} \frac{\partial^2 y(x, t)}{\partial t^2}, \quad c = \sqrt{\frac{T}{\rho}}
\end{gather}
where $c$ has the dimension of a velocity. This is the (linear) **wave equation**.
### General solution: waves
General solutions are propagating waves:
If $f(x)$ is a solution at $t=0$ then
$$
y_{\mp}(x, t) = f(x \mp ct)
$$
are also solutions at later $t > 0$.
Because of linearity, any linear combination is also a solution, so the most general solution contains both right and left propagating waves
$$
y(x, t) = A f(x - ct) + B g(x + ct)
$$
(If $f$ and/or $g$ are present depends on the initial conditions.)
In three dimensions the wave equation is
$$
\boldsymbol{\nabla}^2 y(\mathbf{x}, t) - \frac{1}{c^2} \frac{\partial^2 y(\mathbf{x}, t)}{\partial t^2} = 0\
$$
### Boundary and initial conditions
* The boundary conditions could be that the ends are fixed
$$y(0, t) = y(L, t) = 0$$
* The *initial condition* is a shape for the string, e.g., a Gaussian at the center
$$
y(x, t=0) = g(x) = y_0 \frac{1}{\sqrt{2\pi\sigma}} \exp\left[-\frac{(x - x_0)^2}{2\sigma^2}\right]
$$
at time 0.
* Because the wave equation is *second order in time* we need a second initial condition, for instance, the string is released from rest:
$$
\frac{\partial y(x, t=0)}{\partial t} = 0
$$
(The derivative, i.e., the initial displacement velocity is provided.)
### Analytical solution
Solve (as always) with *separation of variables*.
$$
y(x, t) = X(x) T(t)
$$
and this yields the general solution (with boundary conditions of fixed string ends and initial condition of zero velocity) as a superposition of normal modes
$$
y(x, t) = \sum_{n=0}^{+\infty} B_n \sin k_n x\, \cos\omega_n t,
\quad \omega_n = ck_n,\ k_n = n \frac{2\pi}{L} = n k_0.
$$
(The angular frequency $\omega$ and the wave vector $k$ are determined from the boundary conditions.)
The coefficients $B_n$ are obtained from the initial shape:
$$
y(x, t=0) = \sum_{n=0}^{+\infty} B_n \sin n k_0 x = g(x)
$$
In principle one can use the fact that $\int_0^L dx \sin m k_0 x \, \sin n k_0 x = \pi \delta_{mn}$ (orthogonality) to calculate the coefficients:
\begin{align}
\int_0^L dx \sin m k_0 x \sum_{n=0}^{+\infty} B_n \sin n k_0 x &= \int_0^L dx \sin(m k_0 x) \, g(x)\\
\pi \sum_{n=0}^{+\infty} B_n \delta_{mn} &= \dots \\
B_m &= \pi^{-1} \dots
\end{align}
(but the analytical solution is ugly and I cannot be bothered to put it down here.)
## Numerical solution
1. discretize wave equation
2. time stepping: leap frog algorithm (iterate)
Use the central difference approximation for the second order derivatives:
\begin{align}
\frac{\partial^2 y}{\partial t^2} &\approx \frac{y(x, t+\Delta t) + y(x, t-\Delta t) - 2y(x, t)}{\Delta t ^2} = \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2}\\
\frac{\partial^2 y}{\partial x^2} &\approx \frac{y(x+\Delta x, t) + y(x-\Delta x, t) - 2y(x, t)}{\Delta x ^2} = \frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2}
\end{align}
and substitute into the wave equation to yield the *discretized* wave equation:
$$
\frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2} = \frac{1}{c^2} \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2}
$$
Re-arrange so that the future terms $j+1$ can be calculated from the present $j$ and past $j-1$ terms:
$$
y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad
\beta := \frac{c}{\Delta x/\Delta t}
$$
This is the time stepping algorithm for the wave equation.
## Numerical implementation
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.style.use('ggplot')
```
### Student version
```python
L = 0.5 # m
Nx = 50
Nt = 100
Dx = L/Nx
Dt = 1e-4 # s
rho = 1.5e-2 # kg/m
tension = 150 # N
c = np.sqrt(tension/rho)
# TODO: calculate beta
beta = c*Dt/Dx
beta2 = beta**2
print("c = {0} m/s".format(c))
print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt))
print("beta = {}".format(beta))
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L):
return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2))
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((Nt+1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1]
# save initial
t_index = 0
y_t[t_index, :] = y0
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
```
c = 100.0 m/s
Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s
beta = 1.0
Completed 99 iterations: t=0.0099 s
### Fancy version
Package as a function and can use `step` to only save every `step` time steps.
```python
def wave(L=0.5, Nx=50, Dt=1e-4, Nt=100, step=1,
rho=1.5e-2, tension=150.):
Dx = L/Nx
#rho = 1.5e-2 # kg/m
#tension = 150 # N
c = np.sqrt(tension/rho)
beta = c*Dt/Dx
beta2 = beta**2
print("c = {0} m/s".format(c))
print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt))
print("beta = {}".format(beta))
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L):
return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2))
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1]
# save initial
t_index = 0
y_t[t_index, :] = y0
if step == 1:
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
if jt % step == 0 or jt == Nt-1:
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
return y_t, X, Dx, Dt, step
```
```python
y_t, X, Dx, Dt, step = wave()
```
c = 100.0 m/s
Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s
beta = 1.0
Completed 99 iterations: t=0.0099 s
### 1D plot
Plot the output in the save array `y_t`. Vary the time steps that you look at with `y_t[start:end]`.
We indicate time by color changing.
```python
ax = plt.subplot(111)
ax.set_prop_cycle("color", [plt.cm.viridis(i) for i in np.linspace(0, 1, len(y_t))])
ax.plot(X, y_t[:40].T, alpha=0.5);
```
### 1D Animation
For 1D animation to work in a Jupyter notebook, use
```python
%matplotlib widget
```
If no animations are visible, restart kernel and execute the `%matplotlib notebook` cell as the very first one in the notebook.
We use `matplotlib.animation` to look at movies of our solution:
```python
import matplotlib.animation as animation
```
Generate one full period:
```python
y_t, X, Dx, Dt, step = wave(Nt=100)
```
The `update_wave()` function simply re-draws our image for every `frame`.
```python
y_limits = 1.05*y_t.min(), 1.05*y_t.max()
fig1 = plt.figure(figsize=(5,5))
ax = fig1.add_subplot(111)
ax.set_aspect(1)
def update_wave(frame, data):
global ax, Dt, y_limits
ax.clear()
ax.set_xlabel("x (m)")
ax.set_ylabel("y (m)")
ax.plot(X, data[frame])
ax.set_ylim(y_limits)
ax.text(0.1, 0.9, "t = {0:3.1f} ms".format(frame*Dt*1e3), transform=ax.transAxes)
wave_anim = animation.FuncAnimation(fig1, update_wave, frames=len(y_t), fargs=(y_t,),
interval=30, blit=True, repeat_delay=100)
```
If you have ffmpeg installed then you can export to a MP4 movie file:
```python
wave_anim.save("string.mp4", fps=30, dpi=300)
```
The whole video can be incoroporated into an html page (uses the HTML5 `<video>` tag).
```python
with open("string.html", "w") as html:
html.write(wave_anim.to_html5_video())
```
```python
```
### 3D plot
(Uses functions from previous lessons.)
```python
def plot_y(y_t, Dt, Dx, step=1):
T, X = np.meshgrid(range(y_t.shape[0]), range(y_t.shape[1]))
Y = y_t.T[X, T] # intepret index 0 as "t" and index 1 as "x", but plot x along axis 1 and t along axis 2
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot_wireframe(X*Dx, T*Dt*step, Y)
ax.set_ylabel(r"time $t$ (s)")
ax.set_xlabel(r"position $x$ (m)")
ax.set_zlabel(r"displacement $y$ (m)")
fig.tight_layout()
return ax
def plot_surf(y_t, Dt, Dx, step=1, filename=None, offset=-1, zlabel=r'displacement',
elevation=40, azimuth=-20, cmap=plt.cm.coolwarm):
"""Plot y_t as a 3D plot with contour plot underneath.
Arguments
---------
y_t : 2D array
displacement y(t, x)
filename : string or None, optional (default: None)
If `None` then show the figure and return the axes object.
If a string is given (like "contour.png") it will only plot
to the filename and close the figure but return the filename.
offset : float, optional (default: 20)
position the 2D contour plot by offset along the Z direction
under the minimum Z value
zlabel : string, optional
label for the Z axis and color scale bar
elevation : float, optional
choose elevation for initial viewpoint
azimuth : float, optional
chooze azimuth angle for initial viewpoint
"""
t = np.arange(y_t.shape[0], dtype=int)
x = np.arange(y_t.shape[1], dtype=int)
T, X = np.meshgrid(t, x)
Y = y_t.T[X, T]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X*Dx, T*Dt*step, Y, cmap=cmap, rstride=1, cstride=1, alpha=1)
cset = ax.contourf(X*Dx, T*Dt*step, Y, 20, zdir='z', offset=offset+Y.min(), cmap=cmap)
ax.set_xlabel('x')
ax.set_ylabel('t')
ax.set_zlabel(zlabel)
ax.set_zlim(offset + Y.min(), Y.max())
ax.view_init(elev=elevation, azim=azimuth)
cb = fig.colorbar(surf, shrink=0.5, aspect=5)
cb.set_label(zlabel)
if filename:
fig.savefig(filename)
plt.close(fig)
return filename
else:
return ax
```
```python
plot_y(y_t, Dt, Dx)
```
```python
plot_surf(y_t, Dt, Dx, offset=-0.04, cmap=plt.cm.coolwarm)
```
## von Neumann stability analysis: Courant condition
Assume that the solutions of the discretized equation can be written as normal modes
$$
y_{m,j} = \xi(k)^j e^{ikm\Delta x}, \quad t=j\Delta t,\ x=m\Delta x
$$
The time stepping algorith is stable if
$$
|\xi(k)| < 1
$$
Insert normal modes into the discretized equation
$$
y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad
\beta := \frac{c}{\Delta x/\Delta t}
$$
and simplify (use $1-\cos x = 2\sin^2\frac{x}{2}$):
$$
\xi^2 - 2(1-2\beta^2 s^2)\xi + 1 = 0, \quad s=\sin(k\Delta x/2)
$$
The characteristic equation has roots
$$
\xi_{\pm} = 1 - 2\beta^2 s^2 \pm \sqrt{(1-2\beta^2 s^2)^2 - 1}.
$$
It has one root for
$$
\left|1-2\beta^2 s^2\right| = 1,
$$
i.e., for
$$
\beta s = 1
$$
We have two real roots for
$$
\left|1-2\beta^2 s^2\right| < 1 \\
\beta s > 1
$$
but one of the roots is always $|\xi| > 1$ and hence these solutions will diverge and not be stable.
For
$$
\left|1-2\beta^2 s^2\right| ≥ 1 \\
\beta s ≤ 1
$$
the roots will be *complex conjugates of each other*
$$
\xi_\pm = 1 - 2\beta^2s^2 \pm i\sqrt{1-(1-2\beta^2s^2)^2}
$$
and the *magnitude*
$$
|\xi_{\pm}|^2 = (1 - 2\beta^2s^2)^2 - (1-(1-2\beta^2s^2)^2) = 1
$$
is unity: Thus the solutions will not grow and will be *stable* for
$$
\beta s ≤ 1\\
\frac{c}{\frac{\Delta x}{\Delta t}} \sin\frac{k \Delta x}{2} ≤ 1
$$
Assuming the "worst case" for the $\sin$ factor (namely, 1), the **condition for stability** is
$$
c ≤ \frac{\Delta x}{\Delta t}
$$
or
$$
\beta ≤ 1.
$$
This is also known as the **Courant condition**. When written as
$$
\Delta t ≤ \frac{\Delta x}{c}
$$
it means that the time step $\Delta t$ (for a given $\Delta x$) must be *smaller than the time that the wave takes to travel one grid step*.
## Simplified simulation
The above example used real numbers for a cello string. Below is bare-bones where we just set $\beta$.
```python
L = 10.0
Nx = 100
Nt = 200
step = 1
Dx = L/Nx
beta2 = 1.0
X = np.linspace(0, L, Nx+1) # need N+1!
def gaussian(x):
return np.exp(-(x-5)**2)
# displacements at j-1, j, j+1
y0 = np.zeros_like(X)
y1 = np.zeros_like(y0)
y2 = np.zeros_like(y0)
# save array
y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1))
# boundary conditions
y0[0] = y0[-1] = y1[0] = y1[-1] = 0
y2[:] = y0
# initial conditions: velocity 0, i.e. no difference between y0 and y1
y0[:] = y1[:] = gaussian(X)
# save initial
t_index = 0
y_t[t_index, :] = y0
if step == 1:
t_index += 1
y_t[t_index, :] = y1
for jt in range(2, Nt):
y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2])
y0[:], y1[:] = y1, y2
if jt % step == 0 or jt == Nt-1:
t_index += 1
y_t[t_index, :] = y2
print("Iteration {0:5d}".format(jt), end="\r")
else:
print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt))
```
```python
ax = plt.subplot(111)
ax.set_prop_cycle("color", [plt.cm.viridis_r(i) for i in np.linspace(0, 1, len(y_t))])
ax.plot(X, y_t.T);
```
```python
```
|
theory IP_Address_toString
imports IP_Address IPv4 IPv6
Lib_Word_toString
Lib_List_toString
"HOL-Library.Code_Target_Nat" (*!!*)
begin
section\<open>Pretty Printing IP Addresses\<close>
subsection\<open>Generic Pretty Printer\<close>
text\<open>Generic function. Whenever possible, use IPv4 or IPv6 pretty printing!\<close>
definition ipaddr_generic_toString :: "'i::len word \<Rightarrow> string" where
"ipaddr_generic_toString ip \<equiv>
''[IP address ('' @ string_of_nat (LENGTH('i)) @ '' bit): '' @ dec_string_of_word0 ip @ '']''"
lemma "ipaddr_generic_toString (ipv4addr_of_dotdecimal (192,168,0,1)) = ''[IP address (32 bit): 3232235521]''" by eval
subsection\<open>IPv4 Pretty Printing\<close>
fun dotteddecimal_toString :: "nat \<times> nat \<times> nat \<times> nat \<Rightarrow> string" where
"dotteddecimal_toString (a,b,c,d) =
string_of_nat a@''.''@string_of_nat b@''.''@string_of_nat c@''.''@string_of_nat d"
definition ipv4addr_toString :: "ipv4addr \<Rightarrow> string" where
"ipv4addr_toString ip = dotteddecimal_toString (dotdecimal_of_ipv4addr ip)"
lemma "ipv4addr_toString (ipv4addr_of_dotdecimal (192, 168, 0, 1)) = ''192.168.0.1''" by eval
text\<open>Correctness Theorems:\<close>
thm dotdecimal_of_ipv4addr_ipv4addr_of_dotdecimal
ipv4addr_of_dotdecimal_dotdecimal_of_ipv4addr
subsection\<open>IPv6 Pretty Printing\<close>
definition ipv6addr_toString :: "ipv6addr \<Rightarrow> string" where
"ipv6addr_toString ip = (
let partslist = ipv6_preferred_to_compressed (int_to_ipv6preferred ip);
\<comment> \<open>add empty lists to the beginning and end if omission occurs at start/end\<close>
\<comment> \<open>to join over \<^verbatim>\<open>:\<close> properly\<close>
fix_start = (\<lambda>ps. case ps of None#_ \<Rightarrow> None#ps | _ \<Rightarrow> ps);
fix_end = (\<lambda>ps. case rev ps of None#_ \<Rightarrow> ps@[None] | _ \<Rightarrow> ps)
in list_separated_toString '':''
(\<lambda>pt. case pt of None \<Rightarrow> ''''
| Some w \<Rightarrow> hex_string_of_word0 w)
((fix_end \<circ> fix_start) partslist)
)"
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0x2001 0xDB8 0x0 0x0 0x8 0x800 0x200C 0x417A))
= ''2001:db8::8:800:200c:417a''" by eval \<comment> \<open>a unicast address\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0xFF01 0x0 0x0 0x0 0x0 0x0 0x0 0x0101)) =
''ff01::101''" by eval \<comment> \<open>a multicast address\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0 0 0 0 0x8 0x800 0x200C 0x417A)) =
''::8:800:200c:417a''" by eval
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0x2001 0xDB8 0 0 0 0 0 0)) =
''2001:db8::''" by eval
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0xFF00 0 0 0 0 0 0 0)) =
''ff00::''" by eval \<comment> \<open>Multicast\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0xFE80 0 0 0 0 0 0 0)) =
''fe80::''" by eval \<comment> \<open>Link-Local unicast\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0 0 0 0 0 0 0 0)) =
''::''" by eval \<comment> \<open>unspecified address\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int (IPv6AddrPreferred 0 0 0 0 0 0 0 1)) =
''::1''" by eval \<comment> \<open>loopback address\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0x2001 0xdb8 0x0 0x0 0x0 0x0 0x0 0x1)) =
''2001:db8::1''" by eval \<comment> \<open>Section 4.1 of RFC5952\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0x2001 0xdb8 0x0 0x0 0x0 0x0 0x2 0x1)) =
''2001:db8::2:1''" by eval \<comment> \<open>Section 4.2.1 of RFC5952\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0x2001 0xdb8 0x0 0x1 0x1 0x1 0x1 0x1)) =
''2001:db8:0:1:1:1:1:1''" by eval \<comment> \<open>Section 4.2.2 of RFC5952\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0x2001 0x0 0x0 0x1 0x0 0x0 0x0 0x1)) =
''2001:0:0:1::1''" by eval \<comment> \<open>Section 4.2.3 of RFC5952\<close>
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0x2001 0xdb8 0x0 0x0 0x1 0x0 0x0 0x1)) =
''2001:db8::1:0:0:1''" by eval \<comment> \<open>Section 4.2.3 of RFC5952\<close>
lemma "ipv6addr_toString max_ipv6_addr = ''ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff''" by eval
lemma "ipv6addr_toString (ipv6preferred_to_int
(IPv6AddrPreferred 0xffff 0xffff 0xffff 0xffff 0xffff 0xffff 0xffff 0xffff)) =
''ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff''" by eval
text\<open>Correctness Theorems:\<close>
thm ipv6_preferred_to_compressed
ipv6_preferred_to_compressed_RFC_4291_format
ipv6_unparsed_compressed_to_preferred_identity1
ipv6_unparsed_compressed_to_preferred_identity2
RFC_4291_format
ipv6preferred_to_int_int_to_ipv6preferred
int_to_ipv6preferred_ipv6preferred_to_int
end
|
lemma (in sigma_algebra) sets_Collect_countable_Ball: assumes "\<And>i. {x\<in>\<Omega>. P i x} \<in> M" shows "{x\<in>\<Omega>. \<forall>i::'i::countable\<in>X. P i x} \<in> M" |
! { dg-do run }
module m
implicit character(8) (a-z)
contains
function f(x)
integer :: x
integer :: f
real :: e
f = x
return
entry e(x)
e = x
end
end module
program p
use m
if (f(1) /= 1) call abort
if (e(1) /= 1.0) call abort
end
|
module Ag05 where
open import Agda.Builtin.Nat
open import Agda.Builtin.Equality
open import Agda.Builtin.Bool
{-
data _≡_ {A : Set} (x : A) : A → Set where
refl : x ≡ x
-}
data Refine : (A : Set) → (A → Set) → Set where
MkRefine : ∀ {A : Set} {f : A → Set} → (a : A) → (f a) → Refine A f
data _∧_ : Set → Set → Set where
and : ∀ (A B : Set) → A ∧ B
-- hl-suc : ∀ {a : Nat} → Refine Nat (λ )
silly : Set
silly = Refine Nat (_≡_ 0)
sillySon : silly
sillySon = MkRefine zero refl
data _≤_ : Nat → Nat → Set where
z≤s : ∀ {b : Nat} → 0 ≤ b
s≤s : ∀ {m n : Nat} → m ≤ n → suc m ≤ suc n
data le-Total (x y : Nat) : Set where
le-left : x ≤ y → le-Total x y
le-right : y ≤ x → le-Total x y
le : Nat → Nat → Bool
le zero zero = true
le zero (suc n) = true
le (suc m) zero = false
le (suc m) (suc n) = le m n
le-wtf : ∀ (x y : Nat) → le-Total x y
le-wtf zero zero = le-left z≤s
le-wtf zero (suc y) = le-left z≤s
le-wtf (suc x) zero = le-right z≤s
le-wtf (suc x) (suc y) with le-wtf x y
... | le-left P = le-left (s≤s P)
... | le-right Q = le-right (s≤s Q)
{- with le x y -- x ≤ y
... | true = {!!}
... | false = {!!}
-}
_⟨_⟩ : (A : Set) → (A → Set) → Set
_⟨_⟩ = Refine
and-refine : ∀ {A : Set} (f g : A → Set)
→ (a : A) → f a → g a
→ Refine A (λ x → (f x) ∧ (g x))
and-refine f g x Pa Pb = MkRefine x (and (f x) (g x))
hSuc : ∀ {m : Nat} → ( Nat ⟨ (λ x → x ≤ m ) ⟩ )
→ ( Nat ⟨ (λ x → x ≤ suc m ) ⟩ )
hSuc (MkRefine a P) = MkRefine (suc a) (s≤s P)
postulate
≤-trans : ∀ {x y z : Nat} → x ≤ y → y ≤ z → x ≤ z
min : ∀ {m n : Nat} → ( Nat ⟨ (λ x → x ≤ m) ⟩ )
→ ( Nat ⟨ (λ x → x ≤ n) ⟩ )
→ ( Nat ⟨ (λ x → (x ≤ m) ∧ (x ≤ n)) ⟩ )
min (MkRefine a Pa) (MkRefine b Pb) with le-wtf a b
... {- a ≤ b -} | le-left P = {!and-refine ? ? Pa ? !}
... {- b ≤ a -} | le-right Q = {!and-refine _ _ ? Pb !}
{-
with le-Total a b
... | le-left a = {!!}
... | le-right b = ? -}
{-
min {m} {n} (MkRefine a P₀) (MkRefine b P₁) with (le a b)
... | true = {!!}
... | false = {!!}
-}
{-
min {m} {n} (MkRefine zero x) (MkRefine b y) = MkRefine 0 (and (zero ≤ m) (zero ≤ n))
min {m} {n} (MkRefine (suc a) x) (MkRefine zero y) = MkRefine 0 (and (zero ≤ m) (zero ≤ n))
min {suc m} {suc n} (MkRefine (suc a) x) (MkRefine (suc b) y) = {!hSuc (min (MkRefine a ?) (MkRefine b ?))!}
-}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.