text
stringlengths 0
3.34M
|
---|
#pragma once
#include <boost/variant.hpp>
#include <vector>
#include "export.hpp"
namespace ear {
struct EAR_EXPORT CartesianPosition {
CartesianPosition(double X = 0.0, double Y = 0.0, double Z = 0.0)
: X(X), Y(Y), Z(Z){};
double X;
double Y;
double Z;
};
struct EAR_EXPORT PolarPosition {
PolarPosition(double azimuth = 0.0, double elevation = 0.0,
double distance = 1.0)
: azimuth(azimuth), elevation(elevation), distance(distance){};
double azimuth;
double elevation;
double distance;
};
using Position = boost::variant<CartesianPosition, PolarPosition>;
} // namespace ear
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Sean Leather
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.free_monoid
import Mathlib.algebra.opposites
import Mathlib.control.traversable.instances
import Mathlib.control.traversable.lemmas
import Mathlib.category_theory.category.default
import Mathlib.category_theory.endomorphism
import Mathlib.category_theory.types
import Mathlib.category_theory.category.Kleisli
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# List folds generalized to `traversable`
Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the
reconstructed data structure and, in a state monad, we care about the final state.
The obvious way to define `foldl` would be to use the state monad but it
is nicer to reason about a more abstract interface with `fold_map` as a
primitive and `fold_map_hom` as a defining property.
```
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ...
lemma fold_map_hom (α β)
[monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
...
```
`fold_map` uses a monoid ω to accumulate a value for every element of
a data structure and `fold_map_hom` uses a monoid homomorphism to
substitute the monoid used by `fold_map`. The two are sufficient to
define `foldl`, `foldr` and `to_list`. `to_list` permits the
formulation of specifications in terms of operations on lists.
Each fold function can be defined using a specialized
monoid. `to_list` uses a free monoid represented as a list with
concatenation while `foldl` uses endofunctions together with function
composition.
The definition through monoids uses `traverse` together with the
applicative functor `const m` (where `m` is the monoid). As an
implementation, `const` guarantees that no resource is spent on
reconstructing the structure during traversal.
A special class could be defined for `foldable`, similarly to Haskell,
but the author cannot think of instances of `foldable` that are not also
`traversable`.
-/
namespace monoid
/--
For a list, foldl f x [y₀,y₁] reduces as follows
calc foldl f x [y₀,y₁]
= foldl f (f x y₀) [y₁] : rfl
... = foldl f (f (f x y₀) y₁) [] : rfl
... = f (f x y₀) y₁ : rfl
with f : α → β → α
x : α
[y₀,y₁] : list β
We can view the above as a composition of functions:
... = f (f x y₀) y₁ : rfl
... = flip f y₁ (flip f y₀ x) : rfl
... = (flip f y₁ ∘ flip f y₀) x : rfl
We can use traverse and const to construct this composition:
calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x
= const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x
... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘
((::) <$> const.mk' (flip f y₀)) ) x
... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x
... = const.run ( flip f y₁ ∘ flip f y₀ ) x
... = f (f x y₀) y₁
And this is how `const` turns a monoid into an applicative functor and
how the monoid of endofunctions define `foldl`.
-/
def foldl (α : Type u) := category_theory.End αᵒᵖ
def foldl.mk {α : Type u} (f : α → α) : foldl α := opposite.op f
def foldl.get {α : Type u} (x : foldl α) : α → α := opposite.unop x
def foldl.of_free_monoid {α : Type u} {β : Type u} (f : β → α → β) (xs : free_monoid α) : foldl β :=
opposite.op (flip (list.foldl f) xs)
def foldr (α : Type u) := category_theory.End α
def foldr.mk {α : Type u} (f : α → α) : foldr α := f
def foldr.get {α : Type u} (x : foldr α) : α → α := x
def foldr.of_free_monoid {α : Type u} {β : Type u} (f : α → β → β) (xs : free_monoid α) : foldr β :=
flip (list.foldr f) xs
def mfoldl (m : Type u → Type u) [Monad m] (α : Type u) :=
category_theory.End (category_theory.Kleisli.mk m α)ᵒᵖ
def mfoldl.mk {m : Type u → Type u} [Monad m] {α : Type u} (f : α → m α) : mfoldl m α :=
opposite.op f
def mfoldl.get {m : Type u → Type u} [Monad m] {α : Type u} (x : mfoldl m α) : α → m α :=
opposite.unop x
def mfoldl.of_free_monoid {m : Type u → Type u} [Monad m] {α : Type u} {β : Type u}
(f : β → α → m β) (xs : free_monoid α) : mfoldl m β :=
opposite.op (flip (mfoldl f) xs)
def mfoldr (m : Type u → Type u) [Monad m] (α : Type u) :=
category_theory.End (category_theory.Kleisli.mk m α)
def mfoldr.mk {m : Type u → Type u} [Monad m] {α : Type u} (f : α → m α) : mfoldr m α := f
def mfoldr.get {m : Type u → Type u} [Monad m] {α : Type u} (x : mfoldr m α) : α → m α := x
def mfoldr.of_free_monoid {m : Type u → Type u} [Monad m] {α : Type u} {β : Type u}
(f : α → β → m β) (xs : free_monoid α) : mfoldr m β :=
flip (list.mfoldr f) xs
end monoid
namespace traversable
def fold_map {t : Type u → Type u} [traversable t] {α : Type u} {ω : Type u} [HasOne ω] [Mul ω]
(f : α → ω) : t α → ω :=
traverse (functor.const.mk' ∘ f)
def foldl {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t] (f : α → β → α) (x : α)
(xs : t β) : α :=
monoid.foldl.get (fold_map (monoid.foldl.mk ∘ flip f) xs) x
def foldr {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t] (f : α → β → β) (x : β)
(xs : t α) : β :=
monoid.foldr.get (fold_map (monoid.foldr.mk ∘ f) xs) x
/--
Conceptually, `to_list` collects all the elements of a collection
in a list. This idea is formalized by
`lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`.
The definition of `to_list` is based on `foldl` and `list.cons` for
speed. It is faster than using `fold_map free_monoid.mk` because, by
using `foldl` and `list.cons`, each insertion is done in constant
time. As a consequence, `to_list` performs in linear.
On the other hand, `fold_map free_monoid.mk` creates a singleton list
around each element and concatenates all the resulting lists. In
`xs ++ ys`, concatenation takes a time proportional to `length xs`. Since
the order in which concatenation is evaluated is unspecified, nothing
prevents each element of the traversable to be appended at the end
`xs ++ [x]` which would yield a `O(n²)` run time. -/
def to_list {α : Type u} {t : Type u → Type u} [traversable t] : t α → List α :=
list.reverse ∘ foldl (flip List.cons) []
def length {α : Type u} {t : Type u → Type u} [traversable t] (xs : t α) : ℕ :=
ulift.down (foldl (fun (l : ulift ℕ) (_x : α) => ulift.up (ulift.down l + 1)) (ulift.up 0) xs)
def mfoldl {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t] {m : Type u → Type u}
[Monad m] (f : α → β → m α) (x : α) (xs : t β) : m α :=
monoid.mfoldl.get (fold_map (monoid.mfoldl.mk ∘ flip f) xs) x
def mfoldr {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t] {m : Type u → Type u}
[Monad m] (f : α → β → m β) (x : β) (xs : t α) : m β :=
monoid.mfoldr.get (fold_map (monoid.mfoldr.mk ∘ f) xs) x
def map_fold {α : Type u} {β : Type u} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] :
applicative_transformation (functor.const α) (functor.const β) :=
applicative_transformation.mk (fun (x : Type u_1) => f) sorry sorry
def free.mk {α : Type u} : α → free_monoid α := list.ret
def free.map {α : Type u} {β : Type u} (f : α → β) : free_monoid α → free_monoid β := list.map f
theorem free.map_eq_map {α : Type u} {β : Type u} (f : α → β) (xs : List α) :
f <$> xs = free.map f xs :=
rfl
protected instance free.map.is_monoid_hom {α : Type u} {β : Type u} (f : α → β) :
is_monoid_hom (free.map f) :=
is_monoid_hom.mk
(eq.mpr
(id
((fun (a a_1 : free_monoid β) (e_1 : a = a_1) (ᾰ ᾰ_1 : free_monoid β) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg Eq e_1) e_2)
(free.map f 1) []
(Eq.trans
(Eq.trans
((fun (f f_1 : α → β) (e_1 : f = f_1) (ᾰ ᾰ_1 : free_monoid α) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg free.map e_1) e_2)
f f (Eq.refl f) 1 [] free_monoid.one_def)
(congr_fun (free.map.equations._eqn_1 f) []))
(list.map.equations._eqn_1 f))
1 [] free_monoid.one_def))
(Eq.refl []))
protected instance fold_foldl {α : Type u} {β : Type u} (f : β → α → β) :
is_monoid_hom (monoid.foldl.of_free_monoid f) :=
is_monoid_hom.mk rfl
theorem foldl.unop_of_free_monoid {α : Type u} {β : Type u} (f : β → α → β) (xs : free_monoid α)
(a : β) : opposite.unop (monoid.foldl.of_free_monoid f xs) a = list.foldl f a xs :=
rfl
protected instance fold_foldr {α : Type u} {β : Type u} (f : α → β → β) :
is_monoid_hom (monoid.foldr.of_free_monoid f) :=
is_monoid_hom.mk rfl
@[simp] theorem mfoldl.unop_of_free_monoid {α : Type u} {β : Type u} (m : Type u → Type u) [Monad m]
[is_lawful_monad m] (f : β → α → m β) (xs : free_monoid α) (a : β) :
opposite.unop (monoid.mfoldl.of_free_monoid f xs) a = mfoldl f a xs :=
rfl
protected instance fold_mfoldl {α : Type u} {β : Type u} (m : Type u → Type u) [Monad m]
[is_lawful_monad m] (f : β → α → m β) : is_monoid_hom (monoid.mfoldl.of_free_monoid f) :=
is_monoid_hom.mk rfl
protected instance fold_mfoldr {α : Type u} {β : Type u} (m : Type u → Type u) [Monad m]
[is_lawful_monad m] (f : α → β → m β) : is_monoid_hom (monoid.mfoldr.of_free_monoid f) :=
is_monoid_hom.mk rfl
theorem fold_map_hom {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (g : γ → α)
(x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x :=
Eq.trans
(Eq.trans (Eq.trans rfl rfl)
(is_lawful_traversable.naturality (map_fold f) (functor.const.mk' ∘ g) x))
rfl
theorem fold_map_hom_free {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] [monoid β] (f : free_monoid α → β) [is_monoid_hom f] (x : t α) :
f (fold_map free.mk x) = fold_map (f ∘ free.mk) x :=
fold_map_hom f free.mk x
theorem fold_mfoldl_cons {α : Type u} {β : Type u} {m : Type u → Type u} [Monad m]
[is_lawful_monad m] (f : α → β → m α) (x : β) (y : α) : mfoldl f y (free.mk x) = f y x :=
sorry
theorem fold_mfoldr_cons {α : Type u} {β : Type u} {m : Type u → Type u} [Monad m]
[is_lawful_monad m] (f : β → α → m α) (x : β) (y : α) : list.mfoldr f y (free.mk x) = f x y :=
sorry
@[simp] theorem foldl.of_free_monoid_comp_free_mk {α : Type u} {β : Type u} (f : α → β → α) :
monoid.foldl.of_free_monoid f ∘ free.mk = monoid.foldl.mk ∘ flip f :=
rfl
@[simp] theorem foldr.of_free_monoid_comp_free_mk {α : Type u} {β : Type u} (f : β → α → α) :
monoid.foldr.of_free_monoid f ∘ free.mk = monoid.foldr.mk ∘ f :=
rfl
@[simp] theorem mfoldl.of_free_monoid_comp_free_mk {α : Type u} {β : Type u} {m : Type u → Type u}
[Monad m] [is_lawful_monad m] (f : α → β → m α) :
monoid.mfoldl.of_free_monoid f ∘ free.mk = monoid.mfoldl.mk ∘ flip f :=
sorry
@[simp] theorem mfoldr.of_free_monoid_comp_free_mk {α : Type u} {β : Type u} {m : Type u → Type u}
[Monad m] [is_lawful_monad m] (f : β → α → m α) :
monoid.mfoldr.of_free_monoid f ∘ free.mk = monoid.mfoldr.mk ∘ f :=
sorry
theorem to_list_spec {α : Type u} {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
(xs : t α) : to_list xs = fold_map free.mk xs :=
sorry
theorem fold_map_map {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] [monoid γ] (f : α → β) (g : β → γ) (xs : t α) :
fold_map g (f <$> xs) = fold_map (g ∘ f) xs :=
sorry
theorem foldl_to_list {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] (f : α → β → α) (xs : t β) (x : α) :
foldl f x xs = list.foldl f x (to_list xs) :=
sorry
theorem foldr_to_list {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] (f : α → β → β) (xs : t α) (x : β) :
foldr f x xs = list.foldr f x (to_list xs) :=
sorry
theorem to_list_map {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] (f : α → β) (xs : t α) : to_list (f <$> xs) = f <$> to_list xs :=
sorry
@[simp] theorem foldl_map {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u}
[traversable t] [is_lawful_traversable t] (g : β → γ) (f : α → γ → α) (a : α) (l : t β) :
foldl f a (g <$> l) = foldl (fun (x : α) (y : β) => f x (g y)) a l :=
sorry
@[simp] theorem foldr_map {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u}
[traversable t] [is_lawful_traversable t] (g : β → γ) (f : γ → α → α) (a : α) (l : t β) :
foldr f a (g <$> l) = foldr (f ∘ g) a l :=
sorry
@[simp] theorem to_list_eq_self {α : Type u} {xs : List α} : to_list xs = xs := sorry
theorem length_to_list {α : Type u} {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
{xs : t α} : length xs = list.length (to_list xs) :=
sorry
theorem mfoldl_to_list {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] {m : Type u → Type u} [Monad m] [is_lawful_monad m] {f : α → β → m α}
{x : α} {xs : t β} : mfoldl f x xs = mfoldl f x (to_list xs) :=
sorry
theorem mfoldr_to_list {α : Type u} {β : Type u} {t : Type u → Type u} [traversable t]
[is_lawful_traversable t] {m : Type u → Type u} [Monad m] [is_lawful_monad m] (f : α → β → m β)
(x : β) (xs : t α) : mfoldr f x xs = list.mfoldr f x (to_list xs) :=
sorry
@[simp] theorem mfoldl_map {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u}
[traversable t] [is_lawful_traversable t] {m : Type u → Type u} [Monad m] [is_lawful_monad m]
(g : β → γ) (f : α → γ → m α) (a : α) (l : t β) :
mfoldl f a (g <$> l) = mfoldl (fun (x : α) (y : β) => f x (g y)) a l :=
sorry
@[simp] theorem mfoldr_map {α : Type u} {β : Type u} {γ : Type u} {t : Type u → Type u}
[traversable t] [is_lawful_traversable t] {m : Type u → Type u} [Monad m] [is_lawful_monad m]
(g : β → γ) (f : γ → α → m α) (a : α) (l : t β) : mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l :=
sorry
end Mathlib |
# Conical Spirals - Supports
Given a conical (Archimedean) spiral, calculate where we could place supports. We'll assume they will be at integer intervals. If the height is 5 units, we'll want a support at 1, 2, 3 and 4. The way this works, we specify the support interval delta along the height, `Z`, of the cone and it will calculate the locations and lengths of the support struts.
# Notebook Preamble
```javascript
%%javascript
//Disable autoscroll in the output cells - needs to be in a separate cell with nothing else
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
```
<IPython.core.display.Javascript object>
```python
# decide whether charts will be displayed interactively or in a format that exports to pdf
# Interactive -----------------
# For interactive notebook uncomment:
%matplotlib notebook
# PDF -----------------
# For pdf plotting uncomment:
# %matplotlib inline
# import warnings
# warnings.filterwarnings('ignore')
%config InlineBackend.figure_formats = ['png', 'pdf'] #['svg']
#------------
# Setup matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # handle 3D plots
import matplotlib as mpl
# uncomment the following if you have more then 40 plots
# mpl.rcParams['figure.max_open_warning'] = 60
mpl.rc('font',family='monospace') # all font on the plot will be monospace
```
```python
import numpy as np
from plots import create_standard_figure, axis_legend_remove_duplicates
from common import (
plot_cone,
plot_spiral,
plot_center_pole,
calculate_support_points,
spiral_arc_length_range,
plot_cone_and_sprial,
)
```
# Support Points
We want to find the points on the curve that intersect specific elevations between $0$ and $h$. Our current model:
$$
\begin{equation} \tag{1}
\begin{matrix}
x(\theta) = b \theta \sin \theta \\
y(\theta) = b \theta \cos \theta \\
z(\theta) = z_0 + m \theta
\end{matrix}
\end{equation}
$$
The angles where the curve passes through specific elevations can be calculated with:
$$
\begin{equation} \tag{2}
\theta = \frac{z(\theta) - z_0}{m}
\end{equation}
$$
Essentially, we have to calculate the particular angles that coincide with the heights of interest. In our case, we'll simply use the integer values from $0$ to $h$.
```python
fig, ax = create_standard_figure(
'Archimedean Spiral',
'x',
'y',
'z',
projection='3d',
figsize=(8, 8),
axes_rect=(0.1, 0.1, 0.85, 0.85), # rect [left, bottom, width, height]
)
# NOTE: Units are in what every system you want as long as all length units are the same (ft, m, inches, mm)
# Cone
r = 2 # m
h = 5 # m
d = 0.25 # spacing between loops
plot_cone_and_sprial(ax, r, h, d)
# --------
# Support Points
# What is the support interval along the z-axis from [0, h)?
delta_h = 0.5
print(f'Strut Offset Height (Δh) = {delta_h}')
x, y, z = calculate_support_points(r, h, d, delta_h=delta_h)
ax.scatter(x, y, z, marker='o', color='green')
# ----------
# support struts
z0 = np.arange(0.0, h, step=delta_h)
x0 = np.zeros(z0.shape)
y0 = np.zeros(z0.shape)
support_start = np.vstack([x0, y0, z0])
support_end = np.vstack([x, y, z])
# print('=====')
# print(support_start)
# print()
# print(support_end)
# print('---')
# interleave the matrices by column
full = np.empty((support_start.shape[0], support_start.shape[1]*2))
full[:, 0::2] = support_start
full[:, 1::2] = support_end
# print(full)
# print('-------')
print('------')
# Display the support struts and print their lengths out
for line in np.hsplit(full, full.shape[1]/2):
p1 = line[:,0]
p2 = line[:,1]
length = np.linalg.norm(p2 - p1)
print(f'Support Length (@ Z={p1[2]}) = {length:.2f}')
ax.plot(*line, '-', color='black', linewidth=1.75)
# -----------
# ax.legend(
# handles=[cone_handle, spiral_handle],
# labels=[f'Cone r={r:.2f} h={h:.2f}', f'Spiral d={d:.2f} length={al:.2f}'],
# loc='best',
# shadow=True,
# fancybox=True,
# prop={'family': 'monospace', 'size':12},
# frameon=True,
# )
# ax.view_init(elev=0, azim=45)
fig.show()
```
<IPython.core.display.Javascript object>
Cone Radius (r) = 2.0000
Cone Height (h) = 5.0000
Sprial Distance (d) = 0.2500
Strut Offset Height (Δh) = 0.5
------
Support Length (@ Z=0.0) = 2.00
Support Length (@ Z=0.5) = 1.80
Support Length (@ Z=1.0) = 1.60
Support Length (@ Z=1.5) = 1.40
Support Length (@ Z=2.0) = 1.20
Support Length (@ Z=2.5) = 1.00
Support Length (@ Z=3.0) = 0.80
Support Length (@ Z=3.5) = 0.60
Support Length (@ Z=4.0) = 0.40
Support Length (@ Z=4.5) = 0.20
The result is quite nice. The support points are calculated at specific `Z` values and the lengths of the support strut are calculated and plotted.
## Future
We could potentially add the model to allow use to place supports at reqular angles instead of regular elevations. For example, we could add supports at the regular angles (0, pi/2, pi, 3pi/2 + ...). This would mean that we would trace the curve and put supports on the north, east, south and west sides. This might be easier.
|
{-# OPTIONS --universe-polymorphism --no-irrelevant-projections --without-K #-}
module SafeFlagSafePragmas where
|
[STATEMENT]
lemma full_Suc_Node2_iff [simp]:
"full (Suc n) (Node2 l p r) \<longleftrightarrow> full n l \<and> full n r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. full (Suc n) \<langle>l, p, r\<rangle> = (full n l \<and> full n r)
[PROOF STEP]
by (auto elim: full_elims intro: full.intros) |
function c8_atan_test ( )
%*****************************************************************************80
%
%% C8_ATAN_TEST tests C8_ATAN.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 11 February 2015
%
% Author:
%
% John Burkardt
%
seed = 123456678;
fprintf ( 1, '\n' );
fprintf ( 1, 'C8_ATAN_TEST\n' );
fprintf ( 1, ' C8_ATAN computes the inverse tangent of a C8.\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ...
' C1=C8_UNIFORM_01 C2 = C8_ATAN(C1) C3 = C8_TAN(C2)\n' );
fprintf ( 1, ' --------------------- --------------------- ---------------------\n' );
fprintf ( 1, '\n' );
for test = 1 : 10
[ c1, seed ] = c8_uniform_01 ( seed );
c2 = c8_atan ( c1 );
c3 = c8_tan ( c2 );
fprintf ( 1, ' (%12f %12f) (%12f %12f) (%12f %12f)\n', ...
real ( c1 ), imag ( c1 ), real ( c2 ), imag ( c2 ), real ( c3 ), imag ( c3 ) );
end
return
end
|
import os
import urllib
import traceback
import time
import sys
import numpy as np
import cv2
from rknn.api import RKNN
RKNN_MODEL = 'yolox.rknn'
rknn = RKNN()
rknn.config(mean_values=[123.675, 116.28, 103.53], std_values=[58.82, 58.82, 58.82])
ret = rknn.build(do_quantization=True, dataset='./dataset.txt')
img = cv2.imread('/home/white/PycharmProjects/yolox-pytorch-main/1716/VOCdevkitmon/VOC2007/JPEGImages/001182.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
ret = rknn.init_runtime()
print(ret)
outputs = rknn.inference(inputs=[img])
print(outputs.shape) |
theory bin_times_assoc
imports Main
"$HIPSTER_HOME/IsaHipster"
begin
datatype Bin = One | ZeroAnd "Bin" | OneAnd "Bin"
fun s :: "Bin => Bin" where
"s (One) = ZeroAnd One"
| "s (ZeroAnd xs) = OneAnd xs"
| "s (OneAnd ys) = ZeroAnd (s ys)"
fun plus :: "Bin => Bin => Bin" where
"plus (One) y = s y"
| "plus (ZeroAnd z) (One) = s (ZeroAnd z)"
| "plus (ZeroAnd z) (ZeroAnd ys) = ZeroAnd (plus z ys)"
| "plus (ZeroAnd z) (OneAnd xs) = OneAnd (plus z xs)"
| "plus (OneAnd x2) (One) = s (OneAnd x2)"
| "plus (OneAnd x2) (ZeroAnd zs) = OneAnd (plus x2 zs)"
| "plus (OneAnd x2) (OneAnd ys2) = ZeroAnd (s (plus x2 ys2))"
fun times :: "Bin => Bin => Bin" where
"times (One) y = y"
| "times (ZeroAnd xs) y = ZeroAnd (times xs y)"
| "times (OneAnd ys) y = plus (ZeroAnd (times ys y)) y"
(*hipster s plus times *)
theorem x0 :
"!! (x :: Bin) (y :: Bin) (z :: Bin) .
(times x (times y z)) = (times (times x y) z)"
by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>)
end
|
/-
Copyright (c) 2021 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hanting Zhang
! This file was ported from Lean 3 source module data.real.pi.wallis
! leanprover-community/mathlib commit 980755c33b9168bc82f774f665eaa27878140fac
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Analysis.SpecialFunctions.Integrals
/-! # The Wallis formula for Pi
This file establishes the Wallis product for `π` (`real.tendsto_prod_pi_div_two`). Our proof is
largely about analyzing the behaviour of the sequence `∫ x in 0..π, sin x ^ n` as `n → ∞`.
See: https://en.wikipedia.org/wiki/Wallis_product
The proof can be broken down into two pieces. The first step (carried out in
`analysis.special_functions.integrals`) is to use repeated integration by parts to obtain an
explicit formula for this integral, which is rational if `n` is odd and a rational multiple of `π`
if `n` is even.
The second step, carried out here, is to estimate the ratio
`∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that
it converges to one using the squeeze theorem. The final product for `π` is obtained after some
algebraic manipulation.
## Main statements
* `real.wallis.W`: the product of the first `k` terms in Wallis' formula for `π`.
* `real.wallis.W_eq_integral_sin_pow_div_integral_sin_pow`: express `W n` as a ratio of integrals.
* `real.wallis.W_le` and `real.wallis.le_W`: upper and lower bounds for `W n`.
* `real.tendsto_prod_pi_div_two`: the Wallis product formula.
-/
open Real Topology BigOperators Nat
open Filter Finset intervalIntegral
namespace Real
namespace Wallis
/-- The product of the first `k` terms in Wallis' formula for `π`. -/
noncomputable def w (k : ℕ) : ℝ :=
∏ i in range k, (2 * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3))
#align real.wallis.W Real.Wallis.w
theorem w_succ (k : ℕ) :
w (k + 1) = w k * ((2 * k + 2) / (2 * k + 1) * ((2 * k + 2) / (2 * k + 3))) :=
prod_range_succ _ _
#align real.wallis.W_succ Real.Wallis.w_succ
theorem w_pos (k : ℕ) : 0 < w k := by
induction' k with k hk
· unfold W
simp
· rw [W_succ]
refine' mul_pos hk (mul_pos (div_pos _ _) (div_pos _ _)) <;> positivity
#align real.wallis.W_pos Real.Wallis.w_pos
theorem w_eq_factorial_ratio (n : ℕ) : w n = 2 ^ (4 * n) * n ! ^ 4 / ((2 * n)! ^ 2 * (2 * n + 1)) :=
by
induction' n with n IH
·
simp only [W, prod_range_zero, Nat.factorial_zero, MulZeroClass.mul_zero, pow_zero,
algebraMap.coe_one, one_pow, mul_one, algebraMap.coe_zero, zero_add, div_self, Ne.def,
one_ne_zero, not_false_iff]
· unfold W at IH⊢
rw [prod_range_succ, IH, _root_.div_mul_div_comm, _root_.div_mul_div_comm]
refine' (div_eq_div_iff _ _).mpr _
any_goals exact ne_of_gt (by positivity)
simp_rw [Nat.mul_succ, Nat.factorial_succ, pow_succ]
push_cast
ring_nf
#align real.wallis.W_eq_factorial_ratio Real.Wallis.w_eq_factorial_ratio
theorem w_eq_integral_sin_pow_div_integral_sin_pow (k : ℕ) :
(π / 2)⁻¹ * w k = (∫ x : ℝ in 0 ..π, sin x ^ (2 * k + 1)) / ∫ x : ℝ in 0 ..π, sin x ^ (2 * k) :=
by
rw [integral_sin_pow_even, integral_sin_pow_odd, mul_div_mul_comm, ← prod_div_distrib, inv_div]
simp_rw [div_div_div_comm, div_div_eq_mul_div, mul_div_assoc]
rfl
#align real.wallis.W_eq_integral_sin_pow_div_integral_sin_pow Real.Wallis.w_eq_integral_sin_pow_div_integral_sin_pow
theorem w_le (k : ℕ) : w k ≤ π / 2 :=
by
rw [← div_le_one pi_div_two_pos, div_eq_inv_mul]
rw [W_eq_integral_sin_pow_div_integral_sin_pow, div_le_one (integral_sin_pow_pos _)]
apply integral_sin_pow_succ_le
#align real.wallis.W_le Real.Wallis.w_le
theorem le_w (k : ℕ) : ((2 : ℝ) * k + 1) / (2 * k + 2) * (π / 2) ≤ w k :=
by
rw [← le_div_iff pi_div_two_pos, div_eq_inv_mul (W k) _]
rw [W_eq_integral_sin_pow_div_integral_sin_pow, le_div_iff (integral_sin_pow_pos _)]
convert integral_sin_pow_succ_le (2 * k + 1)
rw [integral_sin_pow (2 * k)]
simp only [sin_zero, zero_pow', Ne.def, Nat.succ_ne_zero, not_false_iff, MulZeroClass.zero_mul,
sin_pi, tsub_zero, Nat.cast_mul, Nat.cast_bit0, algebraMap.coe_one, zero_div, zero_add]
#align real.wallis.le_W Real.Wallis.le_w
theorem tendsto_w_nhds_pi_div_two : Tendsto w atTop (𝓝 <| π / 2) :=
by
refine' tendsto_of_tendsto_of_tendsto_of_le_of_le _ tendsto_const_nhds le_W W_le
have : 𝓝 (π / 2) = 𝓝 ((1 - 0) * (π / 2)) := by rw [sub_zero, one_mul]
rw [this]
refine' tendsto.mul _ tendsto_const_nhds
have h : ∀ n : ℕ, ((2 : ℝ) * n + 1) / (2 * n + 2) = 1 - 1 / (2 * n + 2) :=
by
intro n
rw [sub_div' _ _ _
(ne_of_gt
(add_pos_of_nonneg_of_pos (mul_nonneg (two_pos : 0 < (2 : ℝ)).le (Nat.cast_nonneg _))
two_pos)),
one_mul]
congr 1
ring
simp_rw [h]
refine' (tendsto_const_nhds.div_at_top _).const_sub _
refine' tendsto.at_top_add _ tendsto_const_nhds
exact tendsto_coe_nat_at_top_at_top.const_mul_at_top two_pos
#align real.wallis.tendsto_W_nhds_pi_div_two Real.Wallis.tendsto_w_nhds_pi_div_two
end Wallis
end Real
/-- Wallis' product formula for `π / 2`. -/
theorem Real.tendsto_prod_pi_div_two :
Tendsto (fun k => ∏ i in range k, ((2 : ℝ) * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3)))
atTop (𝓝 (π / 2)) :=
Real.Wallis.tendsto_w_nhds_pi_div_two
#align real.tendsto_prod_pi_div_two Real.tendsto_prod_pi_div_two
|
import Mathlib.Combinatorics.SimpleGraph.Coloring
import Mathlib.Tactic.LibrarySearch
universe u w
open SimpleGraph Hom Iso Embedding
variable {V : Type u} {G : SimpleGraph V} {α : Type v}
def closedNbhdSubgraph (v : V) : SimpleGraph {w | G.Adj v w ∨ w = v} where
Adj := fun w₁ w₂ => G.Adj w₁ w₂ ∧ (w₁ = v ∨ w₂ = v)
symm := by
intro v₁ v₂ h
constructor
· apply G.symm <| h.left
· match h.right with
| .inl h => exact .inr h
| .inr h => exact .inl h
def AdjacentAt (v : V) (e₁ e₂ : edgeSet G) : Prop := Sym2.Mem v e₁ ∧ Sym2.Mem v e₂
theorem AdjacentAt.symm {v : V} {e₁ e₂ : edgeSet G} (h : AdjacentAt v e₁ e₂) : AdjacentAt v e₂ e₁ := ⟨h.right, h.left⟩
def Adjacent (e₁ e₂ : edgeSet G) : Prop := ∃ v, AdjacentAt v e₁ e₂
@[symm, aesop unsafe 10% apply (rule_sets [SimpleGraph])]
theorem Adjacent.symm {e₁ e₂ : edgeSet G} (h : Adjacent e₁ e₂) : Adjacent e₂ e₁ := by
obtain ⟨w,h'⟩ := h
exact ⟨w,AdjacentAt.symm h'⟩
def lineGraph (G : SimpleGraph V) : SimpleGraph (edgeSet G) where
Adj := fun e₁ e₂ => Adjacent e₁ e₂ ∧ e₁ ≠ e₂
variable (G)
abbrev EdgeColoring (α : Type v) := Coloring (lineGraph G) α
theorem EdgeColoring.valid {α : Type v} (G : SimpleGraph V)
(c : EdgeColoring G α) {e₁ e₂ : edgeSet G} (h : e₁ ≠ e₂)
(adj : Adjacent e₁ e₂ ) : c e₁ ≠ c e₂ :=
Coloring.valid c ⟨adj,h⟩
noncomputable def edgeChromaticNumber : ℕ := chromaticNumber (lineGraph G)
variable (v : V) [Fintype (neighborSet G v)]
open Fintype Finset
def edgeSpan : Set (edgeSet G) := fun e => Sym2.Mem v e
instance : Fintype (edgeSpan G v) := sorry
theorem something : edgeSpan G v = (edgeSpan G v).toFinset := sorry
#check edgeSet
def neighborSettoEdge (v' : neighborSet G v) : Sym2 V := ⟦(v,v')⟧
#print Subtype
noncomputable def neighborSetedgeSpanEquiv : (neighborSet G v) ≃ (edgeSpan G v) where
toFun := fun ⟨v',hv'⟩ => by
refine ⟨⟨⟦(v,v')⟧,hv'⟩,?_⟩
· change v ∈ Quotient.mk (Sym2.Rel.setoid V) (v, ↑v')
rw [Sym2.mem_iff]
exact Or.inl rfl
invFun := fun ⟨⟨e,he⟩,he'⟩ => by
refine ⟨Sym2.Mem.other he',?_⟩
dsimp [neighborSet]
rw [←mem_edgeSet,Sym2.other_spec he']
exact he
left_inv := fun v' => by sorry
right_inv := sorry
example (W : Type) (s : Set W) [Fintype s] : Finset W := s.toFinset
-- @Finset.map s W ⟨(↑),Subtype.coe_injective⟩ elems
theorem edgeSpan_isClique : IsClique (lineGraph G) <| edgeSpan G v := fun _ he₁ _ he₂ ne => ⟨⟨v,⟨he₁,he₂⟩⟩,ne⟩
#check IsClique.card_le_of_coloring
theorem degree_le_edgeColoring [Fintype α] (c : EdgeColoring G α) : G.degree v ≤ Fintype.card α := by
change (neighborFinset G v).card ≤ Fintype.card α
-- have : (edgeSpan G v).toFinset = neighborFinset G v := sorry
-- refine @IsClique.card_le_of_coloring (edgeSet G) (lineGraph G) α (edgeSpan G v).toFinset ?_ _ ?_
--
sorry
-- apply IsClique.card_le_of_coloring (G := lineGraph G)
-- · exact edgeSpan_isClique G v
-- · sorry
def restrictedColoring (c : EdgeColoring G α) : G.neighborSet v → α := sorry
theorem ge_degree_of_coloring (n : ℕ) (c : EdgeColoring G (Fin n)) :
n ≥ G.degree v := by
by_contra h
sorry
theorem ge_degree_of_colorable (n : ℕ) (h : G.Colorable n) :
n ≥ G.degree v := sorry
theorem edgeChromaticNumber_ge_degree :
edgeChromaticNumber G ≥ G.degree v := by
sorry
|
#writeList------------------------------2009-02-05
# Writes a list to a file in "D" or "P" format.
# Arguments:
# x - list to save
# fname - file to write list to
# format - write list in "D" or "P" format
# comments - include string as comment at the top of file
#-------------------------------------------ACB/RH
writeList <- function(x, fname="", format="D", comments="") {
NoComments<-missing(comments)
comments <- sub("^", "#", comments)
if (format=="D") {
dput(x, fname)
if (file.exists(fname) && !NoComments) {
output <- scan(fname, what=character(0), sep="\n")
output <- paste(output, collapse="\n")
sink(fname)
on.exit(expr=sink());
#add comments
if (any(comments!="#")) {
cat(paste(comments, collapse="\n"));
cat("\n");
}
#spit out original output from dput
cat(output)
cat("\n")
}
return(fname)
}
if (format=="P") {
if (!is.list(x) || length(x) == 0)
stop("x must be a non-empty list.")
.writeList.P(x, fname, comments)
return(fname)
}
stop(paste("format \"",format,"\" not recognized."))
}
#----------------------------------------writeList
#.writeList.P---------------------------2009-02-10
# Saves list x to disk using "P" format
#-------------------------------------------ACB/RH
.writeList.P <- function( x, fname="", comments, prefix="") {
if (fname!="") {
sink(fname)
on.exit(expr=sink())
}
if (!missing(comments)) {
cat(paste(comments,collapse="\n")); cat("\n")
}
# check for list elements that are missing names
xNames=names(x)
if (is.null (xNames))
# names(x) returns NULL if no names are set
xNames <- names(x) <- paste("X",1:length(x),sep="")
else {
# assign X# names for NA/"" cases
z <- is.na(xNames) | is.element(xNames,"")
if (any(z))
xNames[z] <- names(x)[z] <- paste("X",1:sum(z),sep="")
}
#check for errors
for(i in 1:length(x)) {
dat=x[[i]]
# note if a list (A) contains a list (B), is.vector will return
# true for (B)
if (!is.vector(dat) && !is.matrix(dat) && class(dat)!="data.frame") next
#prepare character strings with quotes if spaces exist
if (is.character(dat) && length(dat)>0) {
for(j in 1:length(dat)) {
#only strings with spaces need quotes
if (typeof(dat[j])=="character") {
x[[i]][j] <- .addslashes(dat[j])
}
}
}
}
#start cat-ing keys and values
for(i in 1:length(x)) {
if (prefix != "")
nam=paste(prefix, xNames[i], sep="$")
else
nam=xNames[i]
dat=x[[i]]
if (!is.vector(dat) && !is.matrix(dat) && class(dat)!="data.frame"
&& !is.array(dat))
next
#print varName
cat(paste("$", nam, "\n", sep=""))
# we must handle lists first because is.vector returns true for
# a list
if (class(dat) == "list") {
#list within the list
.writeList.P (dat, fname="", prefix=nam)
}
else if (is.vector(dat)) {
#print names
vecNames<-names(dat)
if (is.null(vecNames)) vecNames=""
vecNames <- .addslashes(vecNames)
cat(paste("$$vector mode=\"", typeof(dat), "\" names=", vecNames, "\n", sep=""))
cat(dat); cat("\n")
}
else if( is.matrix( dat ) ) {
#print colnames
matColNames <- colnames( dat )
matRowNames <- rownames( dat )
if (is.null(matColNames))
matColNames <- ""
if (is.null(matRowNames))
matRowNames <- ""
matColNames <- .addslashes(matColNames)
matRowNames <- .addslashes(matRowNames)
cat(paste("$$matrix mode=\"", typeof( dat ), "\" rownames=", matRowNames, " colnames=", matColNames, " ncol=", ncol( dat ), "\n", sep=""))
for(j in 1:dim(x[[i]])[1]) {
cat(dat[j,]); cat("\n")
}
}
else if ( is.array(dat) ) {
d=dim(dat); nr=d[1]; nc=d[2]; nd=length(d) # dimension info
#get the dimensional names
dim_names_flat <- c() #single dimension vector
dim_names <- dimnames( dat ) #note: dimnames may also have a names attribute
if( is.null( dim_names ) ) {
dim_names_flat <- ""
} else {
#ensure a name exists, assign an index value otherwise
if( is.null( names( dim_names ) ) )
names( dim_names ) <- 1:length(dim_names)
#flatten into a vector c( 1st_dimname, 1st_dim_element_1, 2, ... n, 2nd_dimname, ... )
for( i in 1:length(dim_names) )
dim_names_flat <- c( dim_names_flat, names(dim_names)[i], dim_names[[i]] )
}
dim_names_flat <- .addslashes( dim_names_flat )
cat(paste("$$array mode=\"", typeof(dat), "\" dim=",.addslashes(d)," byright=FALSE",
" byrow=TRUE dimnames=", dim_names_flat, "\n", sep=""))
dhi=d[3:nd]; nhi=length(dhi) # extra dimensions above 2
idx=1:nhi; index=letters[10+(idx)]
ex1=paste(paste("for(",rev(index)," in 1:",dhi[rev(idx)],"){",sep=""),collapse=" ")
ex2="for(j in 1:nr){"
ex3=paste("cat(dat[j,,",paste(index,collapse=","),"]); cat(\"\\n\")",sep="")
ex4=paste(rep("}",nhi+1),collapse="")
expr=paste(ex1,ex2,ex3,ex4,collapse=" ")
eval(parse(text=expr))
}
else if (class(dat)=="data.frame") {
cat("$$data ");
#ncol
cat("ncol="); cat(dim(dat)[2]); cat(" ");
#modes
cat("modes=\"")
for (j in 1:length(dat)) {
if (j>1) cat(" ")
cat(typeof(dat[[j]])) }
cat("\" ")
#rownames
cat("rownames="); cat(.addslashes(rownames(dat))); cat(" ")
#colnames
cat("colnames="); cat(.addslashes(colnames(dat))); cat(" ")
#byrow
cat("byrow=TRUE"); cat("\n")
for(j in 1:dim(dat)[1]) {
for(k in 1:dim(dat)[2]) {
cat(dat[j,k]); cat(" ") }
cat("\n") }
}
}
}
#-------------------------------------.writeList.P
#readList-------------------------------2008-07-14
# Returns a list in either "D" or "P" format read from disk.
# Arguments:
# fname - file to read
# Change (Anisa Egeli): There is a check to see if the file exists.
# This allows try(readList(...), silent=TRUE) to catch the error.
#-------------------------------------------ACB/AE
readList <- function(fname) {
if(!file.exists(fname))
stop(paste("File", fname, "does not exist."))
#detect file type
f <- scan(fname, what=character(), sep="\n", quiet=TRUE)
for(i in 1:length(f)) {
if (!any(grep("^[ \t]*#", f[i]))) {
if (any(grep("^[ \t]*structure", f[i]))) fileformat <- "D"
else if (any(grep("^[ \t]*list", f[i]))) fileformat <- "R"
else if (any(grep("^[ \t]*\\$", f[i]))) fileformat <- "P"
else stop("unknown fileformat detected.")
break;
}
}
if (fileformat == "R" || fileformat == "D")
return(eval(parse(fname)))
if (fileformat == "P")
return(.readList.P(fname))
}
#-----------------------------------------readList
#.readList.P----------------------------2009-02-05
# Read list in "P" format.
#----------------------------------------ACB/AE/RH
.readList.P <- function(fname) {
#srcfile will be modified, orgfile is untouched and only used for user debug error messages
srcfile=orgfile=scan(fname, what=character(), sep="\n", quiet=TRUE, blank.lines.skip=FALSE)
data=list(); j=0; halt=FALSE; str=""
extendLine <- FALSE #used for extending a single line into lines with \
extendLineNumber <- 0 #where a new widget starts - used for error messages
if (!length(srcfile)) {stop("Input file is empty\n")}
#print("loop start"); print(date());
#if comments were striped out earlier, we would lose the line count.
for(i in 1:length(srcfile)) {
if (!any(grep("^[[:space:]]*(#.*)?$", srcfile[i]))) {
# srcfile[i] <- .stripComments(srcfile[i])
#append last string onto new string if applicable
if (extendLine == TRUE)
str <- paste(str, srcfile[i], sep=" ")
else {
str <- srcfile[i]
extendLineNumber <- i
}
#determine if this string is extended by a \ at the end.
tmp <- sub('\\\\$', '', str)
if (tmp==str) #no sub took place
extendLine = FALSE
else
extendLine = TRUE
str <- tmp
#parse the line once it is complete (no \)
if (extendLine == FALSE) {
j <- j + 1
data[[j]]<-list(str=str, line.start=extendLineNumber, line.end=i)
}
}
}
#convert the "data" list into a real list
varName=varOptions=NULL
varData=retData=list() #list to return
for(i in 1:length(data)) {
str <- data[[i]]$str
#varOptions (optional)
if (substr(str,1,2)=="$$") {
if (!is.null(varOptions))
stop("extra $$ line found")
if (is.null(varName))
stop("$$ line found before $ line")
varOptions <-data[[i]]
varOptions$str = substr(varOptions$str, 3, nchar(varOptions$str)) #remove $$
}
#varName
else if (substr(str,1,1)=="$") {
if (!is.null(varName)) {
#save data into the retData list
listelem <- paste("retData", paste("[[\"", paste(strsplit (varName, "\\$")[[1]], collapse="\"]][[\""), "\"]]", sep=""), sep="")
savedata <- paste(listelem, " <- .readList.P.convertData(varOptions, varData, fname, orgfile)", sep="")
eval(parse(text=savedata))
if (is.null(eval(parse(text=listelem)))) halt<-TRUE
varName <- varOptions <- NULL
varData <- list()
}
# varName <- .trimWhiteSpace(substr(str, 2, nchar(str)))
varName <- (substr(str, 2, nchar(str)))
if (!any(grep("^[a-zA-Z0-9_.$ ]+$", varName))) {
.catError(
paste("Variable name \"", varName,"\" is not valid", sep=""), fname,
data[[i]]$line.start, data[[i]]$line.end,
orgfile, "readList error"
)
halt<-TRUE
}
line.start <- data[[i]]$line.start
}
else {
varData[[length(varData)+1]] <-data[[i]]
}
}
#save anything from after
if (!is.null(varName)) {
listelem <- paste("retData", paste("[[\"", paste(strsplit(varName, "\\$")[[1]], collapse="\"]][[\""), "\"]]", sep=""), sep="")
savedata <- paste(listelem, " <- .readList.P.convertData(varOptions, varData, fname, orgfile)", sep="")
eval(parse(text=savedata))
if (is.null(eval(parse(text=listelem)))) halt<-TRUE
}
if (halt) {stop("Errors were found in the file. Unable to continue\n")}
return(retData)
}
#--------------------------------------.readList.P
#.readList.P.convertData----------------2008-03-05
# Helper function to convert data into proper mode.
#-------------------------------------------ACB/RH
.readList.P.convertData <- function(varOptions, varData, fname="", sourcefile=list()) {
if (is.null(varOptions)) {
#simple format with no options
if (length(varData)==0) return(varData)
else if (length(varData)==1) {
#just a vector
return(.autoConvertMode(.convertParamStrToVector(varData[[1]]$str, fname, varData[[1]]$line.start)))
}
else {
#some sort of matrix to parse
dimSize <- c(length(varData),0) #num of rows
matData <- c() #vector to hold values byrow
for(i in 1:length(varData)) {
tmp <- .convertParamStrToVector(varData[[i]]$str, fname, varData[[i]]$line.start)
if (dimSize[2]==0)
dimSize[2] <- length(tmp)
else if (length(tmp)!=dimSize[2]) {
.catError(paste("Matrix row (line ",varData[[i]]$line.start,") lenght should match first row (line ",varData[[1]]$line.start,") length of ", dimSize[2], sep=""), fname,
varData[[i]]$line.start, varData[[i]]$line.end,
sourcefile, "readList error")
return(NULL)
}
matData <- append(matData, tmp)
}
matData <- .autoConvertMode(matData)
return(matrix(matData, dimSize[1], dimSize[2], byrow=TRUE))
}
}
#otherwise varOptions was given (in string format)
#convert it into a list first
opts <-.getParamFromStr(varOptions$str, fname, varOptions$line.start, varOptions$line.end, sourcefile, .pFormatDefs)
if (is.null(opts)) stop("Errors were detected")
if (length(varData)==0) return(eval(parse(text=paste(opts$mode,"()",sep="")))) # return empty typeof
#flatten all data into a vector (of characters)
x <- c()
for(i in 1:length(varData)) {
#weird things happen if its x[i] <- as.vector(.convert...)
x <- c(x, .convertParamStrToVector(varData[[i]]$str, fname, varData[[i]]$line.start))
}
if(opts$type=="vector") {
x <- .forceMode(x, opts$mode)
if (any(opts$names!="")) {
names(x)<-opts$names
}
return(x)
}
else if(opts$type=="matrix") {
x <- .forceMode(x, opts$mode)
#calculate dims
nrow <- length(x)/opts$ncol
if (as.integer(nrow)!=nrow) {
.catError(paste("Matrix data length [", length(x), "] is not a sub-multiple of ncol [", opts$ncol, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
#convert to matrix
mat <- matrix(x, nrow, opts$ncol, byrow=opts$byrow)
#add colnames
if (any(opts$colnames!="")) {
if (length(opts$colnames)!=opts$ncol) {
.catError(paste("Matrix colnames length [", length(opts$colnames), "] is not equal to ncol [", opts$ncol, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
colnames(mat)<-opts$colnames
}
#add rownames
if (any(opts$rownames!="")) {
if (length(opts$rownames)!=nrow) {
.catError(paste("Matrix rownames length [", length(opts$rownames), "] is not equal to nrow [", nrow, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
rownames(mat)<-opts$rownames
}
return(mat)
}
else if(opts$type=="array") {
x <- .forceMode(x, opts$mode)
opts$dim <- .convertMode(opts$dim, "numeric")
if (any(is.na(opts$dim))) {
.catError("dim values must be numeric", fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
#check dims works
if (length(x)!=prod(opts$dim)) {
.catError(paste("dim [product ",prod(opts$dim),"] do not match the length of object [",length(x),"]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
x=.convertVecToArray(x,opts$dim,byright=opts$byright,byrow=opts$byrow)
if( all( opts$dimnames == "" ) )
return( x )
#restore dimnames
# example: dimnames(Titanic) -> there are 4 dimensions (class, sex, age, survived)
# these dimensions have different number of names: i.e. Sex has two: male, female
# dimnames contains first the name of the element "sex", followed by the labels for the each dimension
# "male", "female". dim(Titanic)[2] tells us sex only has two labels, so the next label is a dimension name
# ex: dimnames="Class 1st 2nd 3rd Crew Sex Male Female Age Child Adult Survived No Yes" dim="4 2 2 2"
dim_name_dimensions <- length( opts$dim )
dim_names <- list()
for( i in 1:dim_name_dimensions ) {
#j points to name of the dimension
if( i == 1 )
j <- 1
else
j <- sum( opts$dim[ 1:(i-1) ] + 1 ) + 1
#dim_name_elements are the element names for a particular dimension
dim_name_elements <- ( j + 1 ) : ( j + opts$dim[ i ] )
dim_names[[ i ]] <- opts$dimnames[ dim_name_elements ]
names( dim_names )[ i ] <- opts$dimnames[ j ]
}
dimnames( x ) <- dim_names
return(x)
}
else if(opts$type=="data") {
#check ncol works
if (length(x)%%opts$ncol>0) {
.catError(paste("dataframe data length [", length(x), "] is not a sub-multiple of ncol [", opts$ncol, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
if (opts$ncol != length(opts$colnames)) {
.catError(paste("Data colnames length [", length(opts$colnames), "] is not equal to ncol [", opts$ncol, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
if (opts$ncol != length(opts$modes)) {
.catError(paste("Data modes length [", length(opts$modes), "] is not equal to ncol [", opts$ncol, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
#calculate nrow
nrow <- length(x)/opts$ncol
#break up data into a vector of a list, such that each element represents a column
dataCols <- list()
if (opts$byrow) {
for(i in 1:length(x)) {
j <- i%%opts$ncol
if (j==0)
j <- opts$ncol
if (length(dataCols)<j)
dataCols[[j]] <- x[i]
else
dataCols[[j]] <- c(dataCols[[j]], x[i])
}
}
else {
for(i in 1:length(x)) {
j <- as.integer((i-1)/(length(x)/opts$ncol))+1
if (length(dataCols)<j)
dataCols[[j]] <- x[i]
else
dataCols[[j]] <- c(dataCols[[j]], x[i])
}
}
#create data.frame and use colnames to refer to each colum
#the data.frame will be stored as 'ret'
txt <- "ret <- data.frame("
for(i in 1:opts$ncol) { #for each column
#convert into propper mode
dataCols[[i]] <- .convertMode(dataCols[[i]], opts$modes[i])
if (i>1)
txt <- paste(txt, ", ", sep="")
name <- opts$colnames[i]
txt <- paste(txt, name, "=dataCols[[", i, "]]", sep="")
}
txt <- paste(txt, ")", sep="")
eval(parse(text=txt))
#add rownames if any exist
if (any(opts$rownames!="")) {
if (length(opts$rownames)!=nrow) {
.catError(paste("Data rownames length [", length(opts$rownames), "] is not equal to nrow [", nrow, "]", sep=""), fname,
varOptions$line.start, varData[[length(varData)]]$line.end,
sourcefile, "readList error")
return(NULL)
}
rownames(ret)<-opts$rownames
}
return(ret)
}
}
#--------------------------.readList.P.convertData
#unpackList-----------------------------2012-12-06
# Make local/global variables from the components of a named list.
#-------------------------------------------ACB/RH
unpackList <- function(x, scope="L") {
namx <- names(x); nx <- length(namx);
if (nx > 0) for (i in 1:nx) {
if (namx[i] != "") {
if (scope=="L")
assign(namx[i], x[[i]], pos=parent.frame(1))
else if (scope=="P")
assign(namx[i], x[[i]], envir = .PBSmodEnv)
else if (scope=="G")
eval(parse(text="assign(namx[i], x[[i]], envir = .GlobalEnv)"))
}
}
namx[namx != ""]
}
#---------------------------------------unpackList
#packList-------------------------------2013-07-16
# Pack a list in target environment with existing
# objects from parent or user-specified environment.
# NOTE:-------------
# New 'packList' takes advantage of the accessor functions:
# 'tget', 'tcall', and 'tput'.
# Less complicated than former 'packList' (temporarily
# available as '.packList.deprecated'), and should be way faster.
#-----------------------------------------------RH
packList=function(stuff, target="PBSlist", value, penv=NULL, tenv=.PBSmodEnv)
{
if (is.null(penv)) penv = parent.frame() # for a parent envir, need to call this inside the function NOT as an argument
if (!is.vector(stuff) || !is.character(stuff))
showAlert("Provide a vector of names denoting objects")
target = as.character(substitute(target))
if (target %in% lisp(envir=tenv))
eval(parse(text=paste("tget(",target,",tenv=tenv)",sep="")))
else
eval(parse(text=paste(target,"=list()")))
if (!missing(value)) {# use explicit value instead of objects
eval(parse(text=paste(target,"[[\"",stuff,"\"]] = ",paste(deparse(value),collapse="\n"),sep="")))
} else {
for (i in stuff)
eval(parse(text=paste(target,"[[\"",i,"\"]] = tcall(",i,",tenv=penv)",sep="")))
}
eval(parse(text=paste("tput(",target,",tenv=tenv)",sep="")))
invisible()
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~packList
#lisp-----------------------------------2012-12-12
lisp = function(name, pos=.PBSmodEnv, envir=as.environment(pos), all.names=TRUE, pattern){
ls(name,pos,envir,all.names,pattern)
}
#---------------------------------------------lisp
#.packList.deprecated-------------------2012-12-03
# Pack a list with (i) existing objects using their
# names or (ii) one explicit value.
#-----------------------------------------------RH
.packList.deprecated=function(stuff, target="PBSlist", value, tenv=.PBSmodEnv)
{
penv = parent.frame() # need to call this inside the function NOT as an argument
# Deparse bad objects: those that break code (see function 'deparse')
deparseBO = function(x){
if (is.list(x) && !is.data.frame(x)) {
sapply(x,function(x){deparseBO(x)},simplify=FALSE) # recursion through lists within lists
} else {
xclass=class(x)
if (mode(x) %in% c("call","expression","(","function","NULL"))
x=paste(deparse(x),collapse="")
class(x)=xclass
return(x)
}
}
if (!is.vector(stuff) || !is.character(stuff))
showAlert("Provide a vector of names denoting objects")
target=deparse(substitute(target))
target=gsub("^\"","",gsub("\"$","",target)) # strip leading and ending escaped quotes
endpos=regexpr("[\\[$]",target)-1; if (endpos<=0) endpos=nchar(target)
base=substring(target,1,endpos)
if (!exists(base,envir=tenv))
assign(base,list(),envir=tenv)
if (!missing(value)) { # use explicit value instead of objects
objet=paste(deparse(value),collapse="\n")
eval(parse(text=paste(target,"[[\"",stuff,"\"]]=",objet,sep="")),envir=tenv) } #pack explicit value into the list
else {
for (s in stuff) {
if (!exists(s,envir=penv)) next
eval(parse(text=paste("objet=get(\"",s,"\",envir=penv)",sep=""))) #grab the local object
if (is.list(objet) && !is.data.frame(objet)) {
atts=attributes(objet)
objet=deparseBO(objet)
natts=setdiff(names(atts),names(attributes(objet)))
# retain additional attributes of the original list
if (length(natts)>0) {
for (i in natts) attr(objet,i)=atts[[i]] }
# Reminder: applying original class can cause a display error if
# underlying objects (e.g., functions, calls) have been converted to strings.
#lclass=sapply(objet,class,simplify=FALSE)
#for(i in 1:length(objet)) attr(objet[[i]],"class")=lclass[[i]]
}
objet=paste(deparse(objet),collapse="\n")
eval(parse(text=paste(target,"[[\"",s,"\"]]=",objet,sep="")),envir=tenv) } #pack into the list
}
invisible() }
#-----------------------------.packList.deprecated
#===== THE END ===================================
|
subroutine dadjdx(delxi,dlxmin,iodb,nodbmx,noutpt,qadjdx)
c
c This subroutine determines whether or not delxi can be reduced
c to satisfy some criterion, such as the pH not exceeding the
c requested maximum value.
c
c This subroutine is called by:
c
c EQ6/path.f
c
c-----------------------------------------------------------------------
c
c Principal input:
c
c
c Principal output:
c
c
c-----------------------------------------------------------------------
c
implicit none
c
c-----------------------------------------------------------------------
c
integer nodbmx
c
integer noutpt
c
integer iodb(nodbmx)
c
logical qadjdx
c
real*8 delxi,dlxmin
c
c-----------------------------------------------------------------------
c
c Local variable declarations.
c
c None
c
c-----------------------------------------------------------------------
c
qadjdx = .false.
if (delxi .le. dlxmin) then
c
c The step size is already at the minimum value.
c Do not cut it.
c
if (iodb(1) .gt. 0) write (noutpt,1100)
1100 format(3x,'The step size will not be cut because it is',
$ ' already at the',/5x,'minimum value.',/)
else
c
c Set up to go back and cut the step size to satisfy the
c accuracy criterion for calculating the point at which the
c event of concern occurs.
c
qadjdx = .true.
endif
c
end
|
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.set.finite
import data.finset.order
import order.well_founded
import order.order_iso_nat
import order.atoms
import order.zorn
import tactic.tfae
/-!
# Compactness properties for complete lattices
For complete lattices, there are numerous equivalent ways to express the fact that the relation `>`
is well-founded. In this file we define three especially-useful characterisations and provide
proofs that they are indeed equivalent to well-foundedness.
## Main definitions
* `complete_lattice.is_sup_closed_compact`
* `complete_lattice.is_Sup_finite_compact`
* `complete_lattice.is_compact_element`
* `complete_lattice.is_compactly_generated`
## Main results
The main result is that the following four conditions are equivalent for a complete lattice:
* `well_founded (>)`
* `complete_lattice.is_sup_closed_compact`
* `complete_lattice.is_Sup_finite_compact`
* `∀ k, complete_lattice.is_compact_element k`
This is demonstrated by means of the following four lemmas:
* `complete_lattice.well_founded.is_Sup_finite_compact`
* `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact`
* `complete_lattice.is_sup_closed_compact.well_founded`
* `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact`
We also show well-founded lattices are compactly generated
(`complete_lattice.compactly_generated_of_well_founded`).
## References
- [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu]
## Tags
complete lattice, well-founded, compact
-/
variables {α : Type*} [complete_lattice α]
namespace complete_lattice
variables (α)
/-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset
contains its `Sup`. -/
def is_sup_closed_compact : Prop :=
∀ (s : set α) (h : s.nonempty), (∀ a b, a ∈ s → b ∈ s → a ⊔ b ∈ s) → (Sup s) ∈ s
/-- A compactness property for a complete lattice is that any subset has a finite subset with the
same `Sup`. -/
def is_Sup_finite_compact : Prop :=
∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id
/-- An element `k` of a complete lattice is said to be compact if any set with `Sup`
above `k` has a finite subset with `Sup` above `k`. Such an element is also called
"finite" or "S-compact". -/
def is_compact_element {α : Type*} [complete_lattice α] (k : α) :=
∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id
/-- An element `k` is compact if and only if any directed set with `Sup` above
`k` already got above `k` at some point in the set. -/
theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) :
is_compact_element k ↔
∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x :=
begin
classical,
split,
{ by_cases hbot : k = ⊥,
-- Any nonempty directed set certainly has sup above ⊥
{ rintros _ _ ⟨x, hx⟩ _ _, use x, by simp only [hx, hbot, bot_le, and_self], },
{ intros hk s hne hdir hsup,
obtain ⟨t, ht⟩ := hk s hsup,
-- If t were empty, its sup would be ⊥, which is not above k ≠ ⊥.
have tne : t.nonempty,
{ by_contradiction n,
rw [finset.nonempty_iff_ne_empty, not_not] at n,
simp only [n, true_and, set.empty_subset, finset.coe_empty,
finset.sup_empty, le_bot_iff] at ht,
exact absurd ht hbot, },
-- certainly every element of t is below something in s, since ↑t ⊆ s.
have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, by refl⟩,
obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s,
exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, },
{ intros hk s hsup,
-- Consider the set of finite joins of elements of the (plain) set s.
let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id },
-- S is directed, nonempty, and still has sup above k.
have dir_US : directed_on (≤) S,
{ rintros x ⟨c, hc⟩ y ⟨d, hd⟩,
use x ⊔ y,
split,
{ use c ∪ d,
split,
{ simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], },
{ simp only [hc.right, hd.right, finset.sup_union], }, },
simp only [and_self, le_sup_left, le_sup_right], },
have sup_S : Sup s ≤ Sup S,
{ apply Sup_le_Sup,
intros x hx, use {x},
simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton,
set.singleton_subset_iff], },
have Sne : S.nonempty,
{ suffices : ⊥ ∈ S, from set.nonempty_of_mem this,
use ∅,
simp only [set.empty_subset, finset.coe_empty, finset.sup_empty,
eq_self_iff_true, and_self], },
-- Now apply the defn of compact and finish.
obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S),
obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS,
use t, exact ⟨htS, by rwa ←htsup⟩, },
end
/-- A compact element `k` has the property that any directed set lying strictly below `k` has
its Sup strictly below `k`. -/
lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α}
(hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s)
(hbelow : ∀ x ∈ s, x < k) : Sup s < k :=
begin
rw is_compact_element_iff_le_of_directed_Sup_le at hk,
by_contradiction,
have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le),
replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩,
obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le,
obtain hxk := hbelow x hxs,
exact hxk.ne (hxk.le.antisymm hkx),
end
lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α}
(s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) :=
begin
classical,
rw is_compact_element_iff_le_of_directed_Sup_le,
intros d hemp hdir hsup,
change f with id ∘ f, rw ←finset.sup_finset_image,
apply finset.sup_le_of_le_directed d hemp hdir,
rintros x hx,
obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx,
specialize h p hps,
rw is_compact_element_iff_le_of_directed_Sup_le at h,
specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup),
simpa only [exists_prop],
end
lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) :
is_Sup_finite_compact α :=
begin
intros s,
let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x },
have hp : p.nonempty, { use [⊥, ∅], simp, },
obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp,
use t, simp only [ht₁, ht₂, true_and], apply le_antisymm,
{ apply Sup_le, intros y hy, classical,
have hy' : (insert y t).sup id ∈ p,
{ use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, },
have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), },
rw ← hm _ hy' hm', simp, },
{ rw [← ht₂, finset.sup_eq_Sup], exact Sup_le_Sup ht₁, },
end
lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) :
is_sup_closed_compact α :=
begin
intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h,
cases t.eq_empty_or_nonempty with h h,
{ subst h, rw finset.sup_empty at ht₂, rw ht₂,
simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], },
{ rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, },
end
lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) :
well_founded ((>) : α → α → Prop) :=
begin
rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩,
suffices : Sup (set.range a) ∈ set.range a,
{ obtain ⟨n, hn⟩ := set.mem_range.mp this,
have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], },
apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, },
apply h (set.range a),
{ use a 37, apply set.mem_range_self, },
{ rintros x y ⟨m, hm⟩ ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply a.to_rel_hom.map_sup, },
end
lemma is_Sup_finite_compact_iff_all_elements_compact :
is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) :=
begin
split,
{ intros h k s hs,
obtain ⟨t, ⟨hts, htsup⟩⟩ := h s,
use [t, hts],
rwa ←htsup, },
{ intros h s,
obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl),
have : Sup s = t.sup id,
{ suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption },
simp only [id.def, finset.sup_le_iff],
intros x hx,
apply le_Sup, exact hts hx, },
use [t, hts], assumption, },
end
lemma well_founded_characterisations :
tfae [well_founded ((>) : α → α → Prop),
is_Sup_finite_compact α,
is_sup_closed_compact α,
∀ k : α, is_compact_element k] :=
begin
tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, },
tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, },
tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, },
tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α },
tfae_finish,
end
lemma well_founded_iff_is_Sup_finite_compact :
well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α :=
(well_founded_characterisations α).out 0 1
lemma is_Sup_finite_compact_iff_is_sup_closed_compact :
is_Sup_finite_compact α ↔ is_sup_closed_compact α :=
(well_founded_characterisations α).out 1 2
lemma is_sup_closed_compact_iff_well_founded :
is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) :=
(well_founded_characterisations α).out 2 0
alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded
alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔
_ is_sup_closed_compact.is_Sup_finite_compact
alias is_sup_closed_compact_iff_well_founded ↔ _ well_founded.is_sup_closed_compact
end complete_lattice
/-- A complete lattice is said to be compactly generated if any
element is the `Sup` of compact elements. -/
class is_compactly_generated (α : Type*) [complete_lattice α] : Prop :=
(exists_Sup_eq :
∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x)
section
variables {α} [is_compactly_generated α] {a b : α} {s : set α}
@[simp]
lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b :=
begin
rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩,
exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)),
end
@[simp]
theorem Sup_compact_eq_top :
Sup {a : α | complete_lattice.is_compact_element a} = ⊤ :=
begin
refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤),
exact (and_iff_left le_top).symm,
end
theorem le_iff_compact_le_imp {a b : α} :
a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b :=
⟨λ ab c hc ca, le_trans ca ab, λ h, begin
rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b],
exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩),
end⟩
/-- This property is sometimes referred to as `α` being upper continuous. -/
theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s):
a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b :=
le_antisymm (begin
rw le_iff_compact_le_imp,
by_cases hs : s.nonempty,
{ intros c hc hcinf,
rw le_inf_iff at hcinf,
rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc,
rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩,
exact (le_inf hcinf.1 cd).trans (le_bsupr d ds) },
{ rw set.not_nonempty_iff_eq_empty at hs,
simp [hs] }
end) supr_inf_le_inf_Sup
/-- This property is equivalent to `α` being upper continuous. -/
theorem inf_Sup_eq_supr_inf_sup_finset :
a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) :=
le_antisymm (begin
rw le_iff_compact_le_imp,
intros c hc hcinf,
rw le_inf_iff at hcinf,
rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩,
exact (le_inf hcinf.1 ht2).trans (le_bsupr t ht1),
end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_eq_Sup t).symm ▸ (Sup_le_Sup h)))
theorem complete_lattice.set_independent_iff_finite {s : set α} :
complete_lattice.set_independent s ↔
∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) :=
⟨λ hs t ht, hs.mono ht, λ h a ha, begin
rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot],
intro t,
rw [supr_eq_bot, finset.sup_eq_Sup],
intro ht,
classical,
have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot,
{ rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h',
exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) },
{ rw [finset.coe_insert, set.insert_subset],
exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ }
end⟩
lemma complete_lattice.set_independent_Union_of_directed {η : Type*}
{s : η → set α} (hs : directed (⊆) s)
(h : ∀ i, complete_lattice.set_independent (s i)) :
complete_lattice.set_independent (⋃ i, s i) :=
begin
by_cases hη : nonempty η,
{ resetI,
rw complete_lattice.set_independent_iff_finite,
intros t ht,
obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht,
obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset,
exact (h i).mono (set.subset.trans hI $ set.bUnion_subset $
λ j hj, hi j (fi.mem_to_finset.2 hj)) },
{ rintros a ⟨_, ⟨i, _⟩, _⟩,
exfalso, exact hη ⟨i⟩, },
end
lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)}
(hs : directed_on (⊆) s)
(h : ∀ a ∈ s, complete_lattice.set_independent a) :
complete_lattice.set_independent (⋃₀ s) :=
by rw set.sUnion_eq_Union; exact
complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h)
end
namespace complete_lattice
lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) :
is_compactly_generated α :=
begin
rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h,
-- x is the join of the set of compact elements {x}
exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩,
end
/-- A compact element `k` has the property that any `b < `k lies below a "maximal element below
`k`", which is to say `[⊥, k]` is coatomic. -/
theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) :
is_coatomic (set.Iic k) :=
⟨λ ⟨b, hbk⟩, begin
by_cases htriv : b = k,
{ left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], },
right,
rcases zorn.zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv)
with ⟨a, a₀, ba, h⟩,
{ refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩,
cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le,
exact lt_irrefl _ hck, },
{ intros S SC cC I IS,
by_cases hS : S.nonempty,
{ exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, },
exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS,
set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, },
end⟩
lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α :=
(@order_iso.Iic_top α _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h)
end complete_lattice
section
variables [is_modular_lattice α] [is_compactly_generated α]
@[priority 100]
instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α :=
⟨λ b, begin
by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥},
{ left,
rw [← Sup_compact_le_eq b, Sup_eq_bot],
exact h },
{ rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩,
right,
have hc' := complete_lattice.Iic_coatomic_of_compact_element hc,
rw ← is_atomic_iff_is_coatomic at hc',
haveI := hc',
obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c),
{ exfalso,
apply hcbot,
simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con,
exact con },
rw [← subtype.coe_le_coe, subtype.coe_mk] at hac,
exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ },
end⟩
/-- See Lemma 5.1, Călugăreanu -/
@[priority 100]
instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α :=
⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin
symmetry,
have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right),
apply (lt_or_eq_of_le hle).resolve_left (λ con, _),
obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b),
obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c,
{ exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) },
{ apply ha.1,
rw eq_bot_iff,
apply le_trans (le_inf _ hac) hc.1,
rw [← subtype.coe_le_coe, subtype.coe_mk],
exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ }
end, λ _, and.left⟩⟩
/-- See Theorem 6.6, Călugăreanu -/
theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α :=
⟨λ b, begin
obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn.zorn_subset
{s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _,
{ refine ⟨Sup s, le_of_eq b_inf_Sup_s, _⟩,
rw [← h, Sup_le_iff],
intros a ha,
rw ← inf_eq_left,
refine (eq_bot_or_eq_of_le_atom ha inf_le_left).resolve_left (λ con, ha.1 _),
rw [eq_bot_iff, ← con],
refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right),
rw ← disjoint_iff at *,
have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right,
rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _),
{ exact set.mem_union_right _ (set.mem_singleton _) },
{ rw [set.mem_union, set.mem_singleton_iff] at hx,
by_cases xa : x = a,
{ simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton],
exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) },
{ have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a},
{ simp only [set.union_singleton],
rw set.insert_diff_of_not_mem,
rw set.mem_singleton_iff,
exact ne.symm xa },
rw [h, Sup_union, Sup_singleton],
apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left
(a_dis_Sup_s.mono_right _).symm,
rw [← Sup_insert, set.insert_diff_singleton,
set.insert_eq_of_mem (hx.resolve_right xa)] } },
{ rw [Sup_union, Sup_singleton, ← disjoint_iff],
exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm },
{ rw [set.mem_union, set.mem_singleton_iff] at hx,
cases hx,
{ exact s_atoms x hx },
{ rw hx,
exact ha } } },
{ intros c hc1 hc2,
refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on
(λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩,
{ rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot],
{ intro i,
rw supr_eq_bot,
intro hi,
obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi,
exact (hc1 xc).2.1 },
{ rw directed_on_image,
refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } },
{ rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩,
exact (hc1 sc).2.2 a as } }
end⟩
/-- See Theorem 6.6, Călugăreanu -/
theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α :=
is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top
theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α :=
begin
split; introsI,
{ exact is_atomistic_of_is_complemented },
{ exact is_complemented_of_is_atomistic }
end
end
|
This is an archive for past years pledges for Bike Commute Month for those DavisWiki participants.
2009
2008
2007
|
[STATEMENT]
lemma analz_insert_Agent [simp]:
"analz (insert (Agent agt) H) = insert (Agent agt) (analz H)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. analz (insert (Agent agt) H) = insert (Agent agt) (analz H)
[PROOF STEP]
apply (rule analz_insert_eq_I)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. x \<in> analz (insert (Agent agt) H) \<Longrightarrow> x \<in> insert (Agent agt) (analz H)
[PROOF STEP]
apply (erule analz.induct, auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
lemma closed_singleton [iff]: "closed {a}" |
State Before: ⊢ cos (2 * ↑π) = 1 State After: no goals Tactic: simp [two_mul, cos_add] |
/-
This is the second homework assignment for UVa CS2101, Spring 2019.
If you are in Professor Sullivan's class, you are to complete problems 1 - 8.
If you are in Prof. Hocking's class, you are to complete problems 9 - 13.
The first eight problems require that you carefully read the updated class
notes on relations vs. functions and on properties of functions: from the
start of 2.4 through 2.4.4. For all of the remaining problems, you must
have read the rest of the chapter, on higher-order functions.
The collaboration policy for this assignment has two parts. First, you must
complete this work on your own. Second, please do not discuss your results
with anyone in the other professor's class, even after the deadline for the
homework has passed, as your assignment this week will be part of their
assignment next week.
To complete this homework, first make a copy of this file in the "work"
directory of your class repository. Do not edit this file directly in the
hw directory. Make a copy first. Then fill in answers as required, save
your changes, and submit your work by uploading the completed file on Collab.
Make a copy of this file in your work directory; complete the work using
that copy; then upload the resulting file, after saving it, through Collab
before the due date.
-/
/-
1. Is the function, G, as defined in the reading, total? Explain.
Answer here:
-/
/-
2. Give an example of a value in the domain of definition the function, F,
as defined in the reading, that proves that F is strictly partial, i.e.,
for which F is not defined.
Answer here:
-/
/-
3. Give an example of a value in the codomain of F that proves that F is
not surjective.
Answer here:
-/
/-
4. Is our example function, G, strictly partial? Explain.
Answer here:
-/
/-
5. Identify a value in the codomain of F that is not the image of any
value value in its domain of definition.
Answer here:
-/
/-
6. Translate our logical definition of injective into mathematically
precise English following the examples for other properties of functions
given in the reading.
Answer here:
-/
/-
7. Is the function, f(x) = log(x) over the real numbers, injective?
Is it surjective? Is it bijective? Explain each of your answers briefly.
Answer here:
-/
/-
8. Is the relation, 3x^2 + 4y^2 = 4, single-valued? Explain your answers.
Answer here:
-/
/-
Complete each of the following partial definitions in Lean by replacing
the underscore characters with code to define functions of the specified
types using lambda notation. We only care that you define some function
of each required type, not what particular function you define.
In preparation, note that if you hover your mouse over an underscore,
Lean will tell you what type of term you is needed to fill that hole.
The type that Lean requires appears after the "turnstile" symbol, |-,
in the message Lean will give you. Even more interestingly, if you
fill in a hole with a term of the right type that itself has one or
more remaining holes, Lean will tell you what types of terms are needed
to fill in those holes! You can thus fill a hole in an incremental manner,
refining a partial solution at each step until all holes are filled,
guided by the types that Lean tells you are needed for any given hole.
We recommend that you try developing your answers in this "top-down
structured" style of programming. That said, we will grade you only on
your answers and not on how you developed them.
-/
-- 9.
def hw2_1: ℕ → ℕ :=
λ(x: ℕ),
_
-- 10.
def hw2_2: ℕ → ℕ → ℕ :=
_
-- 11.
def hw2_3: (ℕ → ℕ) → (ℕ → ℕ) :=
_
-- 12.
def hw2_4: (ℕ → ℕ) → ((ℕ → ℕ) → ℕ) :=
_
-- 13.
def hw2_5: (ℕ → ℕ) → ((ℕ → ℕ) → (ℕ → ℕ)) :=
_
|
import numpy as np
import pandas as pd
import os, sys, csv, random, time
import gensim, re, string, nltk
from collections import Counter
from pickle import dump, load
import tensorflow as tf
from tensorflow import keras
from gensim.models import Word2Vec
from sklearn.model_selection import train_test_split
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from utils import tokenize
from utils import create_sequences
from utils import reduce_corpus
from utils import reduce_vocab
from utils import load_embeddings
from model import BiRNN
from model import loss_function
from model import mask_sequences
@tf.function
def train_step(batch, loss_object):
loss = 0
with tf.GradientTape() as tape:
for t in range(1, batch.shape[0]):
inp, tar = mask_sequences(batch, t=t)
pred = birnn(inp, predict=True)
loss += loss_function(tar, pred, loss_object)
batch_loss = (loss / int(batch.shape[0]))
variables = birnn.trainable_variables
gradients = tape.gradient(loss, variables)
optimizer.apply_gradients(zip(gradients, variables))
train_loss(batch_loss)
return batch_loss
##------------------------------ Define constants and hyperparameters ------------------------------##
UNK_TOKEN = '"انک"'
START_TOKEN = '"س"'
END_TOKEN = '"ش"'
EPOCHS = 10
MIN_SEQ_LEN = 10 # min/max length of input sequences
MAX_SEQ_LEN = 128
MIN_COUNT = 10 # minimum count for vocab words
TEST_SIZE = 0.15
RANDOM_STATE = 42
BATCH_SIZE = 32
UNITS = 256
EMBEDDING_DIM = 256
PROJECTION_UNITS = 256
BUFFER_SIZE = 10000
CORPUS_PATH = 'data/corpus.txt'
EMBEDDING_PATH = 'data/word2vec256.bin'
CHECKPOINT_PATH = 'checkpoints'
LOG_DIR = 'logs'
##------------------------------ Preprocess ------------------------------##
corpus = open(CORPUS_PATH).read().split('\n') # read corpus
corpus = [[token for token in line.split(' ') if token != ''] for line in corpus] # tokenize corpus into words
print('Pre-processing')
print('vocab size: ', len(set([token for line in corpus for token in line])))
print('num. of lines: ', len(corpus))
print(' '.join(corpus[0]))
corpus = reduce_corpus(corpus, min_len=MIN_SEQ_LEN) # reduce corpus size - remove lines with length less than MIN_SEQ_LEN
corpus = [[START_TOKEN]+line+[END_TOKEN] for line in corpus] # add start and end tokens
corpus = reduce_vocab(corpus, UNK_TOKEN, min_count=MIN_COUNT) # reduce vocab size - remove token with count less than MIN_COUNT
vocab = list(set([token for line in corpus for token in line])) # extract vocabulary of corpus
corpus = create_sequences(corpus, max_len=MAX_SEQ_LEN) # create sequences of max length MAX_SEQ_LEN
print('\nPost-processing')
print('vocab size: ', len(vocab))
print('num. of lines: ', len(corpus))
print(' '.join(corpus[0]))
tensor, lang = tokenize(corpus, oov_token=UNK_TOKEN) # tokenize corpus and prepare padded Tensor sequences
train, test = train_test_split(tensor, test_size=TEST_SIZE, random_state=RANDOM_STATE) # split dataset into train and test
del tensor, corpus
steps_per_epoch = len(train)//BATCH_SIZE
vocab_size = max(lang.word_index.values())+1
print('\ntrain shape: ', train.shape, '\tbatches: ', steps_per_epoch)
train = tf.data.Dataset.from_tensor_slices(train).shuffle(BUFFER_SIZE)
train = train.batch(BATCH_SIZE, drop_remainder=True)
# Load embeddings matrix
embedding_matrix = load_embeddings(
embedding_path=EMBEDDING_PATH,
tokenizer=lang,
vocab_size=vocab_size,
embedding_dim=EMBEDDING_DIM,
unk_token=UNK_TOKEN,
start_token=START_TOKEN,
end_token=END_TOKEN)
##------------------------------ Setup training ------------------------------##
birnn = BiRNN(UNITS, PROJECTION_UNITS, MAX_SEQ_LEN, vocab_size, EMBEDDING_DIM, embedding_matrix)
optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)
ckpt = tf.train.Checkpoint(birnn=birnn)
ckpt_manager = tf.train.CheckpointManager(ckpt, CHECKPOINT_PATH, max_to_keep=2)
train_summary_writer = tf.summary.create_file_writer(LOG_DIR)
# if a checkpoint exists, restore the latest checkpoint.
if ckpt_manager.latest_checkpoint:
ckpt.restore(ckpt_manager.latest_checkpoint)
print('Latest checkpoint restored')
##------------------------------ Training ------------------------------##
print('\ntraining')
for epoch in range(EPOCHS):
start = time.time()
total_loss = 0
for i, batch in enumerate(train.take(steps_per_epoch)):
print('batch: ', i)
batch_loss = train_step(batch, loss_object)
total_loss += batch_loss
if i % 10 == 0:
print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1, i, batch_loss.numpy()))
if i % 100 == 0:
print('Epoch {} Batch {} Saving weights'.format(epoch + 1, i))
ckpt_save_path = ckpt_manager.save()
with train_summary_writer.as_default():
tf.summary.scalar('loss', train_loss.result(), step=epoch)
print ('Saving checkpoint for epoch {} at {}'.format(epoch+1,ckpt_save_path))
print('Epoch {} Loss {:.4f}'.format(epoch + 1, train_loss.result()))
print('Time taken for 1 epoch {} sec\n'.format(time.time() - start))
|
module Hoare
import Assn
import Expr
import Imp
import Logic
import Maps
%access public export
%default total
HoareTriple : (p : Assertion) -> (c : Com) -> (q : Assertion) -> Type
HoareTriple p c q = (st, st' : State) -> (c / st \\ st') -> p st -> q st'
hoare_post_true : ((st : State) -> q st) -> HoareTriple p c q
hoare_post_true f _ st' _ _ = f st'
hoare_pre_false : ((st : State) -> Not (p st)) -> HoareTriple p c q
hoare_pre_false f = \st, st', rel, p_st => absurd $ f st p_st
hoare_assign : (q : Assertion) -> HoareTriple (AssignSub x a q) (x ::= a) q
hoare_assign q = \st, _, (E_Ass prf), q_st => rewrite sym prf in q_st
assn_sub_example : HoareTriple (AssignSub X (X + 1) (\st => LT (st X) 5))
(X ::= X + 1)
(\st => LT (st X) 5)
assn_sub_example = hoare_assign (\st => LT (st X) 5)
hoare_assign_fwd : (m : Nat) -> (a : AExp) -> (p : Assertion) ->
HoareTriple (\st => (p st, st X = m))
(X ::= a)
(\st => ( p (t_update X m st)
, st X = aeval (t_update X m st) a ))
hoare_assign_fwd m a p st _ (E_Ass {n} prf1) (p_st, prf2) =
rewrite sym prf2
in rewrite trans (t_update_shadow {x=X} {v2=st X} {v1=n} {m=st})
(t_update_same {x=X} {m=st})
in (p_st, sym prf1)
hoare_assign_fwd_exists : (a : AExp) -> (p : Assertion) ->
HoareTriple
(\st => p st)
(X ::= a)
(\st => (m ** ( p (t_update X m st)
, st X = aeval (t_update X m st) a )))
hoare_assign_fwd_exists a p st st' rel p_st with (st X) proof prf2
hoare_assign_fwd_exists a p st st' rel p_st | m =
(m ** hoare_assign_fwd m a p st st' rel (p_st, sym prf2))
hoare_consequence_pre : (p, p', q : Assertion) -> HoareTriple p' c q ->
(p ->> p') -> HoareTriple p c q
hoare_consequence_pre p p' q ht imp = \st, st', rel, p_st =>
ht st st' rel (imp st p_st)
hoare_consequence_post : (p, q, q' : Assertion) -> HoareTriple p c q' ->
(q' ->> q) -> HoareTriple p c q
hoare_consequence_post p q q' ht imp = \st, st', rel, p_st =>
imp st' (ht st st' rel p_st)
hoare_assign_example_1 : HoareTriple (const ()) (X ::= 1) (\st => st X = 1)
hoare_assign_example_1 =
hoare_consequence_post (const ())
(\st => st X = 1)
(\st => (m : Nat ** ((), st X = 1)))
(hoare_assign_fwd_exists 1 (const ()))
(\_, (_ ** (_, prf)) => prf)
hoare_assign_example_2 : HoareTriple (\st => LT (st X) 4)
(X ::= X + 1)
(\st => LT (st X) 5)
hoare_assign_example_2 =
hoare_consequence_pre (\st => LT (st X) 4)
(\st => LT (st X + 1) 5)
(\st => LT (st X) 5)
(hoare_assign (\st => LT (st X) 5))
(\st, p_st => replace {P=\x => LT x 5}
(sym (plusCommutative (st X) 1))
(LTESucc p_st))
hoare_consequence : (p, p', q, q' : Assertion) -> HoareTriple p' c q' ->
p ->> p' -> q' ->> q -> HoareTriple p c q
hoare_consequence p p' q q' ht p_imp_p' q'_imp_q =
let ht' = hoare_consequence_pre p p' q' ht p_imp_p'
in hoare_consequence_post p q q' ht' q'_imp_q
hoare_assign_example_5 : HoareTriple (\st => LTE (st X + 1) 5)
(X ::= X + 1)
(\st => LTE (st X) 5)
hoare_assign_example_5 = hoare_assign (\st => LTE (st X) 5)
hoare_assign_example_6 : HoareTriple (\st => (LTE 0 3, LTE 3 5))
(X ::= 3)
(\st => (LTE 0 (st X), LTE (st X) 5))
hoare_assign_example_6 = hoare_assign (\st => (LTE 0 (st X), LTE (st X) 5))
hoare_skip : (p : Assertion) -> HoareTriple p SKIP p
hoare_skip _ _ _ E_Skip p_st = p_st
hoare_seq : (p, q, r : Assertion) -> HoareTriple q c2 r -> HoareTriple p c1 q ->
HoareTriple p (do c1; c2) r
hoare_seq p q r ht2 ht1 = \st, st', (E_Seq {st2} cc1 cc2), p_st =>
let q_st2 = ht1 st st2 cc1 p_st
in ht2 st2 st' cc2 q_st2
hoare_assign_example_3 : (a : AExp) -> (n : Nat) ->
HoareTriple (\st => aeval st a = n)
(do X ::= a; SKIP)
(\st => st X = n)
hoare_assign_example_3 a n =
let hta = hoare_assign_fwd_exists a (\st => aeval st a = n)
hta' = hoare_consequence_post
(\st => aeval st a = n)
(\st => st X = n)
(\st => (m : Nat ** ( aeval (t_update X m st) a = n
, st X = aeval (t_update X m st) a )))
hta
(\_, (_ ** (aeval_eq_n, st_X_eq_aeval)) =>
trans st_X_eq_aeval aeval_eq_n)
hts = hoare_skip (\st => st X = n)
in hoare_seq (\st => aeval st a = n) (\st => st X = n) (\st => st X = n)
hts hta'
hoare_assign_example_4 : HoareTriple (const ())
(do X ::= 1; Y ::= 2)
(\st => (st X = 1, st Y = 2))
hoare_assign_example_4 =
let htx = hoare_consequence_post
(const ())
(\st => st X = 1)
(\st => (m : Nat ** ((), st X = 1)))
(hoare_assign_fwd_exists 1 (const ()))
(\_, (_ ** (_, q_st)) => q_st)
hty = hoare_consequence_pre
(\st => st X = 1)
(AssignSub Y 2 (\st => (st X = 1, st Y = 2)))
(\st => (st X = 1, st Y = 2))
(hoare_assign (\st => (st X = 1, st Y = 2)))
(\_, p_st => (p_st, Refl))
in hoare_seq (const ()) (\st => st X = 1) (\st => (st X = 1, st Y = 2))
hty htx
swap_program : Com
swap_program = do Z ::= X
X ::= Y
Y ::= Z
swap_exercise : HoareTriple (\st => LTE (st X) (st Y))
Hoare.swap_program
(\st => LTE (st Y) (st X))
swap_exercise =
let htz = hoare_consequence_pre
(\st => LTE (st X) (st Y))
(AssignSub Z X (\st => LTE (st Z) (st Y)))
(\st => LTE (st Z) (st Y))
(hoare_assign (\st => LTE (st Z) (st Y)))
(\_, p_st => p_st)
htx = hoare_consequence_pre (\st => LTE (st Z) (st Y))
(AssignSub X Y (\st => LTE (st Z) (st X)))
(\st => LTE (st Z) (st X))
(hoare_assign (\st => LTE (st Z) (st X)))
(\_, p_st => p_st)
hty = hoare_consequence_pre (\st => LTE (st Z) (st X))
(AssignSub Y Z (\st => LTE (st Y) (st X)))
(\st => LTE (st Y) (st X))
(hoare_assign (\st => LTE (st Y) (st X)))
(\_, p_st => p_st)
htxy = hoare_seq (\st => LTE (st Z) (st Y))
(\st => LTE (st Z) (st X))
(\st => LTE (st Y) (st X))
hty
htx
in hoare_seq (\st => LTE (st X) (st Y))
(\st => LTE (st Z) (st Y))
(\st => LTE (st Y) (st X))
htxy
htz
hoare_if : (p, q : Assertion) ->
HoareTriple (\st => (p st, BAssn b st)) c1 q ->
HoareTriple (\st => (p st, Not (BAssn b st))) c2 q ->
HoareTriple p (CIf b c1 c2) q
hoare_if p q ht1 ht2 = \st, st', rel, p_st => case rel of
E_IfTrue prf cc1 => ht1 st st' cc1 (p_st, prf)
E_IfFalse prf cc2 => ht2 st st' cc2 (p_st, bexp_eval_false prf)
if_example : HoareTriple (const ())
(CIf (X == 0) (Y ::= 2) (Y ::= X + 1))
(\st => LTE (st X) (st Y))
if_example =
let htt = hoare_consequence
(\st => ((), BAssn (X == 0) st))
(AssignSub Y 2 (\st => (LTE (st X) (st Y), BAssn (X == 0) st)))
(\st => LTE (st X) (st Y))
(\st => (LTE (st X) (st Y), BAssn (X == 0) st))
(hoare_assign (\st => (LTE (st X) (st Y), BAssn (X == 0) st)))
(\st, (_, p_st) => ( replace {P=\x => LTE x 2}
(sym (fst (nat_beq_iff (st X) 0)
p_st))
LTEZero
, p_st ))
(\_, (q_st, _) => q_st)
htf = hoare_consequence
(\st => ((), Not (BAssn (X == 0) st)))
(AssignSub Y (X + 1) (\st => ( LTE (st X) (st Y)
, Not (BAssn (X == 0) st) )))
(\st => LTE (st X) (st Y))
(\st => (LTE (st X) (st Y), Not (BAssn (X == 0) st)))
(hoare_assign (\st => ( LTE (st X) (st Y)
, Not (BAssn (X == 0) st) )))
(\st, (_, p_st) => (lteAddRight (st X), p_st))
(\_, (q_st, _) => q_st)
in hoare_if (const ()) (\st => LTE (st X) (st Y)) htt htf
if_minus_plus : HoareTriple (const ())
(CIf (X <= Y) (Z ::= Y - X) (Y ::= X + Z))
(\st => st Y = st X + st Z)
if_minus_plus =
let htt = hoare_consequence
(\st => ((), BAssn (X <= Y) st))
(AssignSub Z (Y - X) (\st => ( st Y = st X + st Z
, BAssn (X <= Y) st )))
(\st => st Y = st X + st Z)
(\st => (st Y = st X + st Z, BAssn (X <= Y) st))
(hoare_assign (\st => (st Y = st X + st Z, BAssn (X <= Y) st)))
(\st, (_, p_st) =>
( sym (lte_plus_minus (fst (lte_beq_iff (st X) (st Y)) p_st))
, p_st ))
(\_, (q_st, _) => q_st)
htf = hoare_consequence_pre
(\st => ((), Not (BAssn (X <= Y) st)))
(AssignSub Y (X + Z) (\st => st Y = st X + st Z))
(\st => st Y = st X + st Z)
(hoare_assign (\st => st Y = st X + st Z))
(\_, _ => Refl)
in hoare_if (const ()) (\st => st Y = st X + st Z) htt htf
hoare_while : {b : BExp} -> {c : Com} -> (p : Assertion) ->
HoareTriple (\st => (p st, BAssn b st)) c p ->
HoareTriple p (WHILE b c) (\st => (p st, Not (BAssn b st)))
hoare_while {b} {c} p ht st _ (E_WhileEnd prf) p_st =
(p_st, snd not_true_iff_false prf)
hoare_while {b} {c} p ht st st' (E_WhileLoop {st1} prf cbody cnext) p_st =
hoare_while p ht st1 st' cnext (ht st st1 cbody (p_st, prf))
while_example : HoareTriple (\st => LTE (st X) 3)
(CWhile (X <= 2) (X ::= X + 1))
(\st => st X = 3)
while_example st st' rel lte_prf =
let htc = hoare_assign (\st => LTE (st X) 3)
htc' = hoare_consequence_pre
(\st => (LTE (st X) 3, beval st (X <= 2) = True))
(\st => LTE (st X + 1) 3)
(\st => LTE (st X) 3)
htc
(\st, p_st => replace {P=\x => LTE x 3}
(sym (plusCommutative (st X) 1))
(LTESucc (fst (lte_beq_iff (st X) 2)
(snd p_st))))
htw = hoare_while (\st => LTE (st X) 3) htc'
(below, contra) = htw st st' rel lte_prf
in bounded__eq below (fst (lte_nbeq_iff (st' X) 2)
(fst not_true_iff_false contra))
always_loop_hoare : (p, q : Assertion) -> HoareTriple p (WHILE BTrue SKIP) q
always_loop_hoare p q =
let htc = hoare_consequence_pre
(\st => (p st, BAssn BTrue st))
p
p
(hoare_skip p)
(\st, (p_st, _) => p_st)
htw = hoare_while p htc
in hoare_consequence_post
p
q
(\st => (p st, Not (BAssn BTrue st)))
htw
(\st, (_, contra) => absurd (contra Refl))
hoare_if1 : {b : BExp} -> {c : Com} -> (p, q : Assertion) ->
HoareTriple (\st => (p st, BAssn b st)) c q ->
(\st => (p st, Not (BAssn b st))) ->> q ->
HoareTriple p (CIf1 b c) q
hoare_if1 {b} {c} p q htc _ st st' (E_If1True prf cc) p_st =
htc st st' cc (p_st, prf)
hoare_if1 {b} {c} p q _ imp st _ (E_If1False prf) p_st =
imp st (p_st, snd not_true_iff_false prf)
hoare_if1_good : HoareTriple (\st => st X + st Y = st Z)
(IF1 not (Y == 0) THEN
X ::= X + Y
FI)
(\st => st X = st Z)
hoare_if1_good =
let htc = hoare_consequence
(\st => (st X + st Y = st Z, not (st Y == 0) = True))
(AssignSub X (X + Y)
(\st => (st X = st Z, not (st Y == 0) = True)))
(\st => st X = st Z)
(\st => (st X = st Z, not (st Y == 0) = True))
(hoare_assign (\st => (st X = st Z, not (st Y == 0) = True)))
(\_, p_st => p_st)
(\st, (q_st, _) => q_st)
hts = hoare_consequence
(\st => (st X + st Y = st Z, Not (not (st Y == 0) = True)))
(\st => (st X = st Z, Not (not (st Y == 0) = True)))
(\st => st X = st Z)
(\st => (st X = st Z, Not (not (st Y == 0) = True)))
(hoare_skip (\st => (st X = st Z, Not (not (st Y == 0) = True))))
(\st, (plus_st_X_st_Y__st_Z, prf) =>
let st_Y_eq_0 = fst (nat_beq_iff (st Y) 0)
(trans (sym (notInvolutive (st Y == 0)))
(cong {f=not}
(fst not_true_iff_false prf)))
pf = trans (sym (plusZeroRightNeutral (st X)))
(replace {P=\x => st X + x = st Z}
st_Y_eq_0 plus_st_X_st_Y__st_Z)
in (pf, prf))
(\st, (q_st, _) => q_st)
imp = \st, (plus_st_X_st_Y__st_Z, prf) =>
let st_Y_eq_0 = fst (nat_beq_iff (st Y) 0)
(trans (sym (notInvolutive (st Y == 0)))
(cong {f=not} (fst not_true_iff_false prf)))
in trans (sym (plusZeroRightNeutral (st X)))
(replace {P=\x => st X + x = st Z}
st_Y_eq_0 plus_st_X_st_Y__st_Z)
in hoare_if1 (\st => st X + st Y = st Z) (\st => st X = st Z) htc imp
hoare_for : {init, updt, body : Com} -> {cond : BExp} -> (p, q : Assertion) ->
HoareTriple p init q ->
HoareTriple (\st => (q st, BAssn cond st)) (do body; updt) q ->
HoareTriple p
(CFor init cond updt body)
(\st => (q st, Not (BAssn cond st)))
hoare_for {init} {updt} {body} {cond} p q ht_init ht_body_updt st st'
(E_For ci (E_WhileEnd prf)) p_st =
(ht_init st st' ci p_st, bexp_eval_false prf)
hoare_for {init} {updt} {body} {cond} p q ht_init ht_body_updt st st'
(E_For ci {st2} (E_WhileLoop {st1} prf cb cn)) p_st =
let q_st2 = ht_init st st2 ci p_st
q_st1 = ht_body_updt st2 st1 cb (q_st2, prf)
in hoare_while q ht_body_updt st1 st' cn q_st1
hoare_repeat : {c : Com} -> {b : BExp} -> (p, q : Assertion) ->
HoareTriple p c q -> (\st => (q st, Not (BAssn b st))) ->> p ->
HoareTriple p (CRepeat c b) (\st => (q st, BAssn b st))
hoare_repeat {c} {b} p q htc imp st st' (E_Repeat cc (E_WhileEnd prf)) p_st =
let q_st' = htc st st' cc p_st
btrue = trans (sym (notInvolutive (beval st' b))) (cong {f=not} prf)
in (q_st', btrue)
hoare_repeat {c} {b} p q htc imp st st'
r@(E_Repeat {st1} cc1 (E_WhileLoop prf cc2 cnext)) p_st =
let q_st1 = htc st st1 cc1 p_st
bfalse = bexp_eval_false (trans (sym (notInvolutive (beval st1 b)))
(cong {f=not} prf))
p_st1 = imp st1 (q_st1, bfalse)
in hoare_repeat p q htc imp st1 st'
(assert_smaller r (E_Repeat cc2 cnext)) p_st1
hoare_repeat_good : HoareTriple (\st => LT 0 (st X))
(REPEAT do
Y ::= X
X ::= X - 1
UNTIL X == 0 END)
(\st => (st X = 0, LT 0 (st Y)))
hoare_repeat_good =
let hty = hoare_assign (\st => LT 0 (st Y))
htx = hoare_assign (\st => LT 0 (st Y))
htc = hoare_seq (\st => LT 0 (st X))
(\st => LT 0 (st Y))
(\st => LT 0 (st Y))
htx
hty
ht_repeat = hoare_repeat
(\st => LT 0 (st X))
(\st => LT 0 (st Y))
htc
(\st, (_, prf) =>
notZeroImpliesGTZero
(fst (nat_nbeq_iff (st X) 0)
(fst not_true_iff_false prf)))
in hoare_consequence_post (\st => LT 0 (st X))
(\st => (st X = 0, LT 0 (st Y)))
(\st => (LT 0 (st Y), BAssn (X == 0) st))
ht_repeat
(\st, (lte_prf, prf) =>
let pf = fst (nat_beq_iff (st X) 0) prf
in (pf, lte_prf))
|
module Section_2_3_3 where
import Numeric.LinearAlgebra
and' :: Double -> Double -> Double
and' x1 x2 =
let x = vector [x1, x2]
w = vector [0.5, 0.5]
b = (-0.7)
tmp = w <.> x + b
in if tmp <= 0
then 0
else 1
nand :: Double -> Double -> Double
nand x1 x2 =
let x = vector [x1, x2]
w = vector [(-0.5), (-0.5)]
b = 0.7
tmp = w <.> x + b
in if tmp <= 0
then 0
else 1
or' :: Double -> Double -> Double
or' x1 x2 =
let x = vector [x1, x2]
w = vector [0.5, 0.5]
b = (-0.2)
tmp = w <.> x + b
in if tmp <= 0
then 0
else 1
|
[GOAL]
α β : LatCat
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
α β : LatCat
e : ↑α ≃o ↑β
x✝ : (forget LatCat).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]
α β : LatCat
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
α β : LatCat
e : ↑α ≃o ↑β
x✝ : (forget LatCat).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 _
|
[STATEMENT]
theorem soundness_fresh:
assumes \<open>A, n \<turnstile> [([\<^bold>\<not> p], i)]\<close> \<open>i \<notin> nominals p\<close>
shows \<open>M, g, w \<Turnstile> p\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
from assms(1)
[PROOF STATE]
proof (chain)
picking this:
A, n \<turnstile> [([\<^bold>\<not> p], i)]
[PROOF STEP]
have \<open>M, g, g i \<Turnstile> p\<close> for g
[PROOF STATE]
proof (prove)
using this:
A, n \<turnstile> [([\<^bold>\<not> p], i)]
goal (1 subgoal):
1. M, g, g i \<Turnstile> p
[PROOF STEP]
using soundness
[PROOF STATE]
proof (prove)
using this:
A, n \<turnstile> [([\<^bold>\<not> p], i)]
?A, ?n \<turnstile> ?branch \<Longrightarrow> \<exists>block\<in>set ?branch. \<exists>p. p on block \<and> \<not> ?M, ?g, ?w \<Turnstile> p
goal (1 subgoal):
1. M, g, g i \<Turnstile> p
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
M, ?g, ?g i \<Turnstile> p
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
M, ?g, ?g i \<Turnstile> p
[PROOF STEP]
have \<open>M, g(i := w), (g(i := w)) i \<Turnstile> p\<close>
[PROOF STATE]
proof (prove)
using this:
M, ?g, ?g i \<Turnstile> p
goal (1 subgoal):
1. M, g(i := w), (g(i := w)) i \<Turnstile> p
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
M, g(i := w), (g(i := w)) i \<Turnstile> p
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
M, g(i := w), (g(i := w)) i \<Turnstile> p
[PROOF STEP]
have \<open>M, g(i := w), w \<Turnstile> p\<close>
[PROOF STATE]
proof (prove)
using this:
M, g(i := w), (g(i := w)) i \<Turnstile> p
goal (1 subgoal):
1. M, g(i := w), w \<Turnstile> p
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
M, g(i := w), w \<Turnstile> p
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
M, g(i := w), w \<Turnstile> p
[PROOF STEP]
have \<open>M, g(i := g i), w \<Turnstile> p\<close>
[PROOF STATE]
proof (prove)
using this:
M, g(i := w), w \<Turnstile> p
goal (1 subgoal):
1. M, g(i := g i), w \<Turnstile> p
[PROOF STEP]
using assms(2) semantics_fresh
[PROOF STATE]
proof (prove)
using this:
M, g(i := w), w \<Turnstile> p
i \<notin> nominals p
?i \<notin> nominals ?p \<Longrightarrow> (?M, ?g, ?w \<Turnstile> ?p) = (?M, ?g(?i := ?v), ?w \<Turnstile> ?p)
goal (1 subgoal):
1. M, g(i := g i), w \<Turnstile> p
[PROOF STEP]
by metis
[PROOF STATE]
proof (state)
this:
M, g(i := g i), w \<Turnstile> p
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
M, g(i := g i), w \<Turnstile> p
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
M, g(i := g i), w \<Turnstile> p
goal (1 subgoal):
1. M, g, w \<Turnstile> p
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
M, g, w \<Turnstile> p
goal:
No subgoals!
[PROOF STEP]
qed |
using ArgParse
flagDebug=false; # Used to print extra information for debugging
argSettings = ArgParseSettings(description = string(
"This is a tool for systematically generating LSF jobs which write to log files. Below is an outline of the process.\n",
"\n",
"\n",
"\n",
"\n",
"\n STAGE 1: Generate summary files for each set of input data.\n",
"\n",
"\n",
"\n STAGE 1 INPUTS:\n",
"\nPath to protocol file (-p).\n",
"\n(Optional) Variables file supplied with the --vars (-r) option.\n",
"\n(Optional) Variables from lists file supplied with the --fvars (-f) option.\n",
"\n",
"\n",
"\n STAGE 1 OUTPUTS:\n",
"\nSummary files generated by expanding the variables in the protocol file.\n",
"\nText file listing paths to the generated summary files.\n",
"\n",
"\n",
"\n",
"\n",
"\n STAGE 2: Generate job files.\n",
"\n",
"\n",
"\n STAGE 2 INPUTS:\n",
"\nText file listing the of paths to the generated summary files. If stages 1 and 2 are run together the summary files from stage 1 will be used.\n",
"\n",
"\n",
"\n STAGE 2 OUTPUTS:\n",
"\nJob files generated from summary files.\n",
"\nText file listing paths to the generated job files.\n",
"\n",
"\n",
"\n",
"\n",
"\n STAGE 3: Submit jobs to the queuing system.\n",
"\n",
"\n",
"\n STAGE 3 INPUTS:\n",
"\nText file listing paths to the generated job files. If stages 2 and 3 are run together the job files from stage 2 will be used for stage 3.\n",
"\n",
"\n",
"\n STAGE 3 OUTPUTS:\n",
"\nLog files written by the job files.\n",
"\nStarndard output and error output from the queuing system as well as any output produced by running the commands contained in the job files.",
"\n",
"\n",
"\n",
));
sourcePath = dirname(Base.source_path()) * "/"; # Get the path to the jsub.jl file
####### INPUTS #######
## Default job header values
# jobID="LSFjob";
# numberOfCores=1;
# numberOfHosts=1;
# wallTime="8:00";
# queue="normal"
# grantCode="prepay-houlston"
# jobHeader = string(
# "#!/bin/bash\n
# #BSUB -J \"$jobID\"\n
# #BSUB -n $numberOfCores\n
# #BSUB -R \"span[hosts=$numberOfHosts]\"\n
# #BSUB -P $grantCode\n
# #BSUB -W $wallTime\n
# #BSUB -q $queue\n
# #BSUB -o output.$jobID\n
# #BSUB -e error.$jobID\n"
# )
######################
## Hard coded variables
# First non-whitespace string indicating the start of a comment line
const comStr="#" # Note: this is expected to be a string ("#") rather than a character ('#'). Changing the string (char) used to indicate comments may cause problems further down the line.
# const dlmVars='\t' # Column delimiter for files containing variables
# const dlmProtocol=' ' # Column delimiter for the protocol file
const dlmWhitespace=[' ','\t','\n','\v','\f','\r'] # The default whitespace characters used by split
# const verbose = false;
const adapt_quotation=true; # this should be the default to avoid nasty accidents
num_suppressed = [0];
## Tags
tagsExpand = Dict(
"header" => "#BSUB",
"tagSummaryName" => "#JSUB<summary-name>",
"tagSplit" => "#JGROUP",
"tagJobName" => "#JSUB<job-id>"
)
## Paths to bash functions {"function name" => "path to file containing function"}
commonFunctions = Dict(
"kill_this_job" => sourcePath * "common_functions/job_processing.sh",
"process_job" => sourcePath * "common_functions/job_processing.sh",
"version_control" => sourcePath * "common_functions/version_control.sh",
)
checkpointsDict = Dict(
"jcheck_file_not_empty" => sourcePath * "common_functions/jcheck_file_not_empty.sh",
"jcheck_checkpoint" => sourcePath * "common_functions/jcheck_checkpoint.sh",
)
bsubOptions = [
"-ar",
"-B",
"-H",
"-I", "-Ip", "-Is", # [-tty]
"-IS", "-ISp", "-ISs", "-IX", #[-tty]
"-K",
"-N",
"-r", "-rn",
"-ul",
"-a", "esub_application", # [([argument[,argument...]])]..."
"-app", # application_profile_name
"-b", # [[year:][month:]day:]hour:minute
"-C", # core_limit
"-c", # [hour:]minute[/host_name | /host_model]
"-clusters", # "all [~cluster_name] ... | cluster_name[+[pref_level]] ... [others[+[pref_level]]]"
"-cwd", # "current_working_directory"
"-D", # data_limit
"-E", # "pre_exec_command [arguments ...]"
"-Ep", # "post_exec_command [arguments ...]"
"-e", # error_file
"-eo", #error_file
"-ext", #[sched] "external_scheduler_options"
"-F", # file_limit
"-f", # local_file operator [remote_file]" ...
"-freq", # numberUnit
"-G", # user_group
"-g", # job_group_name
"-i", # input_file | -is input_file
"-J", # job_name | -J "job_name[index_list]%job_slot_limit"
"-Jd", # "job_description"
"-jsdl", # file_name | -jsdl_strict file_name
"-k", # "checkpoint_dir [init=initial_checkpoint_period][checkpoint_period] [method=method_name]"
"-L", # login_shell
"-Lp", # ls_project_name
"-M", # mem_limit
"-m", # "host_name[@cluster_name][[!] | +[pref_level]] | host_group[[!] | +[pref_level | compute_unit[[!] | +[pref_level]] ..."
"-mig", # migration_threshold
"-n", # min_proc[,max_proc]
"-network", # " network_res_req"
"-o", # output_file
"-oo", # output_file
"-outdir", # output_directory
"-P", # project_name
"-p", # process_limit
"-pack", # job_submission_file
"-Q", # "[exit_code ...] [EXCLUDE(exit_code ...)]"
"-q", # "queue_name ..."
"-R", # "res_req" [-R "res_req" ...]
"-rnc", # resize_notification_cmd
"-S", # stack_limit
"-s", # signal
"-sla", # service_class_name
"-sp", # priority
"-T", # thread_limit
"-t", # [[[year:]month:]day:]hour:minute
"-U", # reservation_ID
"-u", # mail_user
"-v", # swap_limit
"-W", # [hour:]minute[/host_name | /host_model]
"-We", # [hour:]minute[/host_name | /host_model]
"-w", # 'dependency_expression'
"-wa", # 'signal'
"-wt", # '[hour:]minute'
"-XF",
"-Zs",
"-h",
"-V",
];
#### FUNCTIONS FROM OTHER FIELS ####
include("./common_functions/jsub_common.jl")
####################################
######### MAIN #########
# function main(args)
## Argparse settings
@add_arg_table argSettings begin
"-p", "--protocol"
help = "Path to \"protocol\" file. This file contains commands to be run with variables to be substituted using values from files supplied with \"--vars (-r)\" and/or \"--fvars (-f)\" options."
"-v", "--verbose"
action = :store_true
help = "Verbose mode prints warnings and additional information to std out."
"-s", "--generate-summaries"
action = :store_true
help = "Generate summary files from protocol files using variables from files where supplied (see --help for --vars & --fvars options)."
"-j", "--generate-jobs"
action = :store_true
help = "Generate LSF job files from summary files."
"-u", "--list-summaries"
help = "Path to an text file listing summary file paths."
"-o", "--list-jobs"
help = "Path to an text file listing job file paths."
"-b", "--submit-jobs"
action = :store_true
help = "Submit LSF job files to the queue."
"-r", "--vars"
help = "Path to \"variables\" file. This file contains two columns - variable names and variable values. Matching variable names found in the \"protocol\" will be substituted with the corresponding values. Variable names may themselves contain variables which will be expanded if the variable name-value pair is found above (in this vars file)."
"-f", "--fvars"
help = "Path to \"file variables\" file. The purpose of this file is to declare variables that are to be substituted with values taken from a list in another file. This file consists of three columns - variable names, list file column and list file path."
"-w", "--suppress-warnings"
action = :store_true
help = "Do not print warnings to std out."
"-m", "--summary-prefix"
help = "Prefix to summary files."
"-n", "--process-name"
help = "Name string to be used in all files."
"-q", "--job-prefix"
help = "Prefix to job file paths."
"-t", "--timestamp-files"
action = :store_true
help = "Add timestamps to summary and job files."
"-a", "--portable"
help = "A directory to which copies of the job files as well as the submission script and relevant functions will be written. This is done so that the jobs can be easily copied over to and run on a system where jsub.jl is not to be run directly."
"-z", "--zip-jobs"
action = :store_true
help = "Create a zip file containing the jobs directory supplied to the \"--portable\" (-a) option for ease of copying."
"-c", "--common-header"
help = "String to be included at the start of every job file. Default value is \"#!/bin/bash\nset -eu\n\"."
"-l", "--header-from-file"
help = "Path to a file containing text to be included in every job file header. This is included after any string specified in the --common-header option."
"-y", "--no-version-control"
action = :store_true
help = "Do not call the bash function which does version control inside these jobs."
"-d", "--no-logging-timestamp"
action = :store_true
help = "When this flag is not present, timestamps of the format \"YYYYMMDD_HHMMSS\" are not added to the log file by job files running the process_job function."
"-k", "--keep-superfluous-quotes"
action = :store_true
help = "Do not remove superfluous quotes. For example, the string \"abc\"\"def\" will not be converted to \"abcdef\"."
"-g", "--fvars-delimiter"
help = "Delimiter used in the .fvars file. The default delmiter character is a tab ('\t'). The .fvars file is expected to contain three columns (1) variable name, (2) one-indexed column number, (3) path to a text file."
"-e", "--prefix-lsf-out"
help = "Prefix given to the output (*.output) and error (*.error) files produced when running an LSF job."
"-C", "--prefix-completed"
help = "Prefix to the *.completed files generated by the LSF job."
"-I", "--prefix-incomplete"
help = "Prefix to the *.incomplete files generated by the LSF job."
end
parsed_args = parse_args(argSettings) # the result is a Dict{String,Any}
## Set flag states
const flagVerbose = get_argument(parsed_args, "verbose", verbose=parsed_args["verbose"], optional=true, default=false);
const SUPPRESS_WARNINGS = get_argument(parsed_args, "suppress-warnings", verbose=flagVerbose, optional=true, default=false);
const delimiterFvars = get_argument(parsed_args, "fvars-delimiter", verbose=flagVerbose, optional=true, default='\t');
requiredStages = map_flags_sjb(parsed_args["generate-summaries"], parsed_args["generate-jobs"], parsed_args["submit-jobs"])
flagVerbose && print("\nInterpreted jsub arguments as requesting the following stages: ")
(flagVerbose && requiredStages[1]=='1') && print("1 ")
(flagVerbose && requiredStages[2]=='1') && print("2 ")
(flagVerbose && requiredStages[3]=='1') && print("3 ")
flagVerbose && print("\n\n")
## Initialise shared variables
pathSubmissionScript = string(sourcePath, "/common_functions/submit_lsf_jobs.sh");
pathSubmissionFunctions = string(sourcePath, "/common_functions/job_submission_functions.sh");
## TODO: Check input file format
# Check that pathFvars contains 3 delmiterFvars separated columns
## Declare functions used to run the three stages of summary file generation (1), job file generation (2) and job submission (3).
## STAGE 1
function run_stage1_(pathProtocol, pathVars, pathFvars; processName="", summaryPrefix="", pathSummariesList="", flagVerbose=false, adapt_quotation=true, delimiterFvars='\t', tagsExpand=Dict(), keepSuperfluousQuotes=false, timestampString="")
flagVerbose && println("\n - STAGE 1: Generating summary files using data from files supplied to the --protocol, --vars and --fvars options.");
## Determine what names to use for output summary files
# The following options are used to generate a "process name"
# --protocol "dir/protocolFile"
# --vars "dir/varsFile"
# --fvars "dir/fvarsFile"
# OR
# --process-name "processName"
if processName == ""
stringProtocol = remove_suffix(basename(pathProtocol), ".protocol");
stringVars = remove_suffix(basename(pathVars), ".vars");
stringFvars = remove_suffix(basename(pathFvars), ".fvars");
processName = stick_together(stick_together(stringProtocol, stringVars, "_"), stringFvars, "_");
end
flagDebug && println("Using \"$processName\" as the default recurring name but this may be overwritten by specific inputs or tags in the summary files.");
## Get path to summaries list file
if pathSummariesList == ""
pathSummariesList = string(summaryPrefix, processName, ".list-summaries");
end
## Read protocol, vars and fvars files and expand variables
namesVars = []; valuesVars = [];
if pathVars != ""
flagVerbose && println(string("Expanding variables line by line in data from \"--vars\" file: ", pathVars));
# Read .vars file # Extract arrays of variable names and variable values
namesVarsRaw, valuesVarsRaw = parse_varsfile_(pathVars, tagsExpand=tagsExpand);
# Expand variables in each row from .vars if they were assigned in a higher row (as though they are being assigned at the command line).
namesVars, valuesVars = expandinorder(namesVarsRaw, valuesVarsRaw, adapt_quotation=adapt_quotation);
end
namesFvars = []; infileColumnsFvars = []; filePathsFvars = [];
if pathFvars != ""
flagVerbose && println(string("Expanding variables in data from \"--fvars\" file using names and values from the \"--vars\" file: ", pathFvars));
namesFvars, infileColumnsFvars, filePathsFvars = parse_expandvars_fvarsfile_(pathFvars, namesVars, valuesVars; dlmFvars=delimiterFvars, verbose=false, adapt_quotation=adapt_quotation, tagsExpand=tagsExpand, keepSuperfluousQuotes=keepSuperfluousQuotes);
end
# Previously: # Read .protocol file (of 1 column ) and expand variables from .vars
# (flagVerbose && length(namesVars) > 0) && println("Expanding variables in protocol file using values from the --vars file.");
# arrProtExpVars, cmdRowsProt = parse_expandvars_protocol_(pathProtocol, namesVars, valuesVars, adapt_quotation=adapt_quotation, verbose=false, tagsExpand=tagsExpand, keepSuperfluousQuotes=keepSuperfluousQuotes);
dictListArr = Dict(); dictCmdLineIdxs = Dict();
if pathFvars != ""
println(string("Expanding variables from the --fvars file using values from the files listed in each row..."));
dictListArr, dictCmdLineIdxs = parse_expandvars_listfiles_(filePathsFvars, namesVars, valuesVars, delimiterFvars; verbose=false, adapt_quotation=adapt_quotation, tagsExpand=tagsExpand, keepSuperfluousQuotes=keepSuperfluousQuotes);
if length(keys(dictListArr)) != length(keys(dictCmdLineIdxs))
error("Numbers of command rows (", length(keys(dictListArr)), ") and command row indices (", length(keys(dictCmdLineIdxs)), ") in list file (", filePathsFvars, ") do not match.")
end
end
## Create summary files
# Use variable values from "list" files to create multiple summary file arrays from the single .protocol file array
flagVerbose && println("Creating summary arrays...");
arrArrExpFvars = [];
arrProt, cmdRowsProt = file2arrayofarrays_(pathProtocol, comStr; cols=1, delimiter=nothing, tagsExpand=tagsExpand);
if length(keys(dictListArr)) != 0 && length(keys(dictCmdLineIdxs)) != 0
(flagVerbose && length(namesVars) > 0) && println("Expanding variables in protocol file using values from both the --vars and --frvars files.");
arrArrExpFvars = protocol_to_array(arrProt, cmdRowsProt, namesVars, valuesVars, namesFvars, infileColumnsFvars, filePathsFvars, dictListArr, dictCmdLineIdxs ;
verbose=false, adapt_quotation=adapt_quotation, keepSuperfluousQuotes=keepSuperfluousQuotes
);
else
# Read .protocol file (of 1 column ) and expand variables from .vars
(flagVerbose && length(namesVars) > 0) && println("Expanding variables in protocol file using only values from the --vars file.");
push!(arrArrExpFvars, expand_inarrayofarrays(arrProt, cmdRowsProt, namesVars, valuesVars; verbose=false, adapt_quotation=adapt_quotation, keepSuperfluousQuotes=keepSuperfluousQuotes)); # If there is no data from list files, simply proceed using the data from the vars file
end
# Generate list of summary file paths.
summaryPaths = get_summary_names(arrArrExpFvars; tag="#JSUB<summary-name>", # if an entry with this tag is found in the protocol (arrArrExpFvars), the string following the tag will be used as the name
longName=processName, # Otherwise the string passed to longName will be used as the basis of the summary file name
prefix=summaryPrefix,
suffix=".summary",
timestamp=timestampString
);
# Take an expanded protocol in the form of an array of arrays and produce a summary file for each entry
outputSummaryPaths = create_summary_files_(arrArrExpFvars, summaryPaths; verbose=flagVerbose);
println(string("Writing list of summary files to: ", pathSummariesList));
writedlm(pathSummariesList, outputSummaryPaths);
return pathSummariesList
end
## STAGE 2
function run_stage2_(pathSummariesList, pathJobsList; jobFilePrefix="", flagVerbose=false, tagsExpand=Dict(), checkpointsDict=Dict(), commonFunctions=Dict(), tagCheckpoint="jcheck_", doJsubVersionControl=true, stringBoolFlagLoggingTimestamp=true, headerPrefix="#!/bin/bash", headerSuffix="", prefixOutputError="", prefixCompleted="", prefixIncomplete="", timestampString="")
flagVerbose && println("\n - STAGE 2: Using summary files to generate LSF job files.");
summaryPaths2 = readdlm(pathSummariesList); # Read paths to summary files from list file
summaryFilesData = map((x) -> file2arrayofarrays_(x, "#", cols=1, tagsExpand=tagsExpand), summaryPaths2 ); # Note: file2arrayofarrays_ returns a tuple of file contents (in an array) and line number indices (in an array)
flagVerbose && println("Importing bash functions from files...");
arrDictCheckpoints = map((x) -> identify_checkpoints(x[1], checkpointsDict; tagCheckpoint="jcheck_"), summaryFilesData );
arrBashFunctions = map((x) -> get_bash_functions(commonFunctions, x), arrDictCheckpoints);
flagVerbose && println("Splitting summary file contents into separate jobs...");
summaryArrDicts = map((x) -> split_summary(x[1]; tagSplit=tagsExpand["tagSplit"]), summaryFilesData);
## The job file name and the job ID passed to lsf's bsub command are determined by the contents of the array arrJobIDs from which values are passed to the create_jobs_from_summary_ function.
## Get job ID and check that the list is unique
jobIDTag = "#JSUB<job-id>";
flagVerbose && println("Getting job ID prefixes from summary file lines starting with: ", jobIDTag);
preArrJobIDs = map((x) -> get_taggedunique(x[1], jobIDTag), summaryFilesData );
# Create an array of summary file basenames concatenated with a padded index
replaceWith = map((x, y) -> stick_together(basename(remove_suffix(x, ".summary")), dec(y, length(dec(length(summaryPaths2)))), "_"),
summaryPaths2, collect(1:length(summaryPaths2))
);
flagDebug && (println("Replaceing blank jobID entries with the values from array replaceWith:"); println(replaceWith);)
# Use this array to replace any empty strings in the jobIDs array
arrJobIDs = replace_empty_strings(preArrJobIDs, replaceWith);
(length(arrJobIDs) != length(unique(arrJobIDs))) && error(" in run_stage2_ the array of job IDs contains non-qunique entries:\n", arrJobIDs);
flagDebug && (println("Final array of job IDs is arrJobIDs:"); println(arrJobIDs);)
## Create directories required by prefixes
(dirname(jobFilePrefix) != "") && mkpath(dirname(jobFilePrefix)); # Create directory for job files if it does not already exist
(dirname(prefixOutputError) != "") && mkpath(dirname(prefixOutputError)); # Create directory for .error and .output files
(dirname(prefixCompleted) != "") && mkpath(dirname(prefixCompleted)); # Create directory for .completed files
(dirname(prefixIncomplete) != "") && mkpath(dirname(prefixIncomplete)); # Create directory for .incomplete files
## Write job files
arrDictFilePaths = map((summaryFilePath, dictSummaries, jobID) -> create_jobs_from_summary_(summaryFilePath, dictSummaries, commonFunctions, checkpointsDict;
jobFilePrefix=jobFilePrefix, jobID=jobID, jobDate=timestampString,
doJsubVersionControl=doJsubVersionControl, stringBoolFlagLoggingTimestamp=stringBoolFlagLoggingTimestamp, headerPrefix=headerPrefix, headerSuffix=headerSuffix, verbose=flagVerbose, bsubOptions=bsubOptions, prefixOutputError=prefixOutputError, prefixCompleted=prefixCompleted, prefixIncomplete=prefixIncomplete
),
summaryPaths2, summaryArrDicts, arrJobIDs,
);
## Get an array of job priorities
arrDictPriorities = map((dictSummaries, dictFilePaths, jobID) -> get_priorities(dictSummaries, dictFilePaths), summaryArrDicts, arrDictFilePaths, arrJobIDs)
## Re-order job paths list according to job priority
arrArrOrderedJobPaths = map((ranksDict, pathsDict) -> order_by_dictionary(ranksDict, pathsDict), arrDictPriorities, arrDictFilePaths)
## Write ordered list of job paths to file
string2file_(pathJobsList, join(map(x -> join(x, '\n'), arrArrOrderedJobPaths), '\n') * "\n");
return pathJobsList
end
## STAGE 3
function run_stage3_(pathJobsList, pathPortable, pathSubmissionScript, pathSubmissionFunctions; flagVerbose=false, flagZip=false)
flagVerbose && println("\n - STAGE 3: Submitting LSF jobs.");
## Call the job submission script or copy it to the jobs directory
if (pathPortable == "")
SUPPRESS_WARNINGS ? arg2 = "suppress-warnings" : arg2 = "";
flagVerbose && println("Submitting jobs to LSF queuing system using...");
flagVerbose && println("bash $pathSubmissionScript $pathJobsList $arg2");
subRun = "";
if checkforlsf_()
try
run(`bash $pathSubmissionScript $pathJobsList $arg2`);
catch
println(subRun);
end
else
println("The LSF queuing system does not appear to be available on this system.")
# println("If this is incorrect consider amending line 423 of jsub.jl or submitting manually using:")
println("Finished running jsub stage 3 without submitting any jobs.")
end
## Point out that the zip option currently only works in combination with the portable option
if flagZip == true
(!SUPPRESS_WARNINGS) && println("WARNING (in jsub.jl): The --zip-jobs (-z) flag was supplied but an argument to the --portable (-a) option was not supplied. Currently the -z option only works together with -a so it will have no effect here.");
end
else
# Get the target directory from the the portable option or use default
pathPortableZip = get_zip_dir_path(pathPortable);
mkpath(pathPortable); # Create the portable directory if needed
# Parse list of job paths and copy them to the portable directory (if it's not the same directory)
flagVerbose && println(string("Copying file listing jobs (", basename(pathJobsList), ") to the directory: ", pathPortable));
cp(pathJobsList, string(pathPortable, "/", basename(pathJobsList)), remove_destination=true); # Copy list of jobs
arrJobPaths = split(readall(pathJobsList), '\n')
for jobFile in arrJobPaths
if !ispath(jobFile)
(!SUPPRESS_WARNINGS) && println("WARNING (in jsub.jl): The list file $pathJobsList contains a non-valid path: $jobFile");
elseif (dirname(jobFile) != pathPortable)
flagVerbose && println(string("Copying job file \"$jobFile\" to directory specificed by the --portable (-a) option: ", pathPortable));
cp(jobFile, string(pathPortable, "/", basename(jobFile)), remove_destination=true);
end
end
flagVerbose && println(string("Writing a copy of the submission script and functions file to the job file directory: ", pathPortable));
# println("pathSubmissionScript = ", pathSubmissionScript);
cp(pathSubmissionScript, string(pathPortable, "/", basename(pathSubmissionScript)), remove_destination=true);
# println("pathSubmissionFunctions = ", pathSubmissionFunctions);
cp(pathSubmissionFunctions, string(pathPortable, "/", basename(pathSubmissionFunctions)), remove_destination=true);
flagVerbose && println(string("The jobs can be submitted to the queuing system by running the shell script: ", basename(pathSubmissionScript)));
## Zip jobs directory if requested
if flagZip == true
flagVerbose && println("Zipping jobs directory: ", pathPortable);
flagVerbose && println(" into file: ", pathPortableZip);
flagVerbose ? zipVerbose = "v" : zipVerbose = ""
subZip = "";
try
subZip = run(`tar -zc$[zipVerbose]f $pathPortableZip $pathPortable`);
catch
println(subZip);
end
end
end
flagVerbose && println("");
end
## RUN ##
if requiredStages[1] == '1'
flagDebug && println(" --- Starting STAGE 1.\n")
pathExistingSummariesList = run_stage1_(
get_argument(parsed_args, "protocol"; verbose=flagVerbose, optional=(requiredStages[1]=='0'), default=""),
get_argument(parsed_args, "vars"; verbose=flagVerbose, optional=true, default=""),
get_argument(parsed_args, "fvars"; verbose=flagVerbose, optional=true, default="");
processName=get_argument(parsed_args, "process-name"; verbose=flagVerbose, optional=true, default=""),
summaryPrefix=get_argument(parsed_args, "summary-prefix", verbose=flagVerbose, optional=true, default=""),
pathSummariesList=get_argument(parsed_args, "list-summaries"; verbose=flagVerbose, optional=true, default=""),
keepSuperfluousQuotes=get_argument(parsed_args, "keep-superfluous-quotes", verbose=flagVerbose, optional=true, default=false),
flagVerbose=flagVerbose, adapt_quotation=adapt_quotation, delimiterFvars=delimiterFvars, tagsExpand=tagsExpand,
timestampString=( (get_argument(parsed_args, "timestamp-files", verbose=flagVerbose, optional=true, default=false) ? get_timestamp_(nothing) : "") ), # Get summary timestamp string,
);
flagDebug && println(" --- Completed STAGE 1. Produced summary list file: $pathExistingSummariesList\n")
elseif requiredStages[2] == '1'
flagDebug && println("Not running stage 1, so the path to *.list-summaries has to come from an argument.")
pathExistingSummariesList = get_argument(parsed_args, "list-summaries"; verbose=flagVerbose, optional=(requiredStages[2] != '1'), default=""); # Optional if jobs are not being generated from summaries
end
if requiredStages[2] == '1'
pathCommonHeader = get_argument(parsed_args, "header-from-file"; verbose=flagVerbose, optional=true, default="");
inputJobsPrefix = get_argument(parsed_args, "job-prefix", verbose=flagVerbose, optional=true, default="")
flagDebug && println(" --- Starting STAGE 2.\n")
pathExistingJobsList = run_stage2_(
pathExistingSummariesList,
string(inputJobsPrefix, basename(remove_suffix(pathExistingSummariesList, ".list-summaries")), ".list-jobs"); # Determine path to the *.list-jobs file
flagVerbose=flagVerbose, tagsExpand=tagsExpand, checkpointsDict=checkpointsDict, commonFunctions=commonFunctions,
jobFilePrefix=inputJobsPrefix,
doJsubVersionControl=( get_argument(parsed_args, "no-version-control"; verbose=flagVerbose, optional=true, default=false) ? "false" : "true" ),
stringBoolFlagLoggingTimestamp=( get_argument(parsed_args, "no-logging-timestamp"; verbose=flagVerbose, optional=true, default=false) ? "false" : "true" ), # Indicates if bash scripts should create a timestamp in the logging file, default is "true" (this is a string because it is written into a bash script)
headerPrefix=get_argument(parsed_args, "common-header"; verbose=flagVerbose, optional=true, default="#!/bin/bash\nset -eu\n"),
prefixOutputError=get_argument(parsed_args, "prefix-lsf-out", verbose=flagVerbose, optional=true, default=""), # Get prefix for *.error and *.output files (written by the LSF job)
prefixCompleted=get_argument(parsed_args, "prefix-completed", verbose=flagVerbose, optional=true, default=""),
prefixIncomplete=get_argument(parsed_args, "prefix-incomplete", verbose=flagVerbose, optional=true, default=""),
timestampString=(get_argument(parsed_args, "timestamp-files", verbose=flagVerbose, optional=true, default=false) ? get_timestamp_(nothing) : ""), # Get job timestamp string
headerSuffix=(pathCommonHeader == "" ? "" : readall(pathCommonHeader)), # String from file to be added to the header (after common-header string) of every job file
)
flagDebug && println(" --- Completed STAGE 2. Produced jobs list file: $pathExistingJobsList\n")
elseif requiredStages[3] == '1'
flagDebug && println("Not running stage 2, so the path to *.list-jobs has to come from an argument.")
pathExistingJobsList = get_argument(parsed_args, "list-jobs"; verbose=flagVerbose, optional=(requiredStages[3] != '1'), default=""); # Optional if jobs are not being submitted
end
if requiredStages[3] == '1'
flagDebug && println(" --- Starting STAGE 3.\n")
run_stage3_(
pathExistingJobsList,
get_argument(parsed_args, "portable", verbose=flagVerbose, optional=true, default=""),
pathSubmissionScript,
pathSubmissionFunctions;
flagVerbose=flagVerbose,
flagZip=get_argument(parsed_args, "zip-jobs"; verbose=flagVerbose, optional=true, default=false),
)
flagDebug && println(" --- Completed STAGE 3.\n")
end
#########
# Report if there were any suppressed warnings
if num_suppressed[1] > 0
println("Suppressed ", num_suppressed[1], " warnings.");
end
########################
# EOF
|
data.path<-file.path("C:","MV","SMS","NS_63-10-OP")
scenario<-"HCR_stoc_rec_final"
scenario.dir<-file.path(data.path,scenario)
do.save<-F
spNames<-c('COD', 'WHG', 'HAD', 'POK', 'HER', 'SAN', 'NOR', 'SPR', 'PLE', 'SOL')
allnames<-c(c('yield', 'CWsum', 'Fbar', 'SSB', 'TSB', 'recruit', 'Species.n', 'iteration'),spNames)
if (do.save) {
setwd(scenario.dir)
condensed<-read.table(file.path(data.path,"HCR-fin1_stoc_rec","OP_Fcombinations.out"),header=FALSE)
dimnames(condensed)[[2]]<-allnames
a<-read.table(file.path(data.path,"HCR-fin2_stoc_rec","OP_Fcombinations.out"),header=FALSE)
dimnames(a)[[2]]<-allnames
condensed<-rbind(condensed,a)
a<-read.table(file.path(data.path,"HCR-fin3_stoc_rec","OP_Fcombinations.out"),header=FALSE)
dimnames(a)[[2]]<-allnames
condensed<-rbind(condensed,a)
a<-read.table(file.path(data.path,"HCR-fin4_stoc_rec","OP_Fcombinations.out"),header=FALSE)
dimnames(a)[[2]]<-allnames
condensed<-rbind(condensed,a)
a<-read.table(file.path(data.path,"HCR-fin5_stoc_rec","OP_Fcombinations.out"),header=FALSE)
dimnames(a)[[2]]<-allnames
condensed<-rbind(condensed,a)
rm(a)
condensed<-droplevels(subset(condensed,Species.n<25))
save(condensed, file =file.path(scenario.dir, "condensed.RData"))
} else load(file =file.path(scenario.dir, "condensed.RData"))
setwd(data.path)
a<-condensed
rm(condensed)
z <- sapply(ls(), function(x) object.size(get(x))) ;as.matrix(rev(sort(z))[1:10])
source(file.path(prog.path,"FMSY-matrix.R"))
table.MSY<-function(a){
aa<-tapply(a$yield,list(a$Species.n,a$Fround),median)
dimnames(aa)[[1]]<-sp.names[as.numeric(dimnames(aa)[[1]])]
cat('Median MSY (1000 tonnes)\n')
print(round(aa/1000,0))
aa2<-tapply(a$yield,list(a$Species.n,a$Fround),sd)/tapply(a$yield,list(a$Species.n,a$Fround),mean)
dimnames(aa2)[[1]]<-dimnames(aa)[[1]]
MSY<-apply(aa,1,max,na.rm=T)
ab<-aa/rep(MSY,times=dim(aa)[2])
cat('\n')
aa<-tapply(a$SSB,list(a$Species.n,a$Fround),median)
dimnames(aa)[[1]]<-sp.names[as.numeric(dimnames(aa)[[1]])]
cat('Median SSB (1000 tonnes)\n')
print(round(aa/1000))
}
table.MSY(a)
a<-droplevels(subset(a,COD<0.66))
table.MSY(a)
a<-droplevels(subset(a,POK>0.4))
table.MSY(a)
|
import StringIO
import copy
import collections
import base64
import gridfs
import hashlib
import tempfile
import json
import os
import numpy as np
import bson.json_util as json_util
from bson.objectid import ObjectId
import cPickle
#import tabular as tb
from PIL import Image
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.autoreload
from tornado.options import define, options
from yamutils.mongo import SONify
import pymongo as pm
import zmq
define("port", default=9919, help="run on the given port", type=int)
#FEATURE_PORT = 38675
#SOCKET_CONTEXT = zmq.Context()
#FEATURE_SOCKET = SOCKET_CONTEXT.socket(zmq.PAIR)
#FEATURE_SOCKET.bind("tcp://*:%d" % FEATURE_PORT)
print('ready to connect')
#REGRESSORS = cPickle.load(open('/om/user/yamins/morph_regressors.pkl'))
class App(tornado.web.Application):
"""
Tornado app which serves the API.
"""
def __init__(self):
handlers = [ (r"/savedecision",SaveDecisionHandler),
(r"/dbquery", DBQueryHandler)]
settings = dict(debug=True)
tornado.web.Application.__init__(self, handlers, **settings)
class BaseHandler(tornado.web.RequestHandler):
def get(self):
args = self.request.arguments
for k in args.keys():
args[k] = args[k][0]
args = dict([(str(x),y) for (x,y) in args.items()])
callback = args.pop('callback', None)
resp = jsonize(self.get_response(args))
if callback:
self.write(callback + '(')
self.write(json.dumps(resp, default=json_util.default))
if callback:
self.write(')')
print('sending!')
self.finish()
PERM = None
PORT = int(os.environ.get('SKETCHLOOP_MONGO_PORT', 29202))
CONN = pm.MongoClient(port=PORT)
DB_DICT = {}
FS_DICT = {}
def isstring(x):
try:
x + ""
except:
return False
else:
return True
class DBQueryHandler(BaseHandler):
def get_response(self, args):
global CONN
dbname = args['dbname']
colname = args['colname']
db = CONN[dbname]
addfiles = bool(int(args.get('addfiles', '1')))
if addfiles:
coll = db[colname + '.files']
else:
coll = db[colname]
querySequence = json.loads(args['query'])
if isstring(querySequence):
querySequence = [querySequence]
querySequenceParsed = []
for q in querySequence:
if isstring(q):
action = q
posargs = ()
kwargs = {}
elif len(q) == 1:
action = q[0]
posargs = ()
kwargs = {}
elif len(q) == 2:
action = q[0]
if hasattr(q[1], "keys"):
kwargs = q[1]
posargs = ()
else:
posargs = tuple(q[1])
kwargs = {}
elif len(q) == 3:
action = q[0]
posargs = q[1]
kwargs = q[2]
assert action in ['find','find_one','group','skip',
'limit','sort','count','distinct'], action
querySequenceParsed.append((action, posargs, kwargs))
obj = coll
for action, posargs, kwargs in querySequenceParsed:
obj = getattr(obj, action)(*posargs, **kwargs)
if isinstance(obj, pm.cursor.Cursor):
result = list(obj)
else:
result = obj
resp = {"result": result}
return resp
class SaveDecisionHandler(BaseHandler):
def get_response(self,args):
return save_decision_only(self,args)
def save_decision_only(handler,args):
imhash = hashlib.sha1(json.dumps(args)).hexdigest()
#print("imhash", imhash)
filestr = 'filestr'
global CONN
print("args",args)
dbname = args['dbname']
colname = args['colname']
global DB_DICT
if dbname not in DB_DICT:
DB_DICT[dbname] = CONN[dbname]
db = DB_DICT[dbname]
#print("db",db)
global FS_DICT
if (dbname, colname) not in FS_DICT:
FS_DICT[(dbname, colname)] = gridfs.GridFS(db, colname)
fs = FS_DICT[(dbname, colname)]
_id = fs.put(filestr, **args) # actually put file in db
def jsonize(x):
try:
json.dumps(x)
except TypeError:
return SONify(x)
else:
return x
def main():
"""
function which starts up the tornado IO loop and the app.
"""
tornado.options.parse_command_line()
ioloop = tornado.ioloop.IOLoop.instance()
http_server = tornado.httpserver.HTTPServer(App(), max_header_size=10000000)
http_server.listen(options.port)
tornado.autoreload.start()
ioloop.start()
if __name__ == "__main__":
main()
|
From stdpp Require Import fin_maps gmap.
From iris.proofmode Require Import tactics.
From aneris.prelude Require Import collect.
From aneris.aneris_lang Require Import aneris_lang network resources.
From aneris.aneris_lang.state_interp Require Import state_interp_def.
From RecordUpdate Require Import RecordSet.
From aneris.algebra Require Import disj_gsets.
From iris.algebra Require Import auth.
Set Default Proof Using "Type".
Import uPred.
Import RecordSetNotations.
Section state_interpretation.
Context `{!anerisG Mdl Σ}.
Lemma messages_resource_coh_init B :
own (A:=authUR socket_address_groupUR) aneris_socket_address_group_name
(◯ (DGSets B)) -∗
messages_resource_coh (gset_to_gmap (∅, ∅) B).
Proof.
rewrite /messages_resource_coh messages_sent_init.
iIntros "Hown".
iSplitL; [ |].
{ by rewrite dom_gset_to_gmap. }
iExists _.
iSplit; [done|].
iSplit; by iApply big_sepS_empty.
Qed.
(* TODO: Repeated lemma - Why is anerisG needed over anerisPreG? *)
Lemma socket_address_group_own_subseteq
γ (sags sags' : gset socket_address_group) :
sags' ⊆ sags →
own (A:=(authR socket_address_groupUR)) γ
(◯ (DGSets sags)) -∗
own (A:=(authR socket_address_groupUR)) γ
(◯ (DGSets sags')).
Proof.
iIntros (Hle) "Hsags".
apply subseteq_disjoint_union_L in Hle.
destruct Hle as [Z [-> Hdisj]].
setoid_rewrite <-disj_gsets_op_union.
iDestruct "Hsags" as "[H1 H2]".
iFrame.
Qed.
Lemma messages_resource_coh_socket_address_group_own
(sag : socket_address_group) mh :
sag ∈ dom mh →
messages_resource_coh mh -∗
messages_resource_coh mh ∗
socket_address_group_own sag.
Proof.
iIntros (Hin) "[#H Hrest]".
rewrite /socket_address_group_own.
iPoseProof (socket_address_group_own_subseteq _ _ {[sag]} with "H") as "$";
[set_solver|].
rewrite /messages_resource_coh. iFrame "H".
done.
Qed.
Lemma messages_resource_coh_send mh sagT sagR R T msg msg' ϕ :
mh !! sagT = Some (R, T) →
m_sender msg ∈ sagT →
messages_addresses_coh mh →
msg ≡g{sagT, sagR} msg' →
m_destination msg ∈g sagR -∗
sagR ⤇* ϕ -∗
messages_resource_coh mh -∗
ϕ msg' -∗
messages_resource_coh (<[sagT:=(R, {[msg]} ∪ T)]> mh).
Proof.
rewrite /messages_resource_coh /=.
iIntros (Hmh HsagT Hmcoh Hmeq) "[%HsagR _] #HΦ [#Hown Hcoh] Hm".
iAssert (socket_address_group_own sagT) as "HownT".
{
rewrite -(insert_id mh sagT (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
destruct Hmcoh as (Halldisj & Hne & Hmcoh).
iDestruct "Hcoh" as (ms Hle) "[#HcohT Hcoh]".
iDestruct (socket_interp_own with "HΦ") as "#Hown'".
iSplitR.
{
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iApply own_op.
iFrame "Hown HownT".
}
iExists ({[msg]} ∪ ms).
iSplitR.
{
iPureIntro.
rewrite messages_sent_insert.
rewrite -union_assoc_L.
rewrite -(messages_sent_split sagT R T mh Hmh).
set_solver.
}
iSplitR.
{
rewrite messages_sent_insert.
rewrite -union_assoc_L.
rewrite -(messages_sent_split sagT R T mh Hmh).
rewrite !big_sepS_forall.
iIntros (m' Hin).
setoid_rewrite elem_of_union in Hin.
destruct Hin as [Hin|Hin].
{
assert (m' = msg) as <- by set_solver.
iExists sagT, sagR, m'.
iSplit; [iSplit; [|iPureIntro; set_solver] |].
{ iPureIntro. apply message_group_equiv_refl.
- by destruct Hmeq as (Hmin & _).
- done. }
iFrame "HownT Hown'".
}
iDestruct ("HcohT" $!(m') (Hin))
as (sagT' sagR' m'' [Hmeq' Hmin]) "[HcohT' HcohT'']".
iExists sagT', sagR', m''.
apply (elem_of_union_r m'' {[msg]} ms) in Hmin.
iFrame "#".
iSplit; [done|]. iPureIntro. done.
}
destruct (decide (msg ∈ ms)).
{
assert ({[msg]} ∪ ms = ms) as -> by set_solver. iClear "Hm".
assert (ms ⊆ {[msg]} ∪ messages_sent mh) by set_solver.
rewrite /message_received.
rewrite !messages_received_insert.
iApply (big_sepS_mono with "Hcoh").
iIntros (x Hin') "Hcoh".
iDestruct "Hcoh" as (sagT' sagR' Φ Hin'') "[#HΦ' [HownT' Hcoh]]".
subst.
iExists _, _, _.
iFrame "HΦ'".
iSplit.
{ iPureIntro. set_solver. }
iFrame "HownT'".
iDestruct "Hcoh" as "[Hcoh | Hcoh]".
{ by iLeft. }
iRight.
iDestruct "Hcoh" as %(m' & Heq & Hrecv).
iExists m'. iSplit; [done|].
iPureIntro.
rewrite -(insert_id mh sagT (R,T) Hmh) in Hrecv.
apply message_received_insert in Hrecv.
set_solver.
}
rewrite big_sepS_union; [|set_solver].
rewrite big_sepS_singleton.
iSplitL "Hm".
+ iExists _,_, _. iFrame "HΦ".
iFrame "HownT".
iSplit.
{ iPureIntro. set_solver. }
iLeft. iExists _.
iSplitR "Hm"; [done | iApply "Hm"].
+ iApply (big_sepS_mono with "Hcoh").
iIntros (x Hin') "Hcoh".
iDestruct "Hcoh" as (sagT' sagR' Φ Hin'') "[#HΦ' [HownT Hcoh]]".
subst.
iExists _,_, _.
iFrame "HΦ'". iFrame "HownT".
iSplit.
{ iPureIntro. set_solver. }
iDestruct "Hcoh" as "[Hcoh | Hcoh]".
{ by iLeft. }
iRight.
iDestruct "Hcoh" as %(m' & Heq & Hrecv).
iExists m'. iSplit; [done|].
iPureIntro.
rewrite -(insert_id mh sagT (R,T) Hmh) in Hrecv.
rewrite message_received_insert.
by apply message_received_insert in Hrecv.
Qed.
Lemma messages_resource_coh_send_duplicate mh sagT sagR R T msg :
mh !! sagT = Some (R, T) →
m_sender msg ∈ sagT →
messages_addresses_coh mh →
set_Exists (λ m, m ≡g{sagT, sagR} msg) T →
m_destination msg ∈g sagR -∗
messages_resource_coh mh -∗
messages_resource_coh (<[sagT:=(R, {[msg]} ∪ T)]> mh).
Proof.
rewrite /messages_resource_coh /=.
iIntros (Hmh HsagT Hmcoh Hexists) "[%HsagR #Hown'] [#Hown Hcoh]".
iAssert (socket_address_group_own sagT) as "HownT".
{
rewrite -(insert_id mh sagT (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
destruct Hmcoh as (Halldisj & Hne & Hmcoh).
iDestruct "Hcoh" as (ms Hle) "[#HcohT Hcoh]".
iSplitR.
{
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iApply own_op.
iFrame "Hown HownT".
}
iExists ms.
rewrite -{3}(insert_id mh sagT (R, T)); [|set_solver].
rewrite /message_received.
rewrite !messages_received_insert.
iFrame.
iSplitR.
{
iPureIntro.
rewrite messages_sent_insert.
rewrite -union_assoc_L.
rewrite -(messages_sent_split sagT R T mh Hmh); set_solver.
}
rewrite messages_sent_insert.
rewrite -union_assoc_L.
rewrite -(messages_sent_split sagT R T mh Hmh).
destruct (decide (msg ∈ messages_sent mh)) as [Hin|Hnin].
{ assert ({[msg]} ∪ messages_sent mh = messages_sent mh) as Heq by set_solver.
rewrite Heq. done. }
rewrite big_sepS_union; [|set_solver].
iFrame "HcohT".
rewrite big_sepS_singleton.
destruct Hexists as [m' [Hin Hmeq]].
assert (m_destination m' ∈ sagR).
{ by destruct Hmeq as (_ & _ & H' & _). }
rewrite -{2}(insert_id mh sagT (R,T)); [|set_solver].
rewrite messages_sent_insert.
iDestruct (big_sepS_elem_of_acc _ _ m' with "HcohT") as "[Hmsg _]";
[set_solver|].
iDestruct "Hmsg" as (sagT' sagR' m'' [Hmeq' Hmin]) "[HownT' HownR']".
iExists sagT', sagR', m''. iFrame "HownT' HownR'". iSplit;[|done].
iAssert (socket_address_groups_own
({[sagT]} ∪ {[sagR]} ∪ {[sagT']} ∪ {[sagR']})) as "H".
{
iApply socket_address_groups_own_union. iFrame "HownR'".
iApply socket_address_groups_own_union. iFrame "HownT'".
iApply socket_address_groups_own_union. iFrame "Hown' HownT".
}
iDestruct (own_valid with "H") as %Hvalid.
setoid_rewrite auth_frag_valid in Hvalid.
setoid_rewrite disj_gsets_valid in Hvalid.
iPureIntro.
pose proof (message_group_equiv_trans _ sagT sagT' sagR sagR' msg m' m'' Hvalid) as (<- & <- & Hmeq'');
[set_solver..| | | ].
- apply message_group_equiv_symmetry; try done.
by destruct Hmeq as (H' & _).
- apply Hmeq'.
- done.
Qed.
Lemma message_received_delete m mh sag1 sag2 :
messages_addresses_coh mh →
m_destination m ∈ sag1 →
sag1 ∈ dom mh →
sag2 ∈ dom mh →
sag1 ≠ sag2 →
message_received m mh →
message_received m (delete sag2 mh).
Proof.
rewrite /message_received.
rewrite !elem_of_messages_received.
intros (Hdisj & Hne & Hcoh) Hdest Hsag1 Hsag2 Hrecv
[sag [[R T] [Hlookup Hin]]].
assert (sag = sag1) as ->.
{
eapply elem_of_all_disjoint_eq; eauto.
apply elem_of_dom. eexists _. set_solver.
eapply Hcoh. eauto. eauto.
}
eexists sag1, (R,T).
rewrite lookup_delete_ne; last done.
auto.
Qed.
(* TODO: Clean up these lemmas and proofs *)
Lemma messages_resource_coh_receive_in sagR sagT R T R' T' m mh :
mh !! sagR = Some (R, T) →
mh !! sagT = Some (R',T') →
set_Forall (λ m', ¬ (m ≡g{sagT,sagR} m')) R →
m ∈ T' →
messages_addresses_coh mh →
m_destination m ∈g sagR -∗
m_sender m ∈g sagT -∗
messages_resource_coh mh -∗
messages_resource_coh (<[sagR:=({[m]} ∪ R, T)]> mh) ∗
∃ φ m', ⌜m ≡g{sagT,sagR} m'⌝ ∗ sagR ⤇* φ ∗ ▷ φ m'.
Proof.
iIntros (Hmha Hmhb HmR HmT' (Hdisj & Hne & Hmacoh)).
iIntros "[%Hmdest _] [%Hmsend _]".
iDestruct 1 as "[#Hown Hrcoh]". rewrite /messages_resource_coh.
iDestruct "Hrcoh" as (ms Hle) "[#HrcohT Hrcoh]".
iAssert (⌜∃ m', m ≡g{sagT,sagR} m' ∧ m' ∈ ms⌝%I) as %(m' & Hmeq & Hmin).
{
assert (messages_sent mh = messages_sent (<[sagT:=(R', T')]>mh)) as Heq.
{ apply insert_id in Hmhb as Heq. by rewrite {1} Heq. }
rewrite Heq messages_sent_insert.
assert (T' = {[m]} ∪ T') as HTeq by set_solver.
rewrite HTeq.
iDestruct (big_sepS_elem_of_acc _ _ m with "HrcohT")
as "[Hm _]"; [set_solver|].
iDestruct "Hm" as (sagT' sagR' m' [Hmeq Hmin]) "[HownT' HownR']".
assert (sagR ∈ dom mh).
{ apply elem_of_dom. eexists _. set_solver. }
iAssert (socket_address_group_own sagT) as "HownT".
{
rewrite -(insert_id mh sagT (R',T')); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iAssert (socket_address_group_own sagR) as "HownR".
{
rewrite -(insert_id mh sagR (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iAssert (socket_address_groups_own
({[sagT]} ∪ {[sagR]} ∪ {[sagT']} ∪ {[sagR']})) as "Hown'".
{
iApply socket_address_groups_own_union. iFrame "HownR'".
iApply socket_address_groups_own_union. iFrame "HownT'".
iApply socket_address_groups_own_union. iFrame "HownR HownT".
}
iDestruct (own_valid with "Hown'") as %Hvalid.
setoid_rewrite auth_frag_valid in Hvalid.
setoid_rewrite disj_gsets_valid in Hvalid.
assert (sagT = sagT') as <-.
{ eapply (message_group_equiv_dest_eq _
sagT sagT' sagR sagR' m m' Hvalid); try set_solver. }
assert (sagR = sagR') as <-.
{ eapply (message_group_equiv_dest_eq _
sagT sagT sagR sagR' m m' Hvalid); try set_solver. }
iPureIntro.
eexists m'.
done.
}
assert (ms = {[m']} ∪ (ms ∖ {[m']})) as Hms.
{ rewrite -union_difference_L. eauto. set_solver. }
rewrite Hms.
rewrite big_sepS_union; [|set_solver]. rewrite big_sepS_singleton.
iDestruct "Hrcoh" as "[Hm' Hrcoh]".
iDestruct "Hm'" as (sagT' sagR' Φ Hdest) "[#HΦ [#HownT' Hm]]".
assert (sagR ∈ dom mh) as HsagR.
{ rewrite elem_of_dom. eexists _. set_solver. }
iDestruct "Hm" as "[Hm | Hm]"; last first.
{
iDestruct "Hm" as %(m'' & Hmeq' & Hrecv).
iAssert (socket_address_group_own sagT) as "HownT".
{
rewrite -(insert_id mh sagT (R',T')); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iAssert (socket_address_group_own sagR) as "HownR".
{
rewrite -(insert_id mh sagR (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iDestruct (socket_interp_own with "HΦ") as "HownR'".
iAssert (socket_address_groups_own
({[sagT]} ∪ {[sagT']} ∪ {[sagR]} ∪ {[sagR']})) as "Hown'".
{
iApply socket_address_groups_own_union. iFrame "HownR'".
iApply socket_address_groups_own_union. iFrame "HownR".
iApply socket_address_groups_own_union. iFrame "HownT' HownT".
}
iDestruct (own_valid with "Hown'") as %Hvalid.
setoid_rewrite auth_frag_valid in Hvalid.
setoid_rewrite disj_gsets_valid in Hvalid.
assert (m ≡g{sagT, sagR} m'') as Hmeq''.
{ eapply (message_group_equiv_trans _ sagT sagT' sagR sagR' m m' m''); eauto.
set_solver. set_solver. set_solver. set_solver. }
assert (m_destination m'' ∈ sagR).
{ by eapply message_group_equiv_dest. }
assert (m'' ∈ R).
{ eapply messages_received_in; eauto.
by rewrite /messages_addresses_coh. }
assert (¬ m ≡g{sagT,sagR} m'').
{ by apply HmR. }
done.
}
iDestruct "Hm" as (m'' Hmeq') "Hm'".
iAssert (socket_address_group_own sagT) as "HownT".
{
rewrite -(insert_id mh sagT (R',T')); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iAssert (socket_address_group_own sagR) as "HownR".
{
rewrite -(insert_id mh sagR (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iDestruct (socket_interp_own with "HΦ") as "HownR'".
iAssert (socket_address_groups_own
({[sagT]} ∪ {[sagR]} ∪ {[sagT']} ∪ {[sagR']})) as "Hown'''".
{
iApply socket_address_groups_own_union. iFrame "HownR'".
iApply socket_address_groups_own_union. iFrame "HownT'".
iApply socket_address_groups_own_union. iFrame "HownT HownR".
}
iDestruct (own_valid with "Hown'''") as %Hvalid.
setoid_rewrite auth_frag_valid in Hvalid.
setoid_rewrite disj_gsets_valid in Hvalid.
assert (sagR' = sagR) as ->.
{
symmetry.
eapply (message_group_equiv_trans _ sagT sagT' sagR sagR' m m' m'' Hvalid);
set_solver. }
iSplitR "Hm'"; last first.
{
iExists Φ, m''. iFrame "HΦ Hm'". iPureIntro.
eapply message_group_equiv_trans; eauto.
set_solver. set_solver. set_solver. set_solver.
}
iSplitR.
{
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite !auth_frag_op. iSplit.
iApply "HownR".
iFrame "Hown".
}
iExists ms.
iSplitR.
{
iPureIntro.
rewrite -(insert_id mh sagR (R,T) Hmha) in Hle.
rewrite messages_sent_insert.
rewrite messages_sent_insert in Hle.
done.
}
iSplitR.
{
rewrite -{2}(insert_id mh sagR (R,T) Hmha).
rewrite !messages_sent_insert.
rewrite -Hms.
iApply "HrcohT".
}
rewrite {3} Hms.
rewrite big_sepS_union; last set_solver.
rewrite big_sepS_singleton.
iSplitR.
{ iExists sagT, sagR, Φ.
iSplit; [iPureIntro; set_solver | ].
iFrame "HΦ".
iFrame "HownT".
iRight.
iExists m.
iPureIntro.
split; [by apply message_group_equiv_symmetry | ].
rewrite message_received_insert.
set_solver.
}
iApply (big_sepS_impl with "Hrcoh").
iIntros "!>" (m''' Hmin') "Hrcoh".
iDestruct "Hrcoh" as (sagT'' sagR' Φ' Hmin'') "[#HΦ' [#HownT'' H]]".
iExists sagT'', sagR', Φ'.
iFrame "#".
iSplit; [done|].
iDestruct "H" as "[H|H]"; [ by iFrame | iRight ].
iDestruct "H" as %(m'''' & Hmeq''' & Hrecv).
assert (m_destination m'''' ∈ sagR').
{ eapply message_group_equiv_dest; eauto. }
pose proof Hrecv as Hrecv'.
rewrite /message_received in Hrecv'.
setoid_rewrite elem_of_messages_received in Hrecv'.
destruct Hrecv' as (sag & [R'' T''] & Hlookup & Hin).
simpl in *.
iAssert (socket_address_group_own sag) as "Hown''''".
{
rewrite -(insert_id mh sag (R'',T'')); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iDestruct (socket_interp_own with "HΦ'") as "Hown'''''".
iDestruct (own_op with "[Hown'''' Hown''''']") as "Hown''''''".
{ iSplit; [ iApply "Hown''''" | iApply "Hown'''''" ]. }
rewrite -auth_frag_op.
iDestruct (own_valid with "Hown''''''") as %Hvalid'.
setoid_rewrite auth_frag_valid in Hvalid'.
setoid_rewrite disj_gsets_valid in Hvalid'.
iPureIntro. exists m''''.
split; [done|].
rewrite message_received_insert.
destruct (decide (sagR' = sagR)) as [->|Hneq]; [left|right].
{ apply elem_of_union_r. by eapply messages_received_in. }
rewrite /message_received.
rewrite !elem_of_messages_received.
assert (sag = sagR') as ->.
{
eapply (elem_of_all_disjoint_eq sag sagR' (m_destination m'''')); eauto.
set_solver. set_solver.
eapply Hmacoh. eauto. eauto.
}
eexists _, _.
rewrite lookup_delete_ne; last done.
split; [done|done].
Qed.
Lemma messages_resource_coh_receive_nin sagR sagT R T R' T' m mh :
mh !! sagR = Some (R, T) →
mh !! sagT = Some (R',T') →
m ∈ T' →
messages_addresses_coh mh →
m_destination m ∈g sagR -∗
m_sender m ∈g sagT -∗
messages_resource_coh mh -∗
messages_resource_coh (<[sagR:=({[m]} ∪ R, T)]> mh).
Proof.
iIntros (Hmha Hmhb HmT' (Hdisj & Hne & Hmacoh)).
iIntros "[%Hmdest _] [%Hmsend _] Hrcoh".
iDestruct "Hrcoh" as "[#Hown Hrcoh]".
iDestruct "Hrcoh" as (ms Hle) "[HrcohT Hrcoh]".
rewrite /messages_resource_coh.
rewrite dom_insert_L.
iAssert (socket_address_group_own sagR) as "HownR".
{
rewrite -(insert_id mh sagR (R,T)); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iSplitR.
{
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iSplit. iApply "HownR". iApply "Hown".
}
iExists ms.
iSplit.
{ rewrite messages_sent_insert.
rewrite <- (insert_id _ sagR (R,T)) in Hle; auto.
rewrite messages_sent_insert in Hle.
iPureIntro.
set_solver. }
iSplitR "Hrcoh".
{
rewrite messages_sent_insert.
rewrite -(messages_sent_split sagR R T mh Hmha).
done.
}
iApply (big_sepS_impl with "Hrcoh").
iIntros "!>" (m'' Hmin') "H".
iDestruct "H" as (sagT' sagR' Φ Hdest) "(#Hsag' & HsagT & [H | H])".
{
iDestruct "H" as (m''' Hmeq') "HΦ".
iExists sagT', sagR', Φ.
iSplit; [done|].
iSplit; [done|].
iSplit; [done|].
iLeft. eauto.
}
iDestruct "H" as %(m''' & Hmeq' & Hrecv).
iExists sagT', sagR', Φ.
iSplit; [done|].
iSplit; [done|].
iSplit; [done|].
iRight.
assert (m_destination m''' ∈ sagR').
{ eapply message_group_equiv_dest; eauto. }
pose proof Hrecv as Hrecv'.
rewrite /message_received in Hrecv'.
setoid_rewrite elem_of_messages_received in Hrecv'.
destruct Hrecv' as (sag & [R'' T''] & Hlookup & Hin).
simpl in *.
iAssert (socket_address_group_own sag) as "Hown'".
{
rewrite -(insert_id mh sag (R'',T'')); [|set_solver].
rewrite dom_insert_L.
rewrite -disj_gsets_op_union.
rewrite auth_frag_op.
iDestruct "Hown" as "[$ Hown]".
}
iDestruct (socket_interp_own with "Hsag'") as "Hown''".
iDestruct (own_op with "[Hown' Hown'']") as "Hown'''".
{ iSplit; [ iApply "Hown'" | iApply "Hown''" ]. }
rewrite -auth_frag_op.
iDestruct (own_valid with "Hown'''") as %Hvalid'.
setoid_rewrite auth_frag_valid in Hvalid'.
setoid_rewrite disj_gsets_valid in Hvalid'.
iPureIntro. exists m'''.
split; [done|].
rewrite message_received_insert.
destruct (decide (sagR' = sagR)) as [->|Hneq]; [left|right].
{ apply elem_of_union_r. by eapply messages_received_in. }
assert (sag = sagR') as ->.
{
eapply (elem_of_all_disjoint_eq sag sagR' (m_destination m''')); eauto.
set_solver. set_solver.
eapply Hmacoh. eauto. eauto.
}
rewrite /message_received.
rewrite !elem_of_messages_received.
eexists _, _.
rewrite lookup_delete_ne; last done.
split; [done|done].
Qed.
Lemma messages_resource_coh_receive sagR sagT R T R' T' m mh :
mh !! sagR = Some (R, T) →
mh !! sagT = Some (R',T') →
m ∈ T' →
messages_addresses_coh mh →
m_destination m ∈g sagR -∗
m_sender m ∈g sagT -∗
messages_resource_coh mh -∗
messages_resource_coh (<[sagR:=({[m]} ∪ R, T)]> mh) ∗
(⌜set_Forall (λ m', ¬ (m ≡g{sagT,sagR} m')) R⌝ -∗
∃ φ m', ⌜m ≡g{sagT,sagR} m'⌝ ∗ sagR ⤇* φ ∗ ▷ φ m').
Proof.
iIntros (Hmha Hmhb HmT' Hcoh).
iIntros "HsagR HsagT Hcoh".
destruct (decide (set_Forall (λ m', ¬ (m ≡g{sagT,sagR} m')) R)).
- iDestruct (messages_resource_coh_receive_in with "HsagR HsagT Hcoh")
as "[Hcoh Hφ]"; [ by eauto.. |].
by iFrame.
- iDestruct (messages_resource_coh_receive_nin with "HsagR HsagT Hcoh")
as "[Hcoh Hφ]"; [ by eauto.. |].
iFrame. by iIntros (H).
Qed.
End state_interpretation.
|
usethis::use_description()
roxygen2::roxygenise()
|
C (C) Copr. 1986-92 Numerical Recipes Software ,2:-5K#R..
SUBROUTINE twofft(data1,data2,fft1,fft2,n)
INTEGER*4 n
REAL*4 data1(n),data2(n)
COMPLEX*8 fft1(n),fft2(n)
CU USES four1
INTEGER*4 j,n2
COMPLEX*8 h1,h2,c1,c2
c1 = cmplx(0.5,0.0)
c2 = cmplx(0.0,-0.5)
do j=1,n
fft1(j)=cmplx(data1(j),data2(j))
enddo
call four1(fft1,n,1)
fft1(1)=cmplx(real(fft1(1)),0.0)
fft2(1)=cmplx(imag(fft1(1)),0.0)
n2=n+2
do j=2,n/2+1
h1=c1*(fft1(j)+conjg(fft1(n2-j)))
h2=c2*(fft1(j)-conjg(fft1(n2-j)))
fft1(j)=h1
fft1(n2-j)=conjg(h1)
fft2(j)=h2
fft2(n2-j)=conjg(h2)
enddo
return
END
|
President Barack Obama shakes hands with President-elect Donald Trump in the Oval Office last Thursday, after the two met to discuss the presidential transition.
Donald Trump's victory in the race for the White House leaves widespread uncertainty about what's in store for public schools under the first Republican administration in eight years. Aside from school choice, Trump, a New York-based real estate developer who has never before held public office, spent little time talking about K-12 education during his campaign. And he has no record to speak of on the issue for insights into what he may propose.
"We're all engaging in a lot of speculation because there hasn't been a lot of serious discussion about this, especially in the Trump campaign," Martin R. West, an associate professor of education at Harvard University, said in the run-up to the Nov. 8 presidential election. West has advised Republicans, including 2012 nominee Mitt Romney and Sen. Lamar Alexander of Tennessee, on education.
Trump did propose a $20 billion plan to dramatically expand school choice for low-income students. It would use federal money to help them attend private, charter, magnet, and regular public schools of their choice. It's also designed to leverage additional state investments in school choice of up to $100 billion nationwide.
In the campaign, the president-elect also embraced merit pay for teachers, without offering details beyond saying he found it unfair that "bad" teachers sometimes earned "more than the good ones." And, on the early-childhood front, he's pitched offering six weeks of maternity leave to women who do not get it through their employers, expanding the availability of dependent-care savings accounts, and offering tax incentives for employers to provide on-site day care.
But otherwise, the Trump campaign mostly dealt in sound bites with such controversial issues as the Common Core State Standards, the possibility of getting rid of the U.S. Department of Education, and gun-free school zones.
"I could really see him trying to minimize any role [of the federal government in education]," Nat Malkus, a research fellow at the conservative American Enterprise Institute, said in contemplating the implications of a Trump presidency ahead of the vote.
While education is not a high-profile issue politically at the moment, it's not as if the Trump administration won't have anything to do on school policy.
At or near the top of the K-12 to-do list is how the new administration handles the Every Student Succeeds Act, or ESSA, the latest version of the flagship federal Elementary and Secondary Education Act that was first passed in 1965. The Education Department under President Barack Obama is relatively close to finalizing ESSA regulations governing how states hold schools accountable and how districts must show they are using federal money to supplement their state and local school budgets.
Republicans in Congress have been critical of both sets of proposals from the department, particularly the one governing the supplemental-money rule. In fact, 25 GOP lawmakers recently asked the department to rescind its proposal for ensuring federal funds are supplemental, not a replacement for state and local money, on the grounds that the proposal would give the department too much power over state and local budget decisions.
The incoming administration may be on the same page as those lawmakers, said Gerard Robinson, a fellow at the American Enterprise Institute and former state schools chief in Virginia and Florida.
"I think [Trump's] secretary of education will handle it differently than what we've seen from [current Secretary] John King," regarding the so-called supplement-not-supplant rules, Robinson said. Robinson is serving as a member of the Trump transition team, but spoke only on his own behalf.
Democratic nominee Hillary Clinton focused more on early education and college affordability than K-12 in her losing bid for the White House.
However, when it comes to ESSA in general, Robinson said he believes that Trump views the law as a result of a "bipartisan coalition" and that the president-elect won't get too heavily involved in ESSA's rollout.
And Robinson expects states to have a great deal of flexibility in the ESSA accountability plans that they submit to the Trump administration starting next year—significantly more than they enjoyed under Obama-era waivers from the No Child Left Behind Act, the predecessor to ESSA.
"This is a great time to be a state chief," Robinson said, adding at the same time that "I don't want state chiefs to think that when they turn those [plans] in that, 'Oh, well, these will just get approved.' "
What's more, a lot of policies under the No Child Left Behind Act were part of the law but the George W. Bush or Obama administration didn't do much to enforce them. A couple of examples: the requirement that highly qualified teachers be distributed fairly between poor and less-poor schools, and that districts offer free tutoring to students in schools that weren't making progress under the law.
There could be similar examples of provisions that are on the books in ESSA, or in the Obama administration's regulations for the law, said Vic Klatt, a one-time aide to House Republicans who is now a principal at the Penn Hill Group. And since the Trump administration will be the first to enforce ESSA, it could be "easier and less disruptive" for it to simply ignore parts of the law than it would be for another administration down the line, Klatt said.
Trump could also discard another key piece of the Obama education legacy: The president-elect could significantly curb the role of the department's office for civil rights when it comes to state and local policies, according to Robinson, and thereby return the OCR's role more to how it operated under Presidents George H.W. Bush and George W. Bush. That could have a big impact on everything from action on racial disparities in school discipline to transgender students' rights.
Robinson also said that he expects the OCR to ensure that students' rights are not "trampled on."
Some civil rights advocates though, are already concerned, given some of Trump's campaign-trail rhetoric on Muslims and Latinos, that the office won't flex its enforcement muscles.
"We're worried," said Liz King, the director of education policy for the Leadership Conference on Civil and Human Rights. "We're hearing what everyone else is hearing from teachers and families that kids don't feel safe."
Much depends on whom Trump picks to lead his Education Department—assuming that he decides not to seek elimination or drastic cutbacks to the agency, which he has sometimes said he would like to do.
In October, Carl Palladino, a school board member in Buffalo, N.Y., and a Trump campaign surrogate, said he believed that if elected, Trump would pick someone from outside the education policy world to lead the department.
Another critical decision will be on who reviews states' proposed accountability plans for ESSA next year.
"Who are going to be his people? If he brings in a traditional right-of-center group, you can take it from there," said Maria Ferguson, the executive director of the Center on Education Policy, who worked in the Education Department under President Bill Clinton.
President-elect Donald Trump speaks at his victory rally on Nov. 9 in New York City. The Republican real estate developer made school choice a key theme when talking about public education on the campaign trail.
Ferguson suggested a traditional conservative policy agenda of expanded charter schools and other initiatives would probably get traction under Trump.
"All these familiar themes that the right-of-center groups have talked about will become a version of his agenda," Ferguson predicted. She mentioned school choice and groups like the Foundation for Excellence in Education, which was founded by former Florida Gov. Jeb Bush, one of Trump's rivals for the GOP nomination. "But I don't think it's going to come from him."
Earlier this year, Trump tapped Rob Goad, a staffer for Rep. Luke Messer, R-Ind., to be his education adviser, not long before the Trump campaign released its $20 billion school choice plan. There are some basic similarities between Trump's plan and a push last year to make federal Title I aid "portable" for disadvantaged students to use at both public and private schools.
And Trump's transition team for education includes Robinson, the former Florida and Virginia state chief, and Williamson M. Evers, a research fellow at Stanford University's Hoover Institution, who worked at the Education Department under President George W. Bush.
Much also depends on Trump's relationship with Congress and to what extent he empowers key GOP lawmakers on education policy.
Besides ESSA, Congress has been fairly active in moving education-related legislation. In recent months, for example, the House of Representatives approved reauthorizations of the Carl D. Perkins Career and Technical Education Act and the Juvenile Justice and Delinquency Prevention Act.
Some, but less, progress has also been made on renewing the Child Nutrition Act. And the Higher Education Act, the Individuals with Disabilities Education Act, and the Head Start federal preschool program are up for reauthorization in the near future.
Trump has outlined a general plan on college affordability, including capping student-loan repayments at 12.5 percent of income and instituting loan forgiveness after 15 years for certain borrowers. College affordability is a more prominent issue thanks to the 2016 presidential campaign. And since Congress remains sharply divided along partisan lines, Trump and the Republicans likely won't be able to simply roll ahead with all their preferences on higher education.
"You're not doing anything legislatively without bipartisan support," said West, of Harvard. "It's not obvious to me that there is a clear Republican agenda in Congress right now with respect to K-12 education, except for trying to ensure that ESSA is implemented in a way consistent with the intent of the law of empowering states to design accountability systems as they see fit."
But uncertainty prevails, both over what the new president will take an interest in and how much he will push to get education bills and initiatives over the finish line. |
=begin
# sample-group01.rb
require "algebra"
e = Permutation[0, 1, 2, 3, 4]
a = Permutation[1, 0, 3, 4, 2]
b = Permutation[0, 2, 1, 3, 4]
p a * b #=> [2, 0, 3, 4, 1]
g = Group.new(e, a, b)
g.complete!
p g == PermutationGroup.symmetric(5) #=> true
((<_|CONTENTS>))
=end
|
(*
Title: QR_Decomposition.thy
Author: Jose Divasón <jose.divasonm at unirioja.es>
Author: Jesús Aransay <jesus-maria.aransay at unirioja.es>
*)
section\<open>QR Decomposition\<close>
theory QR_Decomposition
imports Gram_Schmidt
begin
subsection\<open>The QR Decomposition of a matrix\<close>
text\<open>
First of all, it's worth noting what an orthogonal matrix is. In linear algebra,
an orthogonal matrix is a square matrix with real entries whose columns and rows are orthogonal
unit vectors.
Although in some texts the QR decomposition is presented over square matrices, it can be applied to any matrix.
There are some variants of the algorithm, depending on the properties that the output matrices
satisfy (see for instance, @{url "http://inst.eecs.berkeley.edu/~ee127a/book/login/l_mats_qr.html"}).
We present two of them below.
Let A be a matrix with m rows and n columns (A is \<open>m \<times> n\<close>).
Case 1: Starting with a matrix whose column rank is maximum. We can define the QR decomposition
to obtain:
\begin{itemize}
\item @{term "A = Q ** R"}.
\item Q has m rows and n columns. Its columns are orthogonal unit vectors
and @{term "(transpose Q) * Q = mat 1"}. In addition, if A is a square matrix, then Q
will be an orthonormal matrix.
\item R is \<open>n \<times> n\<close>, invertible and upper triangular.
\end{itemize}
Case 2: The called full QR decomposition. We can obtain:
\begin{itemize}
\item @{term "A = Q ** R"}
\item Q is an orthogonal matrix (Q is \<open>m \<times> m\<close>).
\item R is \<open>m \<times> n\<close> and upper triangular, but it isn't invertible.
\end{itemize}
We have decided to formalise the first one, because it's the only useful for solving
the linear least squares problem (@{url "http://math.mit.edu/linearalgebra/ila0403.pdf"}).
If we have an unsolvable system \<open>A *v x = b\<close>, we can try to find an approximate solution.
A plausible choice (not the only one) is to seek an \<open>x\<close> with the property that
\<open>\<parallel>A ** x - y\<parallel>\<close> (the magnitude of the error) is as small as possible. That \<open>x\<close>
is the least squares approximation.
We will demostrate that the best approximation (the solution for the linear least squares problem)
is the \<open>x\<close> that satisfies:
\<open>(transpose A) ** A *v x = (transpose A) *v b\<close>
Now we want to compute that x.
If we are working with the first case, \<open>A\<close> can be substituted by \<open>Q**R\<close> and then
obtain the solution of the least squares approximation by means of the QR decomposition:
\<open>x = (inverse R)**(transpose Q) *v b\<close>
On the contrary, if we are working with the second case after
substituting \<open>A\<close> by \<open>Q**R\<close> we obtain:
\<open>(transpose R) ** R *v x = (transpose R) ** (transpose Q) *v b\<close>
But the \<open>R\<close> matrix is not invertible (so neither is \<open>transpose R\<close>). The left part
of the equation \<open>(transpose R) ** R\<close> is not going to be an upper triangular matrix,
so it can't either be solved using backward-substitution.
\<close>
subsubsection\<open>Divide a vector by its norm\<close>
text\<open>An orthogonal matrix is a matrix whose rows (and columns) are orthonormal vectors. So, in order to
obtain the QR decomposition, we have to normalise (divide by the norm)
the vectors obtained with the Gram-Schmidt algorithm.\<close>
definition "divide_by_norm A = (\<chi> a b. normalize (column b A) $ a)"
text\<open>Properties\<close>
lemma norm_column_divide_by_norm:
fixes A::"'a::{real_inner}^'cols^'rows"
assumes a: "column a A \<noteq> 0"
shows "norm (column a (divide_by_norm A)) = 1"
proof -
have not_0: "norm (\<chi> i. A $ i $ a) \<noteq> 0" by (metis a column_def norm_eq_zero)
have "column a (divide_by_norm A) = (\<chi> i. (1 / norm (\<chi> i. A $ i $ a)) *\<^sub>R A $ i $ a)"
unfolding divide_by_norm_def column_def normalize_def by auto
also have "... = (1 / norm (\<chi> i. A $ i $ a)) *\<^sub>R (\<chi> i. A $ i $ a)"
unfolding vec_eq_iff by auto
finally have "norm (column a (divide_by_norm A)) = norm ((1 / norm (\<chi> i. A $ i $ a)) *\<^sub>R (\<chi> i. A $ i $ a))"
by simp
also have "... = \<bar>1 / norm (\<chi> i. A $ i $ a)\<bar> * norm (\<chi> i. A $ i $ a)"
unfolding norm_scaleR ..
also have "... = (1 / norm (\<chi> i. A $ i $ a)) * norm (\<chi> i. A $ i $ a)"
by auto
also have "... = 1" using not_0 by auto
finally show ?thesis .
qed
lemma span_columns_divide_by_norm:
shows "span (columns A) = span (columns (divide_by_norm A))"
unfolding real_vector.span_eq
proof (auto)
fix x assume x: "x \<in> columns (divide_by_norm A)"
from this obtain i where x_col_i: "x=column i (divide_by_norm A)" unfolding columns_def by blast
also have "... = (1/norm (column i A)) *\<^sub>R (column i A)"
unfolding divide_by_norm_def column_def normalize_def by vector
finally have x_eq: "x=(1/norm (column i A)) *\<^sub>R (column i A)" .
show "x \<in> span (columns A)"
by (unfold x_eq, rule span_mul, rule span_base, auto simp add: columns_def)
next
fix x
assume x: "x \<in> columns A"
show "x \<in> span (columns (divide_by_norm A))"
proof (cases "x=0")
case True show ?thesis by (metis True span_0)
next
case False
from x obtain i where x_col_i: "x=column i A" unfolding columns_def by blast
have "x=column i A" using x_col_i .
also have "... = norm (column i A) *\<^sub>R column i (divide_by_norm A)"
using False unfolding x_col_i columns_def divide_by_norm_def column_def normalize_def by vector
finally have x_eq: "x = norm (column i A) *\<^sub>R column i (divide_by_norm A)" .
show "x \<in> span (columns (divide_by_norm A))"
by (unfold x_eq, rule span_mul, rule span_base,
auto simp add: columns_def Let_def)
qed
qed
text\<open>Code lemmas\<close>
definition "divide_by_norm_row A a = vec_lambda(% b. ((1 / norm (column b A)) *\<^sub>R column b A) $ a)"
lemma divide_by_norm_row_code[code abstract]:
"vec_nth (divide_by_norm_row A a) = (% b. ((1 / norm (column b A)) *\<^sub>R column b A) $ a)"
unfolding divide_by_norm_row_def by (metis (lifting) vec_lambda_beta)
lemma divide_by_norm_code [code abstract]:
"vec_nth (divide_by_norm A) = divide_by_norm_row A"
unfolding divide_by_norm_def unfolding divide_by_norm_row_def[abs_def]
unfolding normalize_def
by fastforce
subsubsection\<open>The QR Decomposition\<close>
text\<open>The QR decomposition. Given a real matrix @{term "A"}, the algorithm will return a pair @{term "(Q,R)"}
where @{term "Q"} is an matrix whose columns are orthogonal unit vectors, @{term "R"}
is upper triangular and @{term "A=Q**R"}.\<close>
definition "QR_decomposition A = (let Q = divide_by_norm (Gram_Schmidt_matrix A) in (Q, (transpose Q) ** A))"
lemma is_basis_columns_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes b: "is_basis (columns A)"
and c: "card (columns A) = ncols A"
shows "is_basis (columns (fst (QR_decomposition A)))
\<and> card (columns (fst (QR_decomposition A))) = ncols A"
proof (rule conjI, unfold is_basis_def, rule conjI)
have "vec.span (columns (fst (QR_decomposition A))) = vec.span (columns (Gram_Schmidt_matrix A))"
unfolding vec.span_eq
proof (auto)
fix x show "x \<in> vec.span (columns (Gram_Schmidt_matrix A))"
using assms(1) assms(2) is_basis_columns_Gram_Schmidt_matrix is_basis_def by auto
next
fix x
assume x: "x \<in> columns (Gram_Schmidt_matrix A)"
from this obtain i where x_col_i: "x=column i (Gram_Schmidt_matrix A)" unfolding columns_def by blast
have zero_not_in: "x \<noteq> 0" using is_basis_columns_Gram_Schmidt_matrix[OF b c] unfolding is_basis_def
using vec.dependent_zero[of "(columns (Gram_Schmidt_matrix A))"] x by auto
have "x=column i (Gram_Schmidt_matrix A)" using x_col_i .
also have "... = norm (column i (Gram_Schmidt_matrix A)) *\<^sub>R column i (divide_by_norm (Gram_Schmidt_matrix A))"
using zero_not_in unfolding x_col_i columns_def divide_by_norm_def column_def normalize_def by vector
finally have x_eq: "x = norm (column i (Gram_Schmidt_matrix A)) *\<^sub>R column i (divide_by_norm (Gram_Schmidt_matrix A))" .
show "x \<in> vec.span (columns (fst (QR_decomposition A)))"
unfolding x_eq span_vec_eq
apply (rule subspace_mul)
apply (auto simp add: columns_def QR_decomposition_def Let_def subspace_span intro: span_superset)
using span_superset by force
qed
thus s: "vec.span (columns (fst (QR_decomposition A))) = (UNIV::(real^'m::{mod_type}) set)"
using is_basis_columns_Gram_Schmidt_matrix[OF b c] unfolding is_basis_def by simp
thus "card (columns (fst (QR_decomposition A))) = ncols A"
by (metis (hide_lams, mono_tags) b c card_columns_le_ncols vec.card_le_dim_spanning
finite_columns vec.indep_card_eq_dim_span is_basis_def ncols_def top_greatest)
thus "vec.independent (columns (fst (QR_decomposition A)))"
by (metis s b c vec.card_eq_dim_span_indep finite_columns vec.indep_card_eq_dim_span is_basis_def)
qed
lemma orthogonal_fst_QR_decomposition:
shows "pairwise orthogonal (columns (fst (QR_decomposition A)))"
unfolding pairwise_def columns_def
proof (auto)
fix i ia
assume col_not_eq: "column i (fst (QR_decomposition A)) \<noteq> column ia (fst (QR_decomposition A))"
hence i_not_ia: "i \<noteq> ia" by auto
from col_not_eq obtain a
where "(fst (QR_decomposition A)) $ a $ i \<noteq> (fst (QR_decomposition A)) $ a $ ia"
unfolding column_def by force
hence col_not_eq2: " (column i (Gram_Schmidt_matrix A)) \<noteq> (column ia (Gram_Schmidt_matrix A))"
using col_not_eq unfolding QR_decomposition_def Let_def fst_conv
by (metis (lifting) divide_by_norm_def vec_lambda_beta)
have d1: "column i (fst (QR_decomposition A))
= (1 / norm (\<chi> ia. Gram_Schmidt_matrix A $ ia $ i)) *\<^sub>R (column i (Gram_Schmidt_matrix A))"
unfolding QR_decomposition_def Let_def fst_conv
unfolding divide_by_norm_def column_def normalize_def unfolding vec_eq_iff by auto
have d2: "column ia (fst (QR_decomposition A))
= (1 / norm (\<chi> i. Gram_Schmidt_matrix A $ i $ ia)) *\<^sub>R (column ia (Gram_Schmidt_matrix A))"
unfolding QR_decomposition_def Let_def fst_conv
unfolding divide_by_norm_def column_def normalize_def unfolding vec_eq_iff by auto
show "orthogonal (column i (fst (QR_decomposition A))) (column ia (fst (QR_decomposition A)))"
unfolding d1 d2 apply (rule orthogonal_mult) using orthogonal_Gram_Schmidt_matrix[of A]
unfolding pairwise_def using col_not_eq2 by auto
qed
lemma qk_uk_norm:
"(1/(norm (column k ((Gram_Schmidt_matrix A))))) *\<^sub>R (column k ((Gram_Schmidt_matrix A)))
= column k (fst(QR_decomposition A))"
unfolding QR_decomposition_def Let_def fst_conv divide_by_norm_def
unfolding column_def normalize_def by vector
lemma norm_columns_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes "rank A = ncols A"
shows "norm (column i (fst (QR_decomposition A))) = 1"
proof -
have "vec.independent (columns (Gram_Schmidt_matrix A))"
by (metis assms full_rank_imp_is_basis2 independent_columns_Gram_Schmidt_matrix)
hence "column i (Gram_Schmidt_matrix A) \<noteq> 0"
using vec.dependent_zero[of "columns (Gram_Schmidt_matrix A)"]
unfolding columns_def by auto
thus "norm (column i (fst (QR_decomposition A))) = 1"
unfolding QR_decomposition_def Let_def fst_conv
by (rule norm_column_divide_by_norm)
qed
corollary span_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
shows "vec.span (columns A) = vec.span (columns (fst (QR_decomposition A)))"
unfolding span_Gram_Schmidt_matrix[of A]
unfolding QR_decomposition_def Let_def fst_conv
by (metis \<open>span (columns A) = span (columns (Gram_Schmidt_matrix A))\<close> span_columns_divide_by_norm span_vec_eq)
corollary col_space_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
shows "col_space A = col_space (fst (QR_decomposition A))"
unfolding col_space_def using span_fst_QR_decomposition
by auto
lemma independent_columns_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes b: "vec.independent (columns A)"
and c: "card (columns A) = ncols A"
shows "vec.independent (columns (fst (QR_decomposition A)))
\<and> card (columns (fst (QR_decomposition A))) = ncols A"
proof -
have r: "rank A = ncols A" thm is_basis_imp_full_rank
proof -
have "rank A = col_rank A" unfolding rank_col_rank ..
also have "... = vec.dim (col_space A)" unfolding col_rank_def ..
also have "... = card (columns A)"
unfolding col_space_def using b
by (rule vec.dim_span_eq_card_independent)
also have "... = ncols A" using c .
finally show ?thesis .
qed
have "vec.independent (columns (fst (QR_decomposition A)))"
by (metis b c col_rank_def col_space_QR_decomposition col_space_def
full_rank_imp_is_basis2 vec.indep_card_eq_dim_span ncols_def rank_col_rank)
moreover have "card (columns (fst (QR_decomposition A))) = ncols A"
by (metis col_space_QR_decomposition full_rank_imp_is_basis2 ncols_def r rank_eq_dim_col_space')
ultimately show ?thesis by simp
qed
lemma orthogonal_matrix_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "transpose (fst (QR_decomposition A)) ** (fst (QR_decomposition A)) = mat 1"
proof (unfold vec_eq_iff, clarify, unfold mat_1_fun, auto)
define Q where "Q = fst (QR_decomposition A)"
have n: "\<forall>i. norm (column i Q) = 1" unfolding Q_def using norm_columns_fst_QR_decomposition[OF r] by auto
have c: "card (columns Q) = ncols A" unfolding Q_def
by (metis full_rank_imp_is_basis2 independent_columns_fst_QR_decomposition r)
have p: "pairwise orthogonal (columns Q)" by (metis Q_def orthogonal_fst_QR_decomposition)
fix ia
have "(transpose Q ** Q) $ ia $ ia = column ia Q \<bullet> column ia Q"
unfolding matrix_matrix_mult_inner_mult unfolding row_transpose ..
also have "... = 1" using n norm_eq_1 by blast
finally show "(transpose Q ** Q) $ ia $ ia = 1" .
fix i
assume i_not_ia: "i \<noteq> ia"
have column_i_not_ia: "column i Q \<noteq> column ia Q"
proof (rule ccontr, simp)
assume col_i_ia: "column i Q = column ia Q"
have rw: "(\<lambda>i. column i Q)` (UNIV-{ia}) = {column i Q|i. i\<noteq>ia}" unfolding columns_def by auto
have "card (columns Q) = card ({column i Q|i. i\<noteq>ia})"
by (rule bij_betw_same_card[of id], unfold bij_betw_def columns_def, auto, metis col_i_ia i_not_ia)
also have "... = card ((\<lambda>i. column i Q)` (UNIV-{ia}))" unfolding rw ..
also have "... \<le> card (UNIV - {ia})" by (metis card_image_le finite_code)
also have "... < CARD ('n)" by simp
finally show False using c unfolding ncols_def by simp
qed
hence oia: "orthogonal (column i Q) (column ia Q)"
using p unfolding pairwise_def unfolding columns_def by auto
have "(transpose Q ** Q) $ i $ ia = column i Q \<bullet> column ia Q"
unfolding matrix_matrix_mult_inner_mult unfolding row_transpose ..
also have "... = 0" using oia unfolding orthogonal_def .
finally show "(transpose Q ** Q) $ i $ ia = 0" .
qed
corollary orthogonal_matrix_fst_QR_decomposition':
fixes A::"real^'n::{mod_type}^'n::{mod_type}"
assumes "rank A = ncols A"
shows "orthogonal_matrix (fst (QR_decomposition A))"
by (metis assms orthogonal_matrix orthogonal_matrix_fst_QR_decomposition)
lemma column_eq_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
and c: "column i (fst (QR_decomposition A)) = column ia (fst (QR_decomposition A))"
shows "i = ia"
proof (rule ccontr)
assume i_not_ia: "i \<noteq> ia"
have "columns (fst (QR_decomposition A)) = (\<lambda>x. column x (fst (QR_decomposition A)))` (UNIV::('n::{mod_type}) set)"
unfolding columns_def by auto
also have "... = (\<lambda>x. column x (fst (QR_decomposition A)))` ((UNIV::('n::{mod_type}) set)-{ia})"
proof (unfold image_def, auto)
fix xa
show "\<exists>x\<in>UNIV - {ia}. column xa (fst (QR_decomposition A)) = column x (fst (QR_decomposition A))"
proof (cases "xa = ia")
case True thus ?thesis using c i_not_ia by (metis DiffI UNIV_I empty_iff insert_iff)
next
case False thus ?thesis by auto
qed
qed
finally have columns_rw: "columns (fst (QR_decomposition A))
= (\<lambda>x. column x (fst (QR_decomposition A))) ` (UNIV - {ia})" .
have "ncols A = card (columns (fst (QR_decomposition A)))"
by (metis full_rank_imp_is_basis2 independent_columns_fst_QR_decomposition r)
also have "... \<le> card (UNIV - {ia})" unfolding columns_rw by (rule card_image_le, simp)
also have "... = card (UNIV::'n set) - 1" by (simp add: card_Diff_singleton)
finally show False unfolding ncols_def
by (metis Nat.add_0_right Nat.le_diff_conv2 One_nat_def Suc_n_not_le_n add_Suc_right one_le_card_finite)
qed
corollary column_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "column k ((Gram_Schmidt_matrix A))
= (column k A) - (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> (column k A) / (x \<bullet> x)) *\<^sub>R x)"
proof -
let ?uk="column k ((Gram_Schmidt_matrix A))"
let ?qk="column k (fst(QR_decomposition A))"
let ?ak="(column k A)"
define f where "f x = (1/norm x) *\<^sub>R x" for x :: "real^'m::{mod_type}"
let ?g="\<lambda>x::real^'m::{mod_type}. (x \<bullet> (column k A) / (x \<bullet> x)) *\<^sub>R x"
have set_rw: "{column i (fst (QR_decomposition A))|i. i < k} = f`{column i (Gram_Schmidt_matrix A)|i. i < k}"
proof (auto)
fix i
assume i: "i < k"
have col_rw: "column i (fst (QR_decomposition A)) =
(1/norm (column i (Gram_Schmidt_matrix A))) *\<^sub>R (column i (Gram_Schmidt_matrix A))"
unfolding QR_decomposition_def Let_def fst_conv divide_by_norm_def column_def normalize_def by vector
thus "column i (fst (QR_decomposition A)) \<in> f ` {column i (Gram_Schmidt_matrix A) |i. i < k}"
unfolding f_def using i
by auto
show "\<exists>ia. f (column i (Gram_Schmidt_matrix A)) = column ia (fst (QR_decomposition A)) \<and> ia < k"
by (rule exI[of _ i], simp add: f_def col_rw i)
qed
have "(\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)
= (\<Sum>x\<in>(f`{column i (Gram_Schmidt_matrix A)|i. i < k}). (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)"
unfolding set_rw ..
also have "... = sum (?g \<circ> f) {column i (Gram_Schmidt_matrix A)|i. i < k}"
proof (rule sum.reindex, unfold inj_on_def, auto)
fix i ia assume i: "i < k" and ia: "ia < k"
and f_eq: "f (column i (Gram_Schmidt_matrix A)) = f (column ia (Gram_Schmidt_matrix A))"
have fi: "f (column i (Gram_Schmidt_matrix A)) = column i (fst (QR_decomposition A))"
unfolding f_def QR_decomposition_def Let_def fst_conv divide_by_norm_def column_def normalize_def
by vector
have fia: "f (column ia (Gram_Schmidt_matrix A)) = column ia (fst (QR_decomposition A))"
unfolding f_def QR_decomposition_def Let_def fst_conv divide_by_norm_def column_def normalize_def
by vector
have "i = ia" using column_eq_fst_QR_decomposition[OF r] f_eq unfolding fi fia by simp
thus "column i (Gram_Schmidt_matrix A) = column ia (Gram_Schmidt_matrix A)" by simp
qed
also have "... = (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i.
i < k}. ((1 / norm x) *\<^sub>R x \<bullet> ?ak / ((1 / norm x) *\<^sub>R x \<bullet> (1 / norm x) *\<^sub>R x)) *\<^sub>R (1 / norm x) *\<^sub>R x)" unfolding o_def f_def ..
also have "... = (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i.
i < k}. ((1 / norm x) *\<^sub>R x \<bullet> ?ak) *\<^sub>R (1 / norm x) *\<^sub>R x)"
proof (rule sum.cong, simp)
fix x assume x: "x \<in> {column i (Gram_Schmidt_matrix A) |i. i < k}"
have "vec.independent {column i (Gram_Schmidt_matrix A) |i. i < k}"
proof (rule vec.independent_mono[of "columns (Gram_Schmidt_matrix A)"])
show "vec.independent (columns (Gram_Schmidt_matrix A))"
using full_rank_imp_is_basis2[of "(Gram_Schmidt_matrix A)"]
by (metis full_rank_imp_is_basis2 independent_columns_Gram_Schmidt_matrix r)
show "{column i (Gram_Schmidt_matrix A) |i. i < k} \<subseteq> columns (Gram_Schmidt_matrix A)"
unfolding columns_def by auto
qed
hence "x \<noteq> 0" using vec.dependent_zero[of " {column i (Gram_Schmidt_matrix A) |i. i < k}"] x
by blast
hence "((1 / norm x) *\<^sub>R x \<bullet> (1 / norm x) *\<^sub>R x) = 1" by (metis inverse_eq_divide norm_eq_1 norm_sgn sgn_div_norm)
thus "((1 / norm x) *\<^sub>R x \<bullet> ?ak / ((1 / norm x) *\<^sub>R x \<bullet> (1 / norm x) *\<^sub>R x)) *\<^sub>R (1 / norm x) *\<^sub>R x =
((1 / norm x) *\<^sub>R x \<bullet> column k A) *\<^sub>R (1 / norm x) *\<^sub>R x" by auto
qed
also have "... = (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (((x \<bullet> ?ak)) / (x \<bullet> x)) *\<^sub>R x)"
proof (rule sum.cong, simp)
fix x
assume x: "x \<in> {column i (Gram_Schmidt_matrix A) |i. i < k}"
show "((1 / norm x) *\<^sub>R x \<bullet> column k A) *\<^sub>R (1 / norm x) *\<^sub>R x = (x \<bullet> column k A / (x \<bullet> x)) *\<^sub>R x"
by (metis (hide_lams, no_types) mult.right_neutral inner_commute inner_scaleR_right
norm_cauchy_schwarz_eq scaleR_one scaleR_scaleR times_divide_eq_right times_divide_times_eq)
qed
finally have "?ak - (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)
= ?ak - (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (((x \<bullet> ?ak)) / (x \<bullet> x)) *\<^sub>R x)" by auto
also have "... = ?uk" using column_Gram_Schmidt_matrix[of k A] by auto
finally show ?thesis ..
qed
lemma column_QR_decomposition':
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "(column k A) = column k ((Gram_Schmidt_matrix A))
+ (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> (column k A) / (x \<bullet> x)) *\<^sub>R x)"
using column_QR_decomposition[OF r] by simp
lemma norm_uk_eq:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "norm (column k ((Gram_Schmidt_matrix A))) = ((column k (fst(QR_decomposition A))) \<bullet> (column k A))"
proof -
let ?uk="column k ((Gram_Schmidt_matrix A))"
let ?qk="column k (fst(QR_decomposition A))"
let ?ak="(column k A)"
have sum_rw: "(?uk \<bullet> (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)) = 0"
proof -
have "(?uk \<bullet> (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x))
= ((\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. ?uk \<bullet> ((x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)))"
unfolding inner_sum_right ..
also have "... = (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. ((x \<bullet> ?ak / (x \<bullet> x)) * (?uk \<bullet> x)))"
unfolding inner_scaleR_right ..
also have "... = 0"
proof (rule sum.neutral, clarify)
fix x i assume "i<k"
hence "?uk \<bullet> column i (Gram_Schmidt_matrix A) = 0"
by (metis less_irrefl r scaleR_columns_Gram_Schmidt_matrix)
thus "column i (Gram_Schmidt_matrix A) \<bullet> ?ak / (column i (Gram_Schmidt_matrix A) \<bullet> column i (Gram_Schmidt_matrix A)) *
(?uk \<bullet> column i (Gram_Schmidt_matrix A)) = 0" by auto
qed
finally show ?thesis .
qed
have "?qk \<bullet> ?ak = ((1/(norm ?uk)) *\<^sub>R ?uk) \<bullet> ?ak" unfolding qk_uk_norm ..
also have "... = (1/(norm ?uk)) * (?uk \<bullet> ?ak)" unfolding inner_scaleR_left ..
also have "... =
(1/(norm ?uk)) * (?uk \<bullet> (?uk + (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)))"
using column_Gram_Schmidt_matrix2[of k A] by auto
also have "... = (1/(norm ?uk)) * ((?uk \<bullet> ?uk) + (?uk \<bullet> (\<Sum>x\<in>{column i (Gram_Schmidt_matrix A) |i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)))"
unfolding inner_add_right ..
also have "... = (1/(norm ?uk)) * (?uk \<bullet> ?uk)" unfolding sum_rw by auto
also have "... = norm ?uk"
by (metis abs_of_nonneg divide_eq_imp div_by_0 inner_commute inner_ge_zero inner_real_def
norm_mult_vec real_inner_1_right real_norm_def times_divide_eq_right)
finally show ?thesis ..
qed
corollary column_QR_decomposition2:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "(column k A)
= (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i \<le> k}. (x \<bullet> (column k A)) *\<^sub>R x)"
proof -
let ?uk="column k ((Gram_Schmidt_matrix A))"
let ?qk="column k (fst(QR_decomposition A))"
let ?ak="(column k A)"
have set_rw: "{column i (fst (QR_decomposition A))|i. i \<le> k}
= insert (column k (fst (QR_decomposition A))) {column i (fst (QR_decomposition A))|i. i < k}"
by (auto, metis less_linear not_less)
have uk_norm_uk_qk: "?uk = norm ?uk *\<^sub>R ?qk"
proof -
have "vec.independent (columns (Gram_Schmidt_matrix A))"
by (metis full_rank_imp_is_basis2 independent_columns_Gram_Schmidt_matrix r)
moreover have "?uk \<in> columns (Gram_Schmidt_matrix A)" unfolding columns_def by auto
ultimately have "?uk \<noteq> 0"
using vec.dependent_zero[of "columns (Gram_Schmidt_matrix A)"] unfolding columns_def by auto
hence norm_not_0: "norm ?uk \<noteq> 0" unfolding norm_eq_zero .
have "norm (?uk) *\<^sub>R ?qk = (norm ?uk) *\<^sub>R ((1 / norm ?uk) *\<^sub>R ?uk)" using qk_uk_norm[of k A] by simp
also have "... = ((norm ?uk) * (1 / norm ?uk)) *\<^sub>R ?uk" unfolding scaleR_scaleR ..
also have "... = ?uk" using norm_not_0 by auto
finally show ?thesis ..
qed
have norm_qk_1: "?qk \<bullet> ?qk = 1"
using norm_eq_1 norm_columns_fst_QR_decomposition[OF r]
by auto
have "?ak = ?uk + (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)"
using column_QR_decomposition'[OF r] by auto
also have "... = (norm ?uk *\<^sub>R ?qk) + (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)"
using uk_norm_uk_qk by simp
also have "... = ((?qk \<bullet> ?ak) *\<^sub>R ?qk)
+ (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)"
unfolding norm_uk_eq[OF r] ..
also have "... = ((?qk \<bullet> ?ak)/(?qk \<bullet> ?qk)) *\<^sub>R ?qk
+ (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)" using norm_qk_1 by fastforce
also have "... = (\<Sum>x\<in>insert ?qk {column i (fst (QR_decomposition A))|i. i < k}. (x \<bullet> ?ak / (x \<bullet> x)) *\<^sub>R x)"
proof (rule sum.insert[symmetric])
show "finite {column i (fst (QR_decomposition A)) |i. i < k}" by simp
show "column k (fst (QR_decomposition A)) \<notin> {column i (fst (QR_decomposition A)) |i. i < k}"
proof (rule ccontr, simp)
assume "\<exists>i. column k (fst (QR_decomposition A)) = column i (fst (QR_decomposition A)) \<and> i < k"
from this obtain i where col_eq: "column k (fst (QR_decomposition A)) = column i (fst (QR_decomposition A))"
and i_less_k: "i < k" by blast
show False using column_eq_fst_QR_decomposition[OF r col_eq] i_less_k by simp
qed
qed
also have "... = (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i \<le> k}. (x \<bullet> (column k A)) *\<^sub>R x)"
proof (rule sum.cong, simp add: set_rw)
fix x assume x: "x \<in> {column i (fst (QR_decomposition A)) |i. i \<le> k}"
from this obtain i where i: "x=column i (fst (QR_decomposition A))" by blast
hence "(x \<bullet> x) = 1" using norm_eq_1 norm_columns_fst_QR_decomposition[OF r]
by auto
thus "(x \<bullet> column k A / (x \<bullet> x)) *\<^sub>R x = (x \<bullet> column k A) *\<^sub>R x" by simp
qed
finally show ?thesis .
qed
lemma orthogonal_columns_fst_QR_decomposition:
assumes i_not_ia: "(column i (fst (QR_decomposition A))) \<noteq> (column ia (fst (QR_decomposition A)))"
shows "(column i (fst (QR_decomposition A)) \<bullet> column ia (fst (QR_decomposition A))) = 0"
proof -
have i: "column i (fst (QR_decomposition A)) \<in> columns (fst (QR_decomposition A))" unfolding columns_def by auto
have ia: "column ia (fst (QR_decomposition A)) \<in> columns (fst (QR_decomposition A))" unfolding columns_def by auto
show ?thesis
using orthogonal_fst_QR_decomposition[of A] i ia i_not_ia unfolding pairwise_def orthogonal_def
by auto
qed
lemma scaler_column_fst_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes i: "i>j"
and r: "rank A = ncols A"
shows "column i (fst (QR_decomposition A)) \<bullet> column j A = 0"
proof -
have "column i (fst(QR_decomposition A)) \<bullet> column j A
= column i (fst (QR_decomposition A)) \<bullet> (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i \<le> j}. (x \<bullet> (column j A)) *\<^sub>R x)"
using column_QR_decomposition2[OF r] by presburger
also have "... = (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i \<le> j}.
column i (fst (QR_decomposition A)) \<bullet> (x \<bullet> (column j A)) *\<^sub>R x)" unfolding real_inner_class.inner_sum_right ..
also have "... = (\<Sum>x\<in>{column i (fst (QR_decomposition A))|i. i \<le> j}.
(x \<bullet> (column j A)) *(column i (fst (QR_decomposition A)) \<bullet> x))" unfolding real_inner_class.inner_scaleR_right ..
also have "... = 0"
proof (rule sum.neutral, clarify)
fix ia assume ia: "ia \<le> j"
have i_not_ia: "i \<noteq> ia" using i ia by simp
hence "(column i (fst (QR_decomposition A)) \<noteq> column ia (fst (QR_decomposition A)))"
by (metis column_eq_fst_QR_decomposition r)
hence "(column i (fst (QR_decomposition A)) \<bullet> column ia (fst (QR_decomposition A))) = 0"
by (rule orthogonal_columns_fst_QR_decomposition)
thus "column ia (fst (QR_decomposition A)) \<bullet> column j A * (column i (fst (QR_decomposition A)) \<bullet> column ia (fst (QR_decomposition A))) = 0"
by auto
qed
finally show ?thesis .
qed
lemma R_Qi_Aj:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
shows "(snd (QR_decomposition A)) $ i $ j = column i (fst (QR_decomposition A)) \<bullet> column j A"
unfolding QR_decomposition_def Let_def snd_conv matrix_matrix_mult_inner_mult
unfolding row_transpose by auto
lemma sums_columns_Q_0:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "(\<Sum>x\<in>{column i (fst (QR_decomposition A)) |i. i>b}. x \<bullet> column b A * x $ a) = 0"
proof (rule sum.neutral, auto)
fix i assume "b<i"
thus "column i (fst (QR_decomposition A)) \<bullet> column b A = 0"
by (rule scaler_column_fst_QR_decomposition, simp add: r)
qed
lemma QR_decomposition_mult:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "A = (fst (QR_decomposition A)) ** (snd (QR_decomposition A))"
proof -
have "\<forall>b. column b A = column b ((fst (QR_decomposition A)) ** (snd (QR_decomposition A)))"
proof (clarify)
fix b
have "(fst (QR_decomposition A) ** snd (QR_decomposition A))
= (\<chi> i j. \<Sum>k\<in>UNIV. fst (QR_decomposition A) $ i $ k * (column k (fst (QR_decomposition A)) \<bullet> column j A))"
unfolding matrix_matrix_mult_def R_Qi_Aj by auto
hence "column b ((fst (QR_decomposition A) ** snd (QR_decomposition A))) =
column b ((\<chi> i j. \<Sum>k\<in>UNIV. fst (QR_decomposition A) $ i $ k * (column k (fst (QR_decomposition A)) \<bullet> column j A)))"
by auto
also have "... = (\<Sum>x\<in>{column i (fst (QR_decomposition A)) |i. i \<le> b}. (x \<bullet> column b A) *\<^sub>R x)"
proof (subst column_def, subst vec_eq_iff, auto)
fix a
define f where "f i = column i (fst (QR_decomposition A))" for i
define g where "g x = (THE i. x = column i (fst (QR_decomposition A)))" for x
have f_eq: "f`UNIV = {column i (fst (QR_decomposition A)) |i. i\<in>UNIV}" unfolding f_def by auto
have inj_f: "inj f"
by (metis inj_on_def f_def column_eq_fst_QR_decomposition r)
have "(\<Sum>x\<in>{column i (fst (QR_decomposition A)) |i. i \<le> b}. x \<bullet> column b A * x $ a)
= (\<Sum>x\<in>{column i (fst (QR_decomposition A)) |i. i\<in>UNIV}. x \<bullet> column b A * x $ a)"
proof -
let ?c= "{column i (fst (QR_decomposition A)) |i. i\<in>UNIV}"
let ?d= "{column i (fst (QR_decomposition A)) |i. i\<le>b}"
let ?f = "{column i (fst (QR_decomposition A)) |i. i>b}"
have set_rw: "?c = ?d \<union> ?f" by force
have "(\<Sum>x\<in>?c. x \<bullet> column b A * x $ a)
= (\<Sum>x\<in>(?d \<union> ?f). x \<bullet> column b A * x $ a)" using set_rw by simp
also have "... = (\<Sum>x\<in>?d. x \<bullet> column b A * x $ a) + (\<Sum>x\<in>?f. x \<bullet> column b A * x $ a)"
by (rule sum.union_disjoint, auto, metis f_def inj_eq inj_f not_le)
also have "... = (\<Sum>x\<in>?d. x \<bullet> column b A * x $ a)" using sums_columns_Q_0[OF r] by auto
finally show ?thesis ..
qed
also have "... = (\<Sum>x\<in>f`UNIV. x \<bullet> column b A * x $ a)" using f_eq by auto
also have "... = (\<Sum>k\<in>UNIV. fst (QR_decomposition A) $ a $ k * (column k (fst (QR_decomposition A)) \<bullet> column b A))"
unfolding sum.reindex[OF inj_f] unfolding f_def column_def by (rule sum.cong, simp_all)
finally show " (\<Sum>k\<in>UNIV. fst (QR_decomposition A) $ a $ k * (column k (fst (QR_decomposition A)) \<bullet> column b A)) =
(\<Sum>x\<in>{column i (fst (QR_decomposition A)) |i. i \<le> b}. x \<bullet> column b A * x $ a)" ..
qed
also have "... = column b A"
using column_QR_decomposition2[OF r] by simp
finally show "column b A = column b (fst (QR_decomposition A) ** snd (QR_decomposition A))" ..
qed
thus ?thesis unfolding column_def vec_eq_iff by auto
qed
lemma upper_triangular_snd_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "upper_triangular (snd (QR_decomposition A))"
proof (unfold upper_triangular_def, auto)
fix i j::'n
assume j_less_i: "j < i"
have "snd (QR_decomposition A) $ i $ j = column i (fst (QR_decomposition A)) \<bullet> column j A"
unfolding QR_decomposition_def Let_def fst_conv snd_conv
unfolding matrix_matrix_mult_inner_mult row_transpose ..
also have "... = 0" using scaler_column_fst_QR_decomposition[OF j_less_i r] .
finally show "snd (QR_decomposition A) $ i $ j = 0" by auto
qed
lemma upper_triangular_invertible:
fixes A :: "real^'n::{finite,wellorder}^'n::{finite,wellorder}"
assumes u: "upper_triangular A"
and d: "\<forall>i. A $ i $ i \<noteq> 0"
shows "invertible A"
proof -
have det_R: "det A = (prod (\<lambda>i. A$i$i) (UNIV::'n set))"
using det_upperdiagonal u unfolding upper_triangular_def by blast
also have "... \<noteq> 0" using d by auto
finally show ?thesis by (metis invertible_det_nz)
qed
lemma invertible_snd_QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "invertible (snd (QR_decomposition A))"
proof (rule upper_triangular_invertible)
show "upper_triangular (snd (QR_decomposition A))"
using upper_triangular_snd_QR_decomposition[OF r] .
show "\<forall>i. snd (QR_decomposition A) $ i $ i \<noteq> 0"
proof (rule allI)
fix i
have ind: "vec.independent (columns (Gram_Schmidt_matrix A))"
by (metis full_rank_imp_is_basis2
independent_columns_Gram_Schmidt_matrix r)
hence zero_not_in: "0 \<notin> (columns (Gram_Schmidt_matrix A))" by (metis vec.dependent_zero)
hence c:"column i (Gram_Schmidt_matrix A) \<noteq> 0" unfolding columns_def by simp
have "snd (QR_decomposition A) $ i $ i = column i (fst (QR_decomposition A)) \<bullet> column i A"
unfolding QR_decomposition_def Let_def snd_conv fst_conv
unfolding matrix_matrix_mult_inner_mult
unfolding row_transpose ..
also have "... = norm (column i (Gram_Schmidt_matrix A))"
unfolding norm_uk_eq[OF r, symmetric] ..
also have "... \<noteq> 0" by (rule ccontr, simp add: c)
finally show "snd (QR_decomposition A) $ i $ i \<noteq> 0" .
qed
qed
lemma QR_decomposition:
fixes A::"real^'n::{mod_type}^'m::{mod_type}"
assumes r: "rank A = ncols A"
shows "A = fst (QR_decomposition A) ** snd (QR_decomposition A) \<and>
pairwise orthogonal (columns (fst (QR_decomposition A))) \<and>
(\<forall>i. norm (column i (fst (QR_decomposition A))) = 1) \<and>
(transpose (fst (QR_decomposition A))) ** (fst (QR_decomposition A)) = mat 1 \<and>
vec.independent (columns (fst (QR_decomposition A))) \<and>
col_space A = col_space (fst (QR_decomposition A)) \<and>
card (columns A) = card (columns (fst (QR_decomposition A))) \<and>
invertible (snd (QR_decomposition A)) \<and>
upper_triangular (snd (QR_decomposition A))"
by (metis QR_decomposition_mult col_space_def full_rank_imp_is_basis2
independent_columns_fst_QR_decomposition invertible_snd_QR_decomposition
norm_columns_fst_QR_decomposition orthogonal_fst_QR_decomposition
orthogonal_matrix_fst_QR_decomposition r span_fst_QR_decomposition
upper_triangular_snd_QR_decomposition)
lemma QR_decomposition_square:
fixes A::"real^'n::{mod_type}^'n::{mod_type}"
assumes r: "rank A = ncols A"
shows "A = fst (QR_decomposition A) ** snd (QR_decomposition A) \<and>
orthogonal_matrix (fst (QR_decomposition A)) \<and>
upper_triangular (snd (QR_decomposition A)) \<and>
invertible (snd (QR_decomposition A)) \<and>
pairwise orthogonal (columns (fst (QR_decomposition A))) \<and>
(\<forall>i. norm (column i (fst (QR_decomposition A))) = 1) \<and>
vec.independent (columns (fst (QR_decomposition A))) \<and>
col_space A = col_space (fst (QR_decomposition A)) \<and>
card (columns A) = card (columns (fst (QR_decomposition A)))"
by (metis QR_decomposition orthogonal_matrix_fst_QR_decomposition' r)
text\<open>QR for computing determinants\<close>
lemma det_QR_decomposition:
fixes A::"real^'n::{mod_type}^'n::{mod_type}"
assumes r: "rank A = ncols A"
shows "\<bar>det A\<bar> = \<bar>(prod (\<lambda>i. snd(QR_decomposition A)$i$i) (UNIV::'n set))\<bar>"
proof -
let ?Q="fst(QR_decomposition A)"
let ?R="snd(QR_decomposition A)"
have det_R: "det ?R = (prod (\<lambda>i. snd(QR_decomposition A)$i$i) (UNIV::'n set))"
apply (rule det_upperdiagonal)
using upper_triangular_snd_QR_decomposition[OF r]
unfolding upper_triangular_def by simp
have "\<bar>det A\<bar> = \<bar>det ?Q * det ?R\<bar>" by (metis QR_decomposition_mult det_mul r)
also have "... = \<bar>det ?Q\<bar> * \<bar>det ?R\<bar>" unfolding abs_mult ..
also have "... = 1 * \<bar>det ?R\<bar>" using det_orthogonal_matrix[OF orthogonal_matrix_fst_QR_decomposition'[OF r]]
by auto
also have "... = \<bar>det ?R\<bar>" by simp
also have "... = \<bar>(prod (\<lambda>i. snd(QR_decomposition A)$i$i) (UNIV::'n set))\<bar>" unfolding det_R ..
finally show ?thesis .
qed
end
|
#eval 2+2
#check Sigma
#check Σ'x, x > 3
#check [1, 2, 3]
#check (_ ∘ _)
#check Function.comp
#check HasEquiv
#check Fin
-- Карта и территория
#check propext
#check funext
-- Натуральные числа
#check Add
#check Mul
#check congr
#check Eq.subst
#check {x // x > 3}
#check Subtype.eta
#check Exists
#check Fin
-- Фактор-типы и целые числа
-- Рациональные и вещественные числа
-- Множества и зависимые пары
-- Функции
namespace Function
def retraction (f: α → ω)(g: ω → α): Prop := ∀x, g (f x) = x
def coretraction (f: ω → α)(g: α → ω): Prop := retraction g f
def inverse (f: α → ω)(g: ω → α) : Prop := retraction f g ∧ retraction g f
def injective (f: α → ω) : Prop := ∀x y, f x = f y → x = y
def surjective (f: α → ω) : Prop := ∀y, ∃x, f x = y
def bijective (f: α → ω) : Prop := injective f ∧ surjective f
theorem has_retr_injective (f: α → ω)(er: ∃g, retraction f g) : injective f :=
by
let ⟨g, r⟩ := er;
intro x y (e: f x = f y); show x = y
have e2: g (f x) = g (f y) := congrArg g e
exact r x ▸ r y ▸ e2
theorem has_coretr_surjective (f: ω → α)(ec: ∃g, coretraction f g) : surjective f :=
let ⟨g,c⟩ := ec; λy:α => ⟨g y, (by rw[c y] : f (g y) = y)⟩
-- theorem inj_has_retraction (f: α → ω)(ij: injective f) : ∃g, retraction f g :=
-- by sorry
-- theorem surj_has_coretraction (f: α → ω)(sj: surjective f) : ∃g, coretraction f g :=
-- by sorry
theorem lwfix (f: α → α → ω)(sj: surjective f)(u: ω → ω): ∃x, u x = x := by
let d := λx => u (f x x); let ⟨c,fp⟩ := (sj d : ∃c, f c = d);
refine ⟨d c, Eq.symm ?_⟩
calc
d c = u (f c c) := rfl
_ = u (d c) := by rw[fp]
end Function
-- Отношения
---------------
#check WellFounded
#check Acc
example (n:Nat): Acc Nat.lt n := by
apply Nat.rec
· show Acc _ 0
exact Acc.intro _ $ λk (h: k < 0) => absurd h (Nat.not_lt_zero k)
· refine λn h => (?_: Acc _ n.succ)
refine Acc.intro _ $ λk (lt: k < n.succ) => (?_: Acc _ k)
apply (Nat.eq_or_lt_of_le (Nat.le_of_succ_le_succ lt)).elim
· intro (l: k = n); exact l ▸ h
· intro (r: k < n); exact Acc.inv h r
#check Eq.subst
-- example {C: α → Sort v}(F: ∀ x, (∀ y, r y x → C y) → C x)(x:α)(a: Acc r x): C x :=
-- a.rec (λx _ ih => F x ih)
#print Acc.rec
inductive WTree {α:Type}: α → Type where
| leaf (r:α): WTree r
| branch (x:α)(b: ∀y:α, WTree y): WTree x
|
#ifndef __GSL_SORT_VECTOR_H__
#define __GSL_SORT_VECTOR_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_sort_vector_long_double.h>
#include <gsl/gsl_sort_vector_double.h>
#include <gsl/gsl_sort_vector_float.h>
#include <gsl/gsl_sort_vector_ulong.h>
#include <gsl/gsl_sort_vector_long.h>
#include <gsl/gsl_sort_vector_uint.h>
#include <gsl/gsl_sort_vector_int.h>
#include <gsl/gsl_sort_vector_ushort.h>
#include <gsl/gsl_sort_vector_short.h>
#include <gsl/gsl_sort_vector_uchar.h>
#include <gsl/gsl_sort_vector_char.h>
#endif /* __GSL_SORT_VECTOR_H__ */
|
[STATEMENT]
lemma conj_Inf_distrib: "D \<noteq> {} \<Longrightarrow> c \<iinter> (\<Sqinter> D) = (\<Sqinter>d\<in>D. c \<iinter> d)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. D \<noteq> {} \<Longrightarrow> c \<iinter> \<Sqinter> D = \<Sqinter> ((\<iinter>) c ` D)
variables:
c :: 'a
(\<iinter>) :: 'a \<Rightarrow> 'a \<Rightarrow> 'a
D :: 'a set
type variables:
'a :: refinement_lattice
[PROOF STEP]
using Inf_conj_distrib conj_commute
[PROOF STATE]
proof (prove)
using this:
(?D::'a::refinement_lattice set) \<noteq> {} \<Longrightarrow> \<Sqinter> ?D \<iinter> (?c::'a::refinement_lattice) = (\<Sqinter>d::'a::refinement_lattice\<in>?D. d \<iinter> ?c)
(?a::'a::refinement_lattice) \<iinter> (?b::'a::refinement_lattice) = ?b \<iinter> ?a
goal (1 subgoal):
1. D \<noteq> {} \<Longrightarrow> c \<iinter> \<Sqinter> D = \<Sqinter> ((\<iinter>) c ` D)
variables:
c :: 'a
(\<iinter>) :: 'a \<Rightarrow> 'a \<Rightarrow> 'a
D :: 'a set
type variables:
'a :: refinement_lattice
[PROOF STEP]
by auto |
Akron is located in northwest Hale County in the west-central part of Alabama. It has a mayor/city council form of government. Akron is the hometown of Riggs Stephenson, who played major-league baseball for the Cleveland Indians (1921-1925) and Chicago Cubs (1926-1934), retiring with a .336 batting average. The name Akron derives from the Greek word for "summit" or "high point."
Akron was established in 1870 by the Alabama and Chattanooga Railroad (now the Alabama Great Southern Railroad) on its line between Chattanooga, Tennessee, and Meridian, Mississippi. The town prospered from its location and was home to two stores by 1882. In 1906, the owner of a large plantation sold his land to a development company, and a construction boom followed; soon the town had a dozen stores, two hotels, a drugstore, two blacksmith shops, and a cotton gin. A new sawmill added lumber to the bales of cotton already being shipped out of town. By 1916, Akron had added a second cotton gin. Akron was incorporated in March 1918. The public library opened in 1937, and the Akron Manufacturing Company, a garment manufacturer, opened in 1964. Akron's economy today depends primarily on farming, with the main crop being soybeans. Timber is still shipped from the area.
Akron's population according to the 2010 Census was 356. Of that number, 86.5 percent of respondents identified themselves as African American, 13.2 percent as white, 0.3 percent as Hispanic or Latino, and 0.3 percent as two or more races. The town's median household income, according to 2010 estimates, was $26,375, and the per capita income was $14,797.
Schools in Akron are part of the Hale County school system; the town has approximately 318 students and 19 teachers in one school.
Local roads connect Akron with State Highway 60, which runs northeast-southwest, less than a mile southeast of town. The Norfolk Southern Corporation, parent company of the Alabama Great Southern Railroad, operates a rail line through Akron.
Tanglewood (1859), a historic plantation listed on the National Register of Historic Places, is located about five miles east of Akron. It is currently part of the 480-acre J. Nicholene Bishop Biological Station, the center of the University of Alabama's natural resources management curriculum.
Hale County Heritage Book Committee. The Heritage of Hale County, Alabama. Clanton, Ala.: Heritage Publishing Consultants, 2001.
Preservation Committee of the Alabama Reunion. Historic Hale County. Greensboro, Ala.: The Greensboro Watchman, 1989. |
Require Import Axiom_Extensionality.
Require Import Axiom_ProofIrrelevance.
Require Import Cast.
Require Import JMEq.
Require Import Category3.
Lemma eq_Category3 : forall (c c':Category3) (p: A3 c = A3 c'),
(forall f:A3 c, cast p (source3 c f) = source3 c' (cast p f)) ->
(forall f:A3 c, cast p (target3 c f) = target3 c' (cast p f)) ->
(forall f g:A3 c,
cast (toOption p) (compose3 c f g) = compose3 c' (cast p f) (cast p g)) ->
c = c'.
Proof.
intros c1 c2 p Hs Ht Hc.
destruct c1 as [A1 s1 t1 cmp1 pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1].
destruct c2 as [A2 s2 t2 cmp2 pss2 pts2 ptt2 pst2 pd2 ps2 pt2 pl2 pr2 pa2].
simpl in p. simpl in Hs. simpl in Ht. simpl in Hc.
revert pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1.
revert Hs Ht Hc. revert s1 t1 cmp1.
rewrite p.
intros s1 t1 cmp1 Hs Ht Hc.
simpl in Hs. simpl in Ht. simpl in Hc.
rewrite (proof_irrelevance _ (toOption eq_refl) eq_refl) in Hc. simpl in Hc.
apply extensionality in Hs.
apply extensionality in Ht.
apply extensionality2 in Hc.
rewrite Hs, Ht, Hc.
intros pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1.
rewrite (proof_irrelevance _ pss1 pss2).
rewrite (proof_irrelevance _ pts1 pts2).
rewrite (proof_irrelevance _ ptt1 ptt2).
rewrite (proof_irrelevance _ pst1 pst2).
rewrite (proof_irrelevance _ pd1 pd2).
rewrite (proof_irrelevance _ ps1 ps2).
rewrite (proof_irrelevance _ pt1 pt2).
rewrite (proof_irrelevance _ pl1 pl2).
rewrite (proof_irrelevance _ pr1 pr2).
rewrite (proof_irrelevance _ pa1 pa2).
reflexivity.
Qed.
|
chapter {* Generated by Lem from evm.lem. *}
theory "EvmAuxiliary"
imports
Main "~~/src/HOL/Library/Code_Target_Numeral"
"Lem_pervasives"
"Lem_word"
"Word256"
"Word160"
"Word8"
"Evm"
begin
(****************************************************)
(* *)
(* Termination Proofs *)
(* *)
(****************************************************)
termination store_byte_list_memory by lexicographic_order
(****************************************************)
(* *)
(* Lemmata *)
(* *)
(****************************************************)
lemma uint_to_address_def_lemma:
" ((\<forall> w. word160FromNat (unat w) = Word.ucast w)) "
(* Theorem: uint_to_address_def_lemma*)(* try *) by auto
lemma address_to_uint_def_lemma:
" ((\<forall> w. word256FromNat (unat w) = Word.ucast w)) "
(* Theorem: address_to_uint_def_lemma*)(* try *) by auto
lemma uint_to_byte_def_lemma:
" ((\<forall> w. word8FromNat (unat w) = Word.ucast w)) "
(* Theorem: uint_to_byte_def_lemma*)(* try *) by auto
lemma byte_to_uint_def_lemma:
" ((\<forall> w. word256FromNat (unat w) = Word.ucast w)) "
(* Theorem: byte_to_uint_def_lemma*)(* try *) by auto
lemma word_rsplit_def_lemma:
" ((\<forall> w. word_rsplit_aux (to_bl w) (( 32 :: nat)) = word_rsplit w)) "
(* Theorem: word_rsplit_def_lemma*)(* try *) by auto
lemma address_to_bytes_def_lemma:
" ((\<forall> w. word_rsplit_aux (to_bl w) (( 20 :: nat)) = word_rsplit w)) "
(* Theorem: address_to_bytes_def_lemma*)(* try *) by auto
lemma word_of_bytes_def_lemma:
" ((\<forall> lst. of_bl (List.concat (List.map to_bl lst)) = word_rcat lst)) "
(* Theorem: word_of_bytes_def_lemma*)(* try *) by auto
end
|
As many more areas around the globe fall to infection , a period known as the " Great Panic " begins . Pakistan and Iran destroy each other in a nuclear war , after the Iranian government attempts to stem the flow of refugees fleeing through Pakistan into Iran . After zombies overrun New York City , the U.S. military sets up a high @-@ profile defense in the nearby city of Yonkers . The " Battle of Yonkers " is a disaster ; modern weapons and tactics prove ineffective against zombies , as the enemy has no self @-@ preservation instincts and can only be stopped if shot through the head . The unprepared and demoralized soldiers are routed on live television . Other countries suffer similarly disastrous defeats , and human civilization teeters on the brink of destruction .
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for manipulating linear operators as elements of vector space."""
from typing import Dict, Tuple
import numpy as np
from cirq import value
from cirq._doc import document
PAULI_BASIS = {
'I': np.eye(2),
'X': np.array([[0.0, 1.0], [1.0, 0.0]]),
'Y': np.array([[0.0, -1j], [1j, 0.0]]),
'Z': np.diag([1.0, -1]),
}
document(PAULI_BASIS, """The four Pauli matrices (including identity) keyed by character.""")
def kron_bases(*bases: Dict[str, np.ndarray], repeat: int = 1) -> Dict[str, np.ndarray]:
"""Creates tensor product of bases."""
product_basis = {'': np.ones(1)}
for basis in bases * repeat:
product_basis = {
name1 + name2: np.kron(matrix1, matrix2)
for name1, matrix1 in product_basis.items()
for name2, matrix2 in basis.items()
}
return product_basis
def hilbert_schmidt_inner_product(m1: np.ndarray, m2: np.ndarray) -> complex:
"""Computes Hilbert-Schmidt inner product of two matrices.
Linear in second argument.
"""
return np.einsum('ij,ij', m1.conj(), m2)
def expand_matrix_in_orthogonal_basis(
m: np.ndarray,
basis: Dict[str, np.ndarray],
) -> value.LinearDict[str]:
"""Computes coefficients of expansion of m in basis.
We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner
product. We do not require that basis be orthonormal. Note that Pauli
basis (I, X, Y, Z) is orthogonal, but not orthonormal.
"""
return value.LinearDict(
{
name: (hilbert_schmidt_inner_product(b, m) / hilbert_schmidt_inner_product(b, b))
for name, b in basis.items()
}
)
def matrix_from_basis_coefficients(
expansion: value.LinearDict[str], basis: Dict[str, np.ndarray]
) -> np.ndarray:
"""Computes linear combination of basis vectors with given coefficients."""
some_element = next(iter(basis.values()))
result = np.zeros_like(some_element, dtype=np.complex128)
for name, coefficient in expansion.items():
result += coefficient * basis[name]
return result
def pow_pauli_combination(
ai: value.Scalar, ax: value.Scalar, ay: value.Scalar, az: value.Scalar, exponent: int
) -> Tuple[value.Scalar, value.Scalar, value.Scalar, value.Scalar]:
"""Computes non-negative integer power of single-qubit Pauli combination.
Returns scalar coefficients bi, bx, by, bz such that
bi I + bx X + by Y + bz Z = (ai I + ax X + ay Y + az Z)^exponent
Correctness of the formulas below follows from the binomial expansion
and the fact that for any real or complex vector (ax, ay, az) and any
non-negative integer k:
[ax X + ay Y + az Z]^(2k) = (ax^2 + ay^2 + az^2)^k I
"""
if exponent == 0:
return 1, 0, 0, 0
v = np.sqrt(ax * ax + ay * ay + az * az).item()
s = (ai + v) ** exponent
t = (ai - v) ** exponent
ci = (s + t) / 2
if s == t:
# v is near zero, only one term in binomial expansion survives
cxyz = exponent * ai ** (exponent - 1)
else:
# v is non-zero, account for all terms of binomial expansion
cxyz = (s - t) / 2
cxyz = cxyz / v
return ci, cxyz * ax, cxyz * ay, cxyz * az
|
CYM-100C - The Cuisinart Electronic Yogurt Maker with Automatic Cooling turns milk and soymilk into nutritious yogurt - automatically! Yogurt lovers can create an endless variety of flavours and the 1.5 liter batch makes enough for days of delicious meals and snacks. Operation is simple. Once processing time has elapsed, the unit switches itself to a cooling mode. It's easy to eat healthy, with Cuisinart! |
module Erlang.Debug
import Erlang
%default total
||| Print the underlying value using `io:format/2`.
export
erlPrintLn : HasIO io => a -> io ()
erlPrintLn x = do
pure $ erlUnsafeCall ErlTerm "io" "format" ["~p~n", the (ErlList _) [MkRaw x]]
pure ()
||| Print the underlying value using `io:format/2`, and return the given value.
|||
||| This function is unsafe as it breaks referential transparency.
export
erlInspect : a -> a
erlInspect x = unsafePerformIO $ do
erlPrintLn x
pure x
|
Formal statement is: lemma convexI: assumes "\<And>x y u v. x \<in> s \<Longrightarrow> y \<in> s \<Longrightarrow> 0 \<le> u \<Longrightarrow> 0 \<le> v \<Longrightarrow> u + v = 1 \<Longrightarrow> u *\<^sub>R x + v *\<^sub>R y \<in> s" shows "convex s" Informal statement is: If the convex combination of any two points in a set is also in the set, then the set is convex. |
!* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
!* See https://llvm.org/LICENSE.txt for license information.
!* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
! parallel do with cyclic schedule
program p
implicit none
integer n
parameter(n=10)
integer a(n)
integer result(n)
integer expect(n)
data expect/0,1,2,3,0,1,2,3,0,1/
integer i
do i = 1,n
a(i) = -1
enddo
call sp2(a,n)
! print *,a
do i = 1,n
result(i) = a(i)
enddo
call check(result,expect,n)
end
subroutine sp2(a,n)
implicit none
integer n
integer a(n)
integer iam, i, omp_get_thread_num
!$omp parallel private(iam)
iam = omp_get_thread_num()
!$omp do schedule(static,1)
do i = 1,n
a(i) = iam
enddo
!$omp end parallel
end
|
import Data.Array.CArray
import Data.Complex
import Data.List (intercalate, transpose)
import Math.FFT (dft, idft)
type Vector = CArray Int (Complex Double)
(.*), (.+) :: Vector -> Vector -> Vector
a .* b = liftArray2 (*) a b
a .+ b = liftArray2 (+) a b
normalize :: Double -> Vector -> Vector
normalize dx v =
let factor = 1 / sqrt dx / norm2 v :+ 0
in liftArray (factor *) v
data Parameters = Parameters
{ xmax :: Double
, res :: Int
, dt :: Double
, timesteps :: Int
, dx :: Double
, x :: Vector
, dk :: Double
, ks :: Vector
, imTime :: Bool
}
defaultParameters :: Parameters
defaultParameters = makeParameters 10 512 0.01 1000 True
makeParameters :: Double -> Int -> Double -> Int -> Bool -> Parameters
makeParameters xmax res dt timesteps imTime =
let fi = fromIntegral
rng = (0, res - 1)
ks = [0 .. div res 2 - 1] ++ [-div res 2 .. -1]
in Parameters
xmax
res
dt
timesteps
(2 * xmax / fi res)
(listArray rng $
map (\n -> xmax * (-1 + 2 * fi n / fi res) :+ 0) [1 .. res])
(pi / xmax)
(listArray rng $ map ((:+ 0) . (pi / xmax *) . fi) ks)
imTime
data Operators = Operators
{ v :: Vector
, rStep :: Vector
, kStep :: Vector
, wfc :: Vector
}
makeOperators :: Parameters -> Complex Double -> Complex Double -> Operators
makeOperators param v0 wfc0 =
let rng = (0, res param - 1)
time
| imTime param = dt param :+ 0
| otherwise = 0 :+ dt param
v = liftArray (\x -> 0.5 * (x - v0) ^ 2) (x param)
rStep = liftArray (\x -> exp (-0.5 * time * x)) v
kStep = liftArray (\k -> exp (-0.5 * time * k ^ 2)) (ks param)
wfc = liftArray (\x -> exp (-(x - wfc0) ^ 2 / 2)) (x param)
in Operators v rStep kStep (normalize (dx param) wfc)
evolve :: Parameters -> Operators -> [Operators]
evolve param op@(Operators _ rStep kStep _) = iterate splitop op
where
splitop op = op {wfc = wfc' op}
wfc' = norm . (rStep .*) . idft . (kStep .*) . dft . (rStep .*) . wfc
norm = if imTime param then normalize (dx param) else id
calculateEnergy :: Parameters -> Operators -> Double
calculateEnergy param ops = (* dx param) . sum . map realPart $ elems totalE
where
totalE = potentialE .+ kineticE
potentialE = wfcConj .* v ops .* wfc ops
kineticOp = liftArray ((/ 2) . (^ 2)) (ks param)
kineticE = wfcConj .* idft (kineticOp .* dft (wfc ops))
wfcConj = liftArray conjugate $ wfc ops
-- Use gnuplot to make an animated GIF using ../gnuplot/plot_output.plt
-- $ gnuplot -e "folder='../haskell'" plot_output.plt
printEvolution :: Parameters -> [Operators] -> IO ()
printEvolution param =
mapM_ (export . (format <$>)) . zip [0 ..] . take 100 . skip
where
skip (x:xs) = x : skip (drop (div (timesteps param) 100 - 1) xs)
format (Operators v _ _ wfc) =
let density = liftArray ((^ 2) . abs) wfc
values = map (map (show . realPart) . elems) [x param, density, v]
in intercalate "\n" $ map (intercalate "\t") $ transpose values
export (i, f) = writeFile ("output" ++ pad (show i) ++ ".dat") f
pad n = replicate (5 - length n) '0' ++ n
main :: IO ()
main = do
let p = defaultParameters
o = makeOperators p 0 4
evol = evolve p o
print $ calculateEnergy p (evol !! timesteps p)
printEvolution p evol
|
function [uOutput] = import_Iceland_PT(nFunction, sFilename)
% Filter function switchyard
%%%% CHANGE THESE LINES %%%%%%%%%%%
if nFunction == FilterOp.getDescription
uOutput = 'Iceland (with P/T-axes)';
elseif nFunction == FilterOp.getWebpage
uOutput = 'import_Iceland_PT_doc.html';
%%%% DO NOT CHANGE %%%%%%%%%%%
elseif nFunction == FilterOp.importCatalog
% Read formated data
mData = textread(sFilename, '%s', 'delimiter', '\n', 'whitespace', '');
% Create empty catalog
uOutput = zeros(length(mData), 12);
% Loop through all lines of catalog and convert them
mData = char(mData);
l = find( mData == ' ' );
mData(l) = '0';
errc = 1;
for i = 1:length(mData(:,1))
if rem(i,100) == 0 ; disp([ num2str(i) ' of ' num2str(length(mData)) ' events processed ']); end
try
uOutput(i,:) = readvalues(mData,i,1);
catch
errc = errc + 1;
if errc == 100
if stoploop
return
end
end
msg.dbfprintf('Import: Problem in line %d of %s. Line ignored.\n',i, sFilename);
uOutput(i,:)=nan;
end
end
l = isnan(uOutput(:,1));
uOutput(l,:) = [];
end
%%%%%%%%%%%%%%%%%%%%%%
%%%% CHANGE THESE LINES %%%%%%%%%%%
function [uOutput] = readvalues(mData,i,k)
uOutput(k,1) =-str2num(mData(i,29:30)) - (str2num(mData(i,31:35))/60); % Longitude
uOutput(k,2) = str2num(mData(i,20:21)) + (str2num(mData(i,22:26))/60); % Latitude
uOutput(k,3) = str2num(mData(i,2:3)) + 1900; % Year
uOutput(k,4) = str2num(mData(i,4:5)); % Month
uOutput(k,5) = str2num(mData(i,6:7)); % Day
uOutput(k,6) = str2num(mData(i,64:66)); % Magnitude
uOutput(k,7) = str2num(mData(i,37:41)); % Depth
uOutput(k,8) = str2num(mData(i,9:10)); % Hour
uOutput(k,9) = str2num(mData(i,11:12)); % Minute
fPTrend = str2double(mData(i,68:70));
fPDip = str2double(mData(i,72:73));
fTTrend = str2double(mData(i,75:77));
fTDip = str2double(mData(i,79:80));
% DipDirection, Dip, Rake
[uOutput(k,10), uOutput(k,11), uOutput(k,12)] = ex_pt2fm(fPTrend, fPDip, fTTrend, fTDip);
% Convert to decimal years
uOutput(k,3) = decyear([uOutput(k,3) uOutput(k,4) uOutput(k,5) uOutput(k,8) uOutput(k,9)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% DO NOT CHANGE %%%%%%%%%%%
function [mystop] = stoploop()
ButtonName=questdlg('More than 100 lines could not be read. Continue?', ...
'Interrupt?', ...
'Yes','No','Nope');
switch ButtonName
case 'Yes'
disp('going on');
mystop = 0;
case 'No'
mystop = 1;
end % switch
|
(***********************************************************************
* HiVe theory files
*
* Copyright (C) 2015 Commonwealth of Australia as represented by Defence Science and Technology
* Group (DST Group)
*
* All rights reserved.
*
* The HiVe theory files are free software: released for redistribution and use, and/or modification,
* under the BSD License, details of which can be found in the LICENSE file included in the
* distribution.
************************************************************************)
theory Value_Types
imports
Equipotence
Cartesian_Universe
begin
text {*
In a sense, having the value space be a disjoint union of all the
allowed value types is something of an overkill. In fact, all that
is required is that any given value type can be embedded in the
the value space. For example, in actual computer languages there is
really only one basic type, essentially the machine word, and all
other types are virtual in the sense that they are formed by re-interpretting
the meaning of a word. Aiding in the search for a suitable value
space is HOL's extensional approach to the introduction of type constructors.
The preferred method is to define new types via a representation set
in some existing type. In fact, in the existing HOL library there appear
to be only four basic type constructors, functions, booleans,
the so-called {\em individuals}
(basic to the development of number systems) and sets. All other
types (including datatypes) are constructed using representation sets built
from these basic constructors. In fact, even the booleans are easily embedded
in the individuals, which are countably infinite.
As described above,
the Cartesian Universe constructor takes an atomic type and constructs
a space large enough to contain disjoint images of all the
types built using the atomic type. the product constructor, and the
set constructor. The Cartesian Universe built from the
individuals is a space large enough to encompass
all of the types of standard HOL. Functions can be modelled
as sets of pairs.
*}
typedef
VAL = "\<univ>-[ind cartuniv]"
by (auto)
(*
lemma VAL_undef:
"set_The \<emptyset> = Abs_VAL (set_The \<emptyset>)"
apply (rule set_the_equality)
sorry
axioms
VAL_undef: "set_The \<emptyset> = Abs_VAL (set_The \<emptyset>)"
*)
interpretation
VAL: epi_type_definition "Rep_VAL" "Abs_VAL"
apply (rule type_definition.epiI)
apply (rule type_definition_VAL)
apply simp
done
text {*
In order to easily control the class of value types allowed in HiVe,
we introduce an axiomatic class to represent all types that have
have an injection @{text "\<vinj>"} into @{text VAL}. We also introduce
and associated projection @{text "\<vproj>"}.
Our approach to modelling this follows similar lines to that adopted for the
@{text order} axclass, we introduce a dummy class @{text "vtype"} for which
@{text "\<vinj>"} is defined. The desired class is then the subclass
@{text "valtype"} of @{text "vtype"} for which @{text "\<vinj>"} is injective.
We use this approach so that we can have fine control over the value of
@{text "\<vinj>"} for some type important type constructors, notably
@{text ind} and @{text set}.
*}
class vtype = typerep +
fixes
vinj :: "'a \<rightarrow> VAL"
begin
definition
vproj :: "VAL \<rightarrow> 'a"
where
vproj_def: "vproj \<defs> inv vinj"
notation (xsymbols output)
vinj ("\<nu>\<iota>") and
vproj ("\<nu>\<pi>")
notation (zed)
vinj ("\<vinj>") and
vproj ("\<vproj>")
end
class
valtype = vtype +
assumes
vinj_inj: "inj \<vinj>"
lemma (in valtype) vinj_inverse: "\<vproj> (\<vinj> x) = x"
by (auto simp add: vproj_def vinj_inj [THEN inv_f_f])
(*
lemma vinj_inverse: "\<vproj> (\<vinj>-['a::valtype] x) = x"
by (auto simp add: vproj_def vinj_inj [THEN inv_f_f])
*)
lemma (in valtype) vinj_o_inverse:
"\<vproj> \<circ> \<vinj> = id"
by (simp add: vproj_def vinj_inj)
lemma (in valtype) vproj_inverse:
"x \<in> range \<vinj>
\<turnstile> \<vinj> (\<vproj> x) = x"
by (simp add: vproj_def f_inv_into_f [of _ _ "\<univ>"])
instantiation
VAL :: vtype
begin
definition
VAL_vinj_def: "\<vinj>-[VAL] \<defs> id"
instance
by (intro_classes)
end
instance
VAL :: valtype
apply (intro_classes)
apply (auto simp add: VAL_vinj_def)
done
text {*
For the purposes of performing the injection proofs, generally we find it more
convenient (especially in the case of datatype constructors) to argue
on an abstract cardinality level. To allow this we introduce parallel
axiomatic classes @{text vcard}, for types with cardinality less than
@{text VAL}, and @{text svcard}, for those with cardinality less than
some rank of @{text VAL}.
*}
class
vcard = typerep +
assumes
vcard: "\<^sEP>{:\<univ>:}{:\<univ>-[VAL]:}"
lemma vcardI':
fixes
f::"'a \<rightarrow> VAL"
assumes
a1: "inj f"
shows
"OFCLASS('a, vcard_class)"
proof (intro_classes)
from a1 have
"(\<graphof> f) \<in> \<univ> \<zinj> \<univ>"
by (rule graph_of_f_inj)
then show
"\<^sEP>{:\<univ>-['a]:}{:\<univ>-[VAL]:}"
by (auto simp add: subequipotent_def)
qed
instance
valtype \<subseteq> vcard
apply (rule vcardI')
apply (rule vinj_inj)
done
lemma vcard_inj_ex:
"(\<exists> f::('a::vcard) \<rightarrow> VAL \<bullet> inj f)"
proof -
from vcard obtain f where
"f \<in> \<univ>-['a] \<zinj> \<univ>-[VAL]"
by (auto simp add: subequipotent_def)
then have
b2: "inj (\<opof> f)"
apply (intro fun_of_f_inj)
apply (mauto(fspace))
done
then show
?thesis
by (auto)
qed
text {*
While the existence on an injection is sufficient to provide
the required type embedding @{text "\<vinj>"}
into @{text VAL} it is not sufficient to ensure that set and function
values can be used as value types. To ensure this we must introduce
stronger class restrictions, namely that the image of
the injection is completely enclosed in a single cartesion rank.
To achieve this we introduce another axiomatic class, the strong
value types @{text "svcard"}.
We require visibility of the rank structure of @{text VAL}, made invisible by the
type definition mechanism.
*}
definition
vrank :: "CT \<rightarrow> VAL set"
where
"vrank T \<defs> Abs_VAL\<lparr>\<chi>-[ind] T\<rparr>"
no_notation
carrier_set ("\<chi>")
notation
vrank ("\<chi>")
lemma vrank_disjoint:
"((\<chi> t_d_1) \<inter> (\<chi> t_d_2)) \<noteq> \<emptyset> \<Leftrightarrow> t_d_1 = t_d_2"
apply (subst carrier_disjoint [symmetric])
apply (auto simp add: vrank_def VAL.Abs_inject)
done
lemma vrank_cover:
"\<univ>-[VAL] = \<Union> {t \<bullet> \<chi> t}"
proof -
have
"\<univ>-[VAL]
= Abs_VAL \<lparr>\<univ>-[ind cartuniv]\<rparr>"
using VAL.Rep_inverse [symmetric]
by (auto simp add: image_def)
also have
"\<univ>-[ind cartuniv]
= \<Union> {t \<bullet> carrier_set t}"
by (rule carrier_cover [where ?'a = "ind"])
also have
"Abs_VAL \<lparr>\<Union> {t \<bullet> carrier_set t}\<rparr>
= \<Union> {t \<bullet> \<chi> t}"
by (auto simp add: vrank_def eind_def)
finally show
?thesis
by (this)
qed
lemma vrank_nemp:
"(\<exists> a \<bullet> a \<in> \<chi> T)"
proof -
from carrier_nemp obtain x::"ind cartuniv" where
"x \<in> carrier_set T"
by (auto)
then show
"?thesis"
apply (witness "Abs_VAL x")
apply (auto simp add: vrank_def VAL.Rep_inverse)
done
qed
lemma vrank_nuniv:
"(\<exists> a \<bullet> a \<notin> \<chi> T)"
proof -
from carrier_nuniv obtain x::"ind cartuniv" where
"x \<notin> carrier_set T"
by (auto)
then show
"?thesis"
apply (witness "Abs_VAL x")
apply (elim contrapos_nn)
apply (auto simp add: vrank_def image_def VAL.Abs_inject)
done
qed
lemma vrank_eq:
assumes
a1: "a \<in> \<chi> s"
shows
"a \<in> \<chi> t \<Leftrightarrow> t = s"
apply (subst carrier_eq [of "Rep_VAL a", symmetric])
using a1
apply (auto simp add: vrank_def VAL.Abs_inverse)
done
lemma vrankI: "(\<exists> t \<bullet> a \<in> \<chi> t)"
proof -
from carrierI obtain t where
"Rep_VAL a \<in> carrier_set t"
by (auto)
then show
"(\<exists> t \<bullet> a \<in> \<chi> t)"
apply (witness "t")
apply (auto simp add: vrank_def image_def VAL.Rep_inverse)
done
qed
lemma vrank_eqI:
assumes
a1: "a \<in> \<chi> s"
shows
"a \<in> \<chi> t \<turnstile> t = s"
by (simp add: vrank_eq [OF a1])
class
svcard = typerep +
assumes
svcard: "(\<exists> T \<bullet> \<^sEP>{:\<univ>-['a]:}{:\<chi> T:})"
instance
svcard \<subseteq> vcard
proof (intro_classes)
from svcard obtain T where
"\<^sEP>{:\<univ>-['a]:}{:\<chi> T:}"
by (auto)
also have
"\<^sEP>{:\<chi> T:}{:\<univ>-[VAL]:}"
apply (rule subset_subequipotent)
apply (auto)
done
finally show
"\<^sEP>{:\<univ>-['a]:}{:\<univ>-[VAL]:}"
by (this)
qed
lemma svcardI':
fixes
f::"'a \<rightarrow> VAL" and
T::CT
assumes
a1: "inj f" and
a2: "range f \<subseteq> \<chi> T"
shows
"OFCLASS('a, svcard_class)"
proof (intro_classes)
from a1 have
"(\<graphof> f) \<in> \<univ> \<zinj> \<univ>"
by (rule graph_of_f_inj)
with a2 have
"(\<graphof> f) \<in> \<univ> \<zinj> (\<chi> T)"
apply (mauto(fspace))
apply (auto simp add: graph_of_def glambda_ran)
done
then show
"(\<exists> T \<bullet> \<^sEP>{:\<univ>-['a]:}{:\<chi> T:})"
by (auto simp add: subequipotent_def)
qed
lemma svcard_inj_ex:
"(\<exists> f::('a::svcard) \<rightarrow> VAL \<bullet> inj f \<and> (\<exists> T \<bullet> range f \<subseteq> \<chi> T))" (is "(\<exists> f \<bullet> ?P f)")
proof -
from svcard obtain f T where
b1: "f \<in> \<univ>-['a] \<zinj> (\<chi> T)"
by (auto simp add: subequipotent_def)
then have
b2: "inj (\<opof> f)"
apply (intro fun_of_f_inj)
apply (mauto(fspace))
done
from b1 have
b3: "range (\<opof> f) \<subseteq> \<chi> T"
by (auto)
from b2 b3 have
"?P (\<opof> f)"
by (auto)
then show
?thesis
by (auto)
qed
text {*
On the basis of the class constraints on @{text "vcard"}, we are able
to introduce a default value injection for each such type.
Since the exact value of this injection is unimportant, we define it
through the Hilbert choice operator, requiring only that it be
injective and that where possible its range has a uniform Cartesian type.
*}
context typerep
begin
definition
cinj :: "'a \<rightarrow> VAL"
where
cinj_typerep_def: "cinj \<defs>
\<if> (\<exists> T \<bullet> \<^sEP>{:\<univ>-['a]:}{:\<chi> T:}) \<then>
(\<some> f | inj f \<and> (\<exists> T \<bullet> range f \<subseteq> \<chi> T))
\<elif> \<^sEP>{:\<univ>-['a]:}{:\<univ>-[VAL]:} \<then>
(\<some> f | inj f)
\<else>
(\<some> f | range f = \<univ>-[VAL])
\<fi>"
end
context vcard
begin
lemma cinj_vcard_cases:
"cinj = (\<some> f | inj f) \<or> (\<exists> T \<bullet> \<^sEP>{:\<univ>-['a]:}{:\<chi> T:} \<and> cinj = (\<some> f | inj f \<and> (\<exists> T \<bullet> range f \<subseteq> \<chi> T)))"
using vcard
by (simp add: cinj_typerep_def)
lemma cinj_inj:
"inj cinj" (is "?P cinj")
using cinj_vcard_cases
apply (msafe(inference))
proof -
from vcard obtain f where
"f \<in> \<univ>-['a] \<zinj> \<univ>-[VAL]"
by (auto simp add: subequipotent_def)
then have
b2: "inj (\<opof> f)"
apply (intro fun_of_f_inj)
apply (mauto(fspace))
done
assume
b3: "cinj = (\<some> f | ?P f)"
from b2 show
"inj cinj"
apply (simp add: b3)
by (rule someI [of ?P])
next
fix
T
assume
b1: "\<^sEP>{:\<univ>-['a]:}{:\<chi> T:}" and
b2: "cinj = (\<some> f | inj f \<and> (\<exists> T \<bullet> range f \<subseteq> \<chi> T))" (is "cinj = (\<some> f | ?Q f)")
from b1 obtain f where
b3: "f \<in> \<univ>-['a] \<zinj> \<chi> T"
by (auto simp add: subequipotent_def)
then have
b4: "inj (\<opof> f)"
apply (intro fun_of_f_inj)
apply (mauto(fspace))
done
from b3 have
b5: "range (\<opof> f) \<subseteq> \<chi> T"
by (auto)
from b4 b5 have
"?Q (\<opof> f)"
by (auto)
then have
"?Q cinj"
apply (simp add: b2)
by (rule someI [of ?Q])
then show
"?P cinj"
by (auto)
qed
end
abbreviation
scinj :: "('a::svcard) \<rightarrow> VAL"
where
"scinj \<defs> cinj"
lemma
scinj_def: "scinj = (\<some> f | inj f \<and> (\<exists> T \<bullet> range f \<subseteq> \<chi> T))"
using svcard
by (auto simp add: cinj_typerep_def)
definition
scCT_of :: "('a::svcard) itself \<rightarrow> CT"
where
scCT_of_def: "scCT_of TYPE('a::svcard) \<defs> (\<mu> T | range (scinj::'a \<rightarrow> VAL) \<subseteq> \<chi> T)"
syntax (zed)
"_scCT" :: "logic" ("\<^scCT>")
"_scCTa" :: "type \<rightarrow> logic" ("\<^scCT>[:_:]")
translations
"\<^scCT>" \<rightharpoonup> "CONST Value_Types.scCT_of \<arb>"
"\<^scCT>[:'a:]" \<rightharpoonup> "CONST Value_Types.scCT_of TYPE('a)"
lemma scinj_char:
"inj scinj-['a::svcard] \<and> (\<exists> T \<bullet> range scinj-['a::svcard] \<subseteq> \<chi> T)"
(is "?P scinj")
proof (unfold scinj_def)
from svcard obtain f T where b1: "f \<in> \<univ>-['a] \<zinj> \<chi> T"
by (auto simp add: subequipotent_def)
then have b2: "inj (\<opof> f)"
apply (intro fun_of_f_inj)
apply (mauto(fspace))
done
from b1 have b3: "range (\<opof> f) \<subseteq> \<chi> T"
by (auto)
from b2 b3 have "?P (\<opof> f)"
by (auto)
then show "?P (\<some> f | ?P f)"
by (rule someI [of ?P])
qed
lemma scinj_inj:
"inj scinj"
by (simp add: cinj_inj)
lemma scinj_bound_inj':
"(\<exists>\<subone> T \<bullet> range scinj \<subseteq> \<chi> T)"
proof -
from scinj_char
obtain T where b1: "range scinj-['a] \<subseteq> \<chi> T"
by (auto)
show "\<exists>\<subone> T \<bullet> range scinj-['a] \<subseteq> \<chi> T"
proof (rule ex1I)
from b1 show "range scinj-['a] \<subseteq> \<chi> T"
by (this)
next
fix S
assume c1: "range scinj-['a] \<subseteq> \<chi> S"
with b1 have "scinj-['a] \<arb> \<in> \<chi> S" "scinj-['a] \<arb> \<in> \<chi> T"
by (auto)
then have "\<chi> S \<inter> \<chi> T \<noteq> \<emptyset>"
by (auto)
then show "S = T"
by (simp add: vrank_disjoint)
qed
qed
lemma scinj_bound_inj:
"(\<exists> T \<bullet> range scinj \<subseteq> \<chi> T)"
using scinj_bound_inj'
by (auto)
lemma scinj_bound_scCT:
"range (scinj-['a::svcard]) \<subseteq> \<chi> \<^scCT>[:'a::svcard:]"
apply (simp add: scCT_of_def)
apply (rule theI' [OF scinj_bound_inj'])
done
text {*
The @{text "svcard"} class has strong enough properties to ensure
closure under the set and function type constructors and we can thus
show that it encompasses the entirety of the base HOL type algebra.
We also find it useful to introduce a strengthened version of
@{text "valtype"} where the range on the value injection is
contained in a single rank.
*}
class
svaltype = valtype +
assumes
bound_vinj: "\<exists> T \<bullet> range \<vinj> \<subseteq> (\<chi> T)"
instance
svaltype \<subseteq> svcard
proof (intro_classes)
from bound_vinj obtain T where
"range \<vinj>-['a] \<subseteq> (\<chi> T)"
by (auto)
with vinj_inj [THEN graph_of_f_inj]
have
"(\<graphof> \<vinj>-['a]) \<in> \<univ>-['a] \<zinj> (\<chi> T)"
apply (mauto(fspace))
apply (auto simp add: graph_of_def glambda_def Range_def Domain_def)
done
then show
"(\<exists> T \<bullet> \<^sEP>{:\<univ>-['a]:}{:((\<chi> T)::VAL set):})"
by (auto simp add: subequipotent_def)
qed
lemma svaltype_bound_unique:
"(\<exists>\<subone> T \<bullet> range \<vinj>-['a::svaltype] \<subseteq> (\<chi> T))"
proof -
show
?thesis
apply (intro ex_ex1I [OF bound_vinj] vrank_disjoint [THEN iffD1])
proof -
fix T_d_1 T_d_2
assume
c1: "range \<vinj>-['a] \<subseteq> (\<chi> T_d_1)" "range \<vinj>-['a] \<subseteq> (\<chi> T_d_2)"
obtain x where
c2: "x \<in> \<univ>-['a]"
by (auto)
from c1 c2 have
c3: "\<vinj> x \<in> \<chi> T_d_1"
by (auto)
from c1 c2 have
c4: "\<vinj> x \<in> \<chi> T_d_2"
by (auto)
from c3 c4 show
"\<chi> T_d_1 \<inter> \<chi> T_d_2 \<noteq> \<emptyset>"
apply (simp add: nempty_conv)
apply (auto)
done
qed
qed
text {*
The image of any element under @{text "\<vinj>"} has a unique Cartesian
type, so we can uniquely associate each object of class @{text "vtype"} with
a Cartesian type.
*}
definition
CT_of_val :: "('a::vtype) \<rightarrow> CT"
where
CT_of_val_def: "CT_of_val x \<defs> (\<mu> t | \<vinj> x \<in> \<chi> t)"
text {*
The range of any type in class @{text "svaltype"} is contained in a Cartesion type.
*}
definition
CT_of :: "('a::svaltype) itself \<rightarrow> CT"
where
CT_of_def: "CT_of TYPE('a::svaltype) \<defs> (\<mu> t | range \<vinj>-['a] \<subseteq> \<chi> t)"
syntax
"_CT" :: "type \<rightarrow> logic" ("\<^CT>{:_:}")
translations
"\<^CT>{:'a:}" \<rightleftharpoons> "CONST Value_Types.CT_of TYPE('a)"
lemma CT_of_val_char:
"\<vinj> x \<in> \<chi> (CT_of_val x)" (is "?P (CT_of_val x)")
proof -
from vrankI obtain t where
b1: "\<vinj> x \<in> \<chi> t"
by (auto)
with vrank_eq
show
"?thesis"
by (auto intro!: theI [of "?P"] simp add: CT_of_val_def)
qed
text {*
We note that the elements of an @{text "svaltype"} type have uniform
Cartesian type.
*}
lemmas CT_of_char = svaltype_bound_unique [THEN theI', folded CT_of_def]
lemmas CT_of_unique = the1_equality [OF svaltype_bound_unique, symmetric, folded CT_of_def]
lemma CT_of_val_eq:
fixes
x::"'a::svaltype"
shows
"CT_of_val x = \<^CT>{:'a:}"
proof -
from bound_vinj obtain T where
b1: "range \<vinj>-['a] \<subseteq> \<chi> T"
by (auto)
from b1 have
b2: "\<vinj> x \<in> \<chi> T"
by (auto)
from CT_of_val_char [of "x"] CT_of_unique [OF b1] vrank_eq [OF b2] show
?thesis
by (auto simp add: eind_def)
qed
lemma CT_of_char':
fixes
"x"::"'a::svaltype"
shows
"\<vinj> x \<in> \<chi> \<^CT>{:'a::svaltype:}"
using CT_of_val_char [of "x"]
by (simp add: CT_of_val_eq)
lemma CT:
"range \<vinj>-['a::svaltype] \<subseteq> \<chi> \<^CT>{:'a::svaltype:}"
by (rule CT_of_char)
lemma CT':
"(\<exists> T \<bullet> range \<vinj>-['a::vtype] \<subseteq> \<chi> T) \<turnstile> range \<vinj>-['a::vtype] \<subseteq> \<chi> (CT_of_val (a::'a))"
proof (msafe_no_assms(inference))
fix T assume
b1: "range \<vinj>-['a] \<subseteq> \<chi> T"
show
"range \<vinj>-['a] \<subseteq> \<chi> (CT_of_val a)"
proof (auto)
fix x::'a
from b1 have
c1: "\<vinj>-['a] x \<in> \<chi> T" and
c2: "\<vinj>-['a] a \<in> \<chi> T"
by (auto)
from CT_of_val_char [of "x"] CT_of_val_char [of "a"]
vrank_eq [OF c1] vrank_eq [OF c2] b1
have
"T = CT_of_val a"
by (auto)
with c1 show
"\<vinj>-['a] x \<in> \<chi> (CT_of_val a)"
by (simp)
qed
qed
lemma ransvinj_nuniv:
"(\<exists> a \<bullet> a \<notin> range \<vinj>-['a::svaltype])"
proof -
have
"(\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T)"
by (rule bound_vinj)
also have
"(\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T)
\<Leftrightarrow> (\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T \<and> (\<exists> a::VAL \<bullet> a \<notin> \<chi> T))"
by (auto intro!: vrank_nemp vrank_nuniv)
also have "\<dots>
\<Leftrightarrow> (\<exists> T (a::VAL) \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T \<and> a \<notin> \<chi> T)"
by (auto)
also have "\<dots>
\<Rightarrow> (\<exists> T (a::VAL) \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T \<and> a \<notin> range \<vinj>-['a])"
by (mauto(wind))
finally show
"(\<exists> (a::VAL) \<bullet> a \<notin> range \<vinj>-['a])"
by (auto)
qed
lemma CT_eq:
assumes
a1: "range \<vinj>-['a::svaltype] \<subseteq> \<chi> T"
shows
"\<^CT>{:'a:} = T"
by (simp add: CT_of_unique [OF a1])
subsection {* Cartesion constructors *}
text {*
We pause to lift the @{text cartuniv} rank constructors to @{text "VAL"}.
*}
definition
vatom_of :: "ind => VAL"
where
"vatom_of i \<defs> Abs_VAL (atom_of i)"
definition
vset_of :: "[CT, VAL set] \<rightarrow> VAL"
where
"vset_of T CL_V \<defs> Abs_VAL (set_of T Rep_VAL\<lparr>CL_V\<rparr>)"
definition
vprod_of :: "(VAL \<times> VAL) \<rightarrow> VAL"
where
"vprod_of uv \<defs> Abs_VAL (prod_of (Rep_VAL (fst uv), Rep_VAL (snd uv)))"
lemma vrank_catom:
"\<chi> catom = vatom_of\<lparr>UNIV-[ind]\<rparr>"
by (auto simp add: vatom_of_def vrank_def image_def chi_catom_mem)
lemma vrank_cset:
"\<chi> (cset T) = (vset_of T)\<lparr>\<pset> (\<chi> T)\<rparr>"
apply (simp add: vrank_def vset_of_def [abs_def] Pow_image image_comp_dist chi_cset image_dist [of "(\<olambda> CL_V \<bullet> Abs_VAL (set_of T CL_V))" "image Rep_VAL"] image_dist [of "Abs_VAL" "set_of T"])
apply (simp add: image_aggregate VAL.Abs_inverse_raw image_id)
done
lemma vrank_cprod:
"\<chi> (cprod T S) = vprod_of\<lparr>(\<chi> T) \<times> (\<chi> S)\<rparr>"
apply (simp add: vrank_def chi_cprod vprod_of_def [abs_def] image_comp_dist image_dist [of "Abs_VAL" "(\<olambda> uv \<bullet> prod_of (Rep_VAL (fst uv), Rep_VAL (snd uv)))"] image_dist [of "prod_of" "(\<olambda> uv \<bullet> (Rep_VAL (fst uv), Rep_VAL (snd uv)))"] map_pair_def [symmetric, simplified split_def] image_map_pair)
apply (simp add: image_aggregate VAL.Abs_inverse_raw)
done
lemma vprod_of_split:
"vprod_of (u, v) = Abs_VAL (prod_of (Rep_VAL u, Rep_VAL v))"
by (auto simp add: vprod_of_def)
lemma inj_vatom_of:
"inj vatom_of"
using inj_atom_of [where ?'a = "ind", THEN injD] VAL.Abs_inject
by (auto intro!: injI simp add: vatom_of_def)
lemmas vatom_of_eq = inj_vatom_of [THEN inj_eq]
lemma inj_vprod_of:
"inj vprod_of"
apply (rule injI)
using inj_prod_of [where ?'a = "ind", THEN inj_eq] VAL.Abs_inject VAL.Rep_inject
apply (auto simp add: vprod_of_split)
done
lemmas vprod_of_eq = inj_vprod_of [THEN inj_eq]
lemma vset_of_eq:
"vset_of s A = vset_of t B \<Leftrightarrow> s = t \<and> A \<inter> \<chi> s = B \<inter> \<chi> t"
apply (simp add: vset_of_def vrank_def VAL.Abs_inject set_of_eq)
apply (subst VAL.Rep_image_eq_iff [symmetric])
apply (simp add: VAL.Rep_image_Int VAL.Abs_inverse_image)
done
lemma inj_on_vset_of_t:
"inj_on (vset_of t) (\<pset> (\<chi> t))"
apply (rule inj_onI)
apply (auto simp add: vset_of_eq)
done
lemma vatom_of_rank:
"vatom_of i \<in> \<chi> catom"
by (auto simp add: vatom_of_def vrank_def image_def chi_catom_mem)
lemma vprod_of_rank:
assumes
a1: "a \<in> \<chi> T" and
a2: "b \<in> \<chi> S"
shows
"vprod_of (a, b) \<in> \<chi> (cprod T S)"
proof -
from a1 a2 have
b1: "(Rep_VAL a, Rep_VAL b) \<in> carrier_set T \<times> carrier_set S"
by (auto simp add: vrank_def VAL.Abs_inverse)
from prod_of_char [OF b1] show
"?thesis"
by (simp add: vprod_of_def vrank_def)
qed
lemma vprod_of_rank':
assumes
a1: "ab \<in> \<chi> T \<times> \<chi> S"
shows
"vprod_of ab \<in> \<chi> (cprod T S)"
using a1 vprod_of_rank [of "fst ab" _ "snd ab"]
by (auto)
lemma vset_of_rank:
assumes
a1: "S \<subseteq> \<chi> t"
shows
"vset_of t S \<in> \<chi> (cset t)"
proof -
from a1 have
b1: "Rep_VAL\<lparr>S\<rparr> \<subseteq> carrier_set t"
by (simp add: vrank_def VAL.Rep_image_connect)
from set_of_char [OF b1] show
"?thesis"
by (simp add: vset_of_def vrank_def)
qed
subsection {* Some basic @{text vtype} instance proofs *}
text {*
Firstly, we observe the @{text "\<bool>"} and @{text ind} are in @{text svcard}
and that the @{text set} and @{text "\<times>"} constructors preserve
@{text svcard}.
*}
instance
bool :: svcard
proof (intro_classes)
let ?f = "(\<olambda> b::\<bool> \<bullet> \<if> b \<then> vatom_of (Suc_Rep Zero_Rep) \<else> vatom_of Zero_Rep \<fi>)"
note Suc_Rep_not_Zero_Rep [of Zero_Rep]
then have
b1: "inj ?f"
by (auto simp add: inj_on_def inj_vatom_of [THEN inj_eq]) -- "@{text atom_of} primrec"
have
"range ?f \<subseteq> \<chi> catom"
by (auto simp add: vatom_of_rank)
with graph_of_f_inj [OF b1]
show
"(\<exists> T \<bullet> \<^sEP>{:\<univ>-[\<bool>]:}{:((\<chi> T)::VAL set):})"
apply (witness "catom")
apply (simp add: subequipotent_def)
apply (witness "\<graphof> ?f")
apply (mauto(fspace))
apply (auto simp add: graph_of_def glambda_ran eind_def)
done
qed
text {*
The next step is to define a value injection for @{text "\<bool>"} and
to show that it is a bound injection. Since we have no particular need to
control the value of the Boolean value injection, we use it as a demonstration of
our general approach to defining the value injection, setting it equal to
@{text scinj}.
*}
instantiation (* type: bool *)
bool :: svaltype
begin
definition
bool_vinj_def: "\<vinj>-[\<bool>] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: bool_vinj_def)
done
end
text {*
This same technique, with essentially the same strong value type
instance proof can be used for any strong cardinality type.
Next we consider the individuals, a type which we do want to have control
over the value injection since we wish to have the basic Cartesian
universe types mapped to their natural image in @{text VAL}. Since, we
wish to separately define the value injection, we directly show that
@{text ind} is in @{text svaltype}, thus indirectly establishing its
membership of @{text svcard}.
*}
instantiation (* type: Nat.ind *)
Nat.ind :: svaltype
begin
definition
ind_vinj_def: "\<vinj>-[ind] \<defs> vatom_of"
instance
proof (intro_classes, unfold ind_vinj_def)
show "inj vatom_of"
by (rule inj_vatom_of)
show "\<exists> T \<bullet> range vatom_of \<subseteq> \<chi> T"
apply (witness "catom")
apply (auto simp add: vatom_of_rank)
done
qed
end
lemma CT_ind:
"\<^CT>{:ind:} = catom"
apply (rule CT_eq)
apply (auto simp add: ind_vinj_def vatom_of_rank)
done
text {*
We use similar techniques for both the set constructor and the product
constructor, though we also show that products preserve @{text valtype} as
well.
*}
lemma vprod_card:
fixes
f_d_1::"'a_d_1 \<rightarrow> VAL" and
f_d_2::"'a_d_2 \<rightarrow> VAL" and
T_d_1::CT and
T_d_2::CT
assumes
a1: "inj f_d_1" "inj f_d_2" and
a2: "range f_d_1 \<subseteq> (\<chi> T_d_1)" "range f_d_2 \<subseteq> (\<chi> T_d_2)"
shows
"inj (\<olambda> (x_d_1, x_d_2) \<bullet> vprod_of (f_d_1 x_d_1, f_d_2 x_d_2)) \<and>
range (\<olambda> (x_d_1, x_d_2) \<bullet> vprod_of (f_d_1 x_d_1, f_d_2 x_d_2)) \<subseteq> \<chi> (cprod T_d_1 T_d_2)"
(is "inj ?f \<and> range ?f \<subseteq> \<chi> ?T")
proof (msafe_no_assms(inference))
show "inj ?f"
apply (rule inj_onI)
apply (auto intro: a1 [THEN inj_onD] simp add: vprod_of_eq)
done
from a2 show "range ?f \<subseteq> \<chi> ?T"
by (auto simp add: image_def subset_def vrank_cprod vprod_of_def)
qed
instance
prod :: (svcard, svcard) svcard
proof -
have b1: "inj scinj-['a]" "inj scinj-['b]"
by (auto intro!: scinj_inj)
have b2: "(\<exists> T \<bullet> range scinj-['a] \<subseteq> \<chi> T)" "(\<exists> T \<bullet> range scinj-['b] \<subseteq> \<chi> T)"
by (auto intro!: scinj_bound_inj)
from vprod_card [OF b1 b2 [THEN someI_ex]]
show "OFCLASS('a \<times> 'b, svcard_class)"
apply (intro svcardI')
apply (mauto(inference))
done
qed
instantiation (* type: * *)
prod :: (svaltype, svaltype) svaltype
begin
definition
prod_vinj_def: "\<vinj>-['a \<times> 'b] \<defs> (\<olambda> (a, b) \<bullet> vprod_of (\<vinj> a, \<vinj> b))"
instance
proof (intro_classes)
have b1:
"range \<vinj>-['a] \<subseteq> \<chi> (\<mu> T | range \<vinj>-['a] \<subseteq> \<chi> T)"
"range \<vinj>-['b] \<subseteq> \<chi> (\<mu> T | range \<vinj>-['b] \<subseteq> \<chi> T)"
apply (rule svaltype_bound_unique [THEN theI'])
apply (rule svaltype_bound_unique [THEN theI'])
done
from vprod_card [OF vinj_inj vinj_inj b1]
show "inj \<vinj>-['a \<times> 'b]"
by (auto simp add: prod_vinj_def)
from vprod_card [OF vinj_inj vinj_inj b1]
show "\<exists> T \<bullet> range \<vinj>-['a \<times> 'b] \<subseteq> \<chi> T"
apply (msafe_no_assms(inference))
apply (witness "cprod (\<mu> T | range \<vinj>-['a] \<subseteq> \<chi> T) (\<mu> T | range \<vinj>-['b] \<subseteq> \<chi> T)")
apply (simp add: prod_vinj_def)
done
qed
end
lemma CT_prod:
"\<^CT>{:('a::svaltype) \<times> ('b::svaltype):} = cprod \<^CT>{:'a::svaltype:} \<^CT>{:'b::svaltype:}"
proof -
have b1: "range \<vinj>-['a] \<subseteq> \<chi> \<^CT>{:'a:}"
by (rule CT)
have b2: "range \<vinj>-['b] \<subseteq> \<chi> \<^CT>{:'b:}"
by (rule CT)
from b1 b2 show ?thesis
apply (intro CT_eq)
apply (auto simp add: prod_vinj_def image_def subset_def vrank_cprod)
done
qed
text {*
A prime driver in our development of the value types classes is to ensure that the function embedding can be properly understood at the @{text "VAL"} level, even in the absence of knowledge of the underlying domain and range types.
To achieve this we need to craft the value embedding to a particular form.
This form is based on functional graphs with uniformly ranked domain and range.
Such graphs can be embedding in @{text "VAL"} as a relation ranked value and a suitable application operator defined.
We start by using the domain and range type embeddings to construct a graph over @{text "VAL"}.
*}
definition
VAL_graph :: "(('a::svaltype) \<rightarrow> ('b::svaltype)) \<rightarrow> (VAL \<leftrightarrow> VAL)"
where
VAL_graph_def: "VAL_graph f \<defs> { a \<bullet> (\<vinj>-['a] a, \<vinj>-['b] (f a)) }"
lemma VAL_graph_dom_char:
"\<zdom> (VAL_graph-['a::svaltype,'b::svaltype] f) \<subseteq> \<chi> \<^CT>{:'a::svaltype:}"
by (auto intro: CT_of_char' simp add: VAL_graph_def)
lemma VAL_graph_ran_char:
"\<zran> (VAL_graph (f::('a::svaltype) \<rightarrow> ('b::svaltype))) \<subseteq> \<chi> \<^CT>{:'b::svaltype:}"
by (auto intro: CT_of_char' simp add: VAL_graph_def)
lemma VAL_graph_rel:
"VAL_graph (f::('a::svaltype) \<rightarrow> ('b::svaltype)) \<in> \<chi> \<^CT>{:'a::svaltype:} \<zrel> \<chi> \<^CT>{:'b::svaltype:}"
apply (mauto(fspace))
apply (intro VAL_graph_dom_char VAL_graph_ran_char)+
done
lemma VAL_graph_functional:
"functional (VAL_graph f)"
proof -
have
b1: "inj \<vinj>-['a]"
by (rule vinj_inj)
have
b2: "inj \<vinj>-['b]"
by (rule vinj_inj)
show ?thesis
by (auto intro!: functionalI simp add: VAL_graph_def inj_eq [OF b1] inj_eq [OF b2])
qed
lemma VAL_graph_beta:
"(VAL_graph (f::('a::svaltype) \<rightarrow> ('b::svaltype)))\<cdot>(\<vinj>-['a::svaltype] x) = \<vinj>-['b::svaltype] (f x)"
apply (rule functional_beta)
apply (rule VAL_graph_functional)
apply (auto simp add: VAL_graph_def)
done
lemma VAL_graph_tfun:
"VAL_graph (f::('a::svaltype) \<rightarrow> ('b::svaltype)) \<in> (range \<vinj>-['a::svaltype]) \<ztfun> (range \<vinj>-['b::svaltype])"
proof -
show ?thesis
apply (mauto(fspace))
apply (rule VAL_graph_functional)
apply (auto simp add: VAL_graph_def prod_vinj_def eind_def)
done
qed
lemma range_VAL_graph_is_tfun:
"range VAL_graph-['a::svaltype, 'b::svaltype] = (range \<vinj>-['a::svaltype]) \<ztfun> (range \<vinj>-['b::svaltype])"
apply (auto)
apply (rule VAL_graph_tfun)
proof -
fix
f
assume
b1: "f \<in> (range \<vinj>-['a::svaltype]) \<ztfun> (range \<vinj>-['b::svaltype])"
have
b2: "VAL_graph (\<olambda> x \<bullet> \<vproj>-['b] (f\<cdot>(\<vinj>-['a] x))) \<in> range VAL_graph-['a::svaltype, 'b::svaltype]"
by (rule rangeI)
have
b3: "VAL_graph (\<olambda> x \<bullet> \<vproj>-['b] (f\<cdot>(\<vinj>-['a] x))) \<in> (range \<vinj>-['a::svaltype]) \<ztfun> (range \<vinj>-['b::svaltype])"
by (rule VAL_graph_tfun)
have
b4: "f = VAL_graph (\<olambda> x \<bullet> \<vproj>-['b] (f\<cdot>(\<vinj>-['a] x)))"
apply (rule tfun_eqI [OF b1 b3])
apply (rule tfun_beta [OF b3, symmetric])
apply (auto simp add: VAL_graph_def vproj_inverse [OF tfun_range [OF b1]])
done
then show
"f \<in> range VAL_graph-['a::svaltype, 'b::svaltype]"
by (simp add: rangeI)
qed
lemma VAL_graph_inj:
"inj VAL_graph-['a::svaltype,'b::svaltype]"
proof (rule injI)
fix f g
assume c1: "VAL_graph-['a,'b] f = VAL_graph-['a,'b] g"
note c3 = VAL_graph_functional [of "f"]
show "f = g"
proof (rule ext)
fix x
have d1: "(\<vinj>-['a] x, \<vinj>-['b] (f x)) \<in> VAL_graph f"
by (auto simp add: VAL_graph_def)
have d2: "(\<vinj>-['a] x, \<vinj>-['b] (g x)) \<in> VAL_graph f"
apply (simp add: c1)
apply (auto simp add: c1 VAL_graph_def)
done
from c3 [THEN functionalD, OF d1 d2]
have "\<vinj>-['b] (f x) = \<vinj>-['b] (g x)"
by (this)
with vinj_inj [THEN injD]
show "f x = g x"
by (auto)
qed
qed
text {*
We directly prove that @{text "VAL_graph"} induces an appropriate embedding for function types.
*}
definition
graph_VAL :: "[CT, CT, (VAL \<leftrightarrow> VAL)] \<rightarrow> VAL"
where
"graph_VAL T T' \<defs> Abs_VAL \<circ> (graph_CU T T') \<circ> image (Rep_VAL \<par> Rep_VAL)"
lemma graph_VAL_vrank:
assumes
a1: "R \<in> \<chi> T \<zrel> \<chi> T'"
shows
"graph_VAL T T' R \<in> \<chi> (cset (cprod T T'))"
proof -
from a1 have
"image (Rep_VAL \<par> Rep_VAL) R \<in> carrier_set T \<zrel> carrier_set T'"
apply (auto simp add: vrank_def rel_def subset_def image_def)
apply (auto elim!: allE impE simp add: VAL.Abs_inverse)
done
then have
"((graph_CU T T') \<circ> image (Rep_VAL \<par> Rep_VAL)) R \<in> carrier_set (cset (cprod T T'))"
by (simp add: graph_CU_char)
then have
"(Abs_VAL \<circ> (graph_CU T T') \<circ> image (Rep_VAL \<par> Rep_VAL)) R \<in> \<chi> (cset (cprod T T'))"
by (simp add: vrank_def)
then show
"?thesis"
by (simp add: graph_VAL_def)
qed
lemma map_pair_inj:
assumes
a1: "inj f" and
a2: "inj g"
shows
"inj (f \<par> g)"
using a1 [THEN injD] a2 [THEN injD]
by (auto intro!: injI simp add: map_pair_def)
lemma image_inj:
assumes
a1: "inj f"
shows
"inj (image f)"
proof (rule injI)
fix
X Y
assume
b1: "f\<lparr>X\<rparr> = f\<lparr>Y\<rparr>"
show
"X = Y"
apply (simp add: set_eq_iff)
apply (rule allI)
proof -
fix
x
have
"x \<in> X
\<Leftrightarrow> f x \<in> f\<lparr>X\<rparr>"
using a1 [THEN injD]
by (auto simp add: image_conv)
also have "\<dots>
\<Leftrightarrow> f x \<in> f\<lparr>Y\<rparr>"
by (simp add: b1)
also have "\<dots>
\<Leftrightarrow> x \<in> Y"
using a1 [THEN injD]
by (auto)
finally show
"x \<in> X \<Leftrightarrow> x \<in> Y"
by (this)
qed
qed
lemma graph_VAL_inj:
"inj_on (graph_VAL T T') (\<chi> T \<zrel> \<chi> T')"
unfolding graph_VAL_def
apply (rule comp_inj_on [OF _ comp_inj_on])
proof -
show
"inj_on (image (Rep_VAL \<par> Rep_VAL)) (\<chi> T \<zrel> \<chi> T')"
apply (rule subset_inj_on)
apply (rule image_inj)
apply (rule map_pair_inj)
apply (intro VAL.Rep_inj)+
apply (auto)
done
have
b1 [rule_format]: "(\<forall> R | R \<in> \<chi> T \<zrel> \<chi> T' \<bullet> (image (Rep_VAL \<par> Rep_VAL)) R \<in> (carrier_set T) \<zrel> (carrier_set T'))"
apply (auto simp add: vrank_def rel_def image_def map_pair_def subset_def)
apply (auto elim!: allE impE simp add: VAL.Abs_inverse)
done
show
"inj_on (graph_CU T T') (image (Rep_VAL \<par> Rep_VAL))\<lparr>\<chi> T \<zrel> \<chi> T'\<rparr>"
apply (rule inj_onI)
apply (elim imageE)
apply (simp add: graph_CU_eq b1)
done
show
"inj_on Abs_VAL ((graph_CU T T')\<lparr>(image (Rep_VAL \<par> Rep_VAL))\<lparr>\<chi> T \<zrel> \<chi> T'\<rparr>\<rparr>)"
apply (rule subset_inj_on)
apply (rule VAL.Abs_inj)
apply (auto)
done
qed
lemma set_card:
fixes f::"'a \<rightarrow> VAL" and T::CT
assumes a1: "inj f" and a2: "range f \<subseteq> (\<chi> T::VAL set)"
shows "inj (\<olambda> X \<bullet> vset_of T (f\<lparr>X\<rparr>)) \<and> range (\<olambda> X \<bullet> vset_of T (f\<lparr>X\<rparr>)) \<subseteq> \<chi> (cset T)"
proof (msafe_no_assms(inference))
let ?set_of = "(vset_of T)::VAL set \<rightarrow> VAL"
let ?vinjimage = "\<olambda> X::('a set) \<bullet> f\<lparr>X\<rparr>"
let ?g = "\<olambda> X::('a set) \<bullet> ?set_of (?vinjimage X)"
have b1: "inj ?vinjimage"
proof (intro inj_onI)
fix X Y
assume c1: "f\<lparr>X\<rparr> = f\<lparr>Y\<rparr>"
then have "(inv f)\<lparr>f\<lparr>X\<rparr>\<rparr> = (inv f)\<lparr>f\<lparr>Y\<rparr>\<rparr>"
by (simp)
then have "((inv f) \<circ> f)\<lparr>X\<rparr> = ((inv f) \<circ> f)\<lparr>Y\<rparr>"
by (simp add: image_compose)
then show "X = Y"
by (simp add: inj_iff [THEN iffD1, OF a1])
qed
from a2 have b2: "range ?vinjimage \<subseteq> \<pset> (\<chi> T)"
by (auto)
have b3: "inj (?set_of \<circ> ?vinjimage)"
apply (intro comp_inj_on)
apply (rule b1)
apply (rule subset_inj_on)
apply (rule inj_on_vset_of_t)
apply (rule b2)
done
then show "inj ?g"
by (simp add: o_def)
have "range ?g = (vset_of T)\<lparr>(range ?vinjimage)\<rparr>"
by auto
then show "range ?g \<subseteq> \<chi> (cset T)"
apply (simp add: vrank_cset)
apply (rule image_mono)
apply (rule b2)
done
qed
instantiation (* type: set *)
"set" :: (svaltype) svaltype
begin
definition
set_vinj_def: "\<vinj>-['a set] \<defs> (\<olambda> X \<bullet> vset_of \<^CT>{:'a:} (\<vinj>-['a]\<lparr>X\<rparr>))"
instance
proof (intro_classes)
have
b1: "range \<vinj>-['a] \<subseteq> \<chi> \<^CT>{:'a:}"
by (rule CT_of_char)
from set_card [OF vinj_inj b1]
show "inj \<vinj>-['a set]"
by (auto simp add: set_vinj_def)
from set_card [OF vinj_inj b1]
show "\<exists> T \<bullet> range \<vinj>-['a set] \<subseteq> \<chi> T"
apply (msafe_no_assms(inference))
apply (witness "cset \<^CT>{:'a:}")
apply (simp add: set_vinj_def)
done
qed
end
instance
set :: (svcard) svcard
proof -
have b1: "inj (scinj::'a \<rightarrow> VAL)"
by (rule scinj_inj)
have b2: "\<exists> T \<bullet> range (scinj::'a \<rightarrow> VAL) \<subseteq> \<chi> T"
by (rule scinj_bound_inj)
from set_card [OF b1 b2 [THEN someI_ex]]
show "OFCLASS('a set, svcard_class)"
apply (intro svcardI')
apply (mauto(inference))
done
qed
instance
set :: (vtype) vtype
by (intro_classes)
lemma CT_set:
"\<^CT>{:('a::svaltype) set:} = cset \<^CT>{:'a:}"
proof -
have b1: "range \<vinj>-['a] \<subseteq> \<chi> \<^CT>{:'a:}"
by (rule CT)
show ?thesis
apply (rule CT_eq)
apply (simp add: set_vinj_def subset_def image_def vrank_cset)
apply (mauto(inference))
proof -
fix X::"'a set"
from b1 show
"\<exists> Y \<bullet>
(\<forall> y \<bullet> y \<in> Y \<Rightarrow> y \<in> \<chi> \<^CT>{:'a:}) \<and>
vset_of \<^CT>{:'a:} {y | (\<exists> x \<bullet> x \<in> X \<and> y = \<vinj> x)} = vset_of \<^CT>{:'a:} Y"
apply (witness "\<vinj>\<lparr>X\<rparr>")
apply (auto simp add: image_def subset_def)
done
qed
qed
instantiation (* type: fun *)
"fun" :: (svaltype, svaltype) svaltype
begin
definition
fun_vinj_def: "\<vinj> \<defs> (graph_VAL \<^CT>{:'a:} \<^CT>{:'b:}) \<circ> VAL_graph"
instance
proof (intro_classes)
have
b1: "inj_on (graph_VAL \<^CT>{:'a:} \<^CT>{:'b:}) (range VAL_graph-['a,'b])"
apply (rule subset_inj_on)
apply (rule graph_VAL_inj)
apply (auto simp add: VAL_graph_rel)
done
show
"inj \<vinj>-['a \<rightarrow> 'b]"
apply (simp add: fun_vinj_def)
apply (rule comp_inj_on [OF VAL_graph_inj b1])
done
next
from graph_VAL_vrank [of _ "\<^CT>{:'a:}" "\<^CT>{:'b:}", OF VAL_graph_rel] show
"(\<exists> T \<bullet> range \<vinj>-['a \<rightarrow> 'b] \<subseteq> \<chi> T)"
apply (witness "cset (cprod \<^CT>{:'a:} \<^CT>{:'b:})")
apply (auto simp add: fun_vinj_def)
done
qed
end
(*
definition
VAL_appl :: "[VAL, VAL] \<rightarrow> VAL" ("_\<vappl>_" [999,1000] 999)
where
"v \<vappl> u \<defs> Abs_VAL ((Rep_VAL v) \<cappl> (Rep_VAL u))"
*)
definition
VAL_appl :: "[VAL, VAL] \<rightarrow> VAL" ("_\<vappl>_" [999,1000] 999)
where
"v \<vappl> u \<defs>
\<if> (Rep_VAL u) \<in> \<zdom> (CU_graph (Rep_VAL v))
\<then> Abs_VAL ((Rep_VAL v) \<cappl> (Rep_VAL u))
\<else> (The (funK \<False>))
\<fi>"
notation (xsymbols output)
VAL_appl ("_ \<nu>\<cdot> _" [999,1000] 999)
(*
lemma graph_VAL_inv_raw:
assumes
a1: "f \<in> \<chi> CT1 \<zpfun> \<chi> CT2"
shows
"VAL_appl (graph_VAL CT1 CT2 f) = \<opof> f"
proof (rule ext)
fix
x :: "VAL"
from a1 have
b1: "{ a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) } \<in> carrier_set CT1 \<zpfun> carrier_set CT2"
apply (mauto(fspace))
apply (auto dest!: rel_memD [OF a1 [THEN pfun_rel]] simp add: vrank_def image_conv VAL.Abs_inverse)
apply (auto intro!: functionalI elim!: functionalE simp add: VAL.Rep_inject)
done
have
b2: "{ a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) }\<cdot>(Rep_VAL x) = Rep_VAL (f\<cdot>x)"
proof (cases "x \<in> \<zdom> f")
assume
c1: "x \<in> \<zdom> f"
show
"?thesis"
apply (rule pfun_beta [OF b1])
apply (simp add: VAL.Rep_inject)
apply (rule pfun_appl [OF a1 c1])
done
next
assume
c1: "x \<notin> \<zdom> f"
then have
c2: "(Rep_VAL x) \<notin> \<zdom> { a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) }"
by (auto simp add: VAL.Rep_inject)
from c1 c2 show
"?thesis"
apply (simp add: undef_beta)
by (simp add: undef_beta VAL_undef VAL.Abs_inverse)
qed
show
"(graph_VAL CT1 CT2 f)\<vappl>x = f\<cdot>x"
by (simp add: VAL_appl_def graph_VAL_def VAL.Abs_inverse map_pair_def image_conv CU_graph [OF b1 [THEN pfun_rel]] b2 VAL.Rep_inverse)
qed
*)
lemma graph_VAL_inv_raw:
assumes
a1: "f \<in> \<chi> CT1 \<zpfun> \<chi> CT2"
shows
"VAL_appl (graph_VAL CT1 CT2 f) = \<opof> f"
proof (rule ext)
fix
x :: "VAL"
from a1 have
b1: "{ a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) } \<in> carrier_set CT1 \<zpfun> carrier_set CT2"
apply (mauto(fspace))
apply (auto dest!: rel_memD [OF a1 [THEN pfun_rel]] simp add: vrank_def image_conv VAL.Abs_inverse)
apply (auto intro!: functionalI elim!: functionalE simp add: VAL.Rep_inject)
done
have
b2: "{ a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) }\<cdot>(Rep_VAL x) =
\<if> x \<in> \<zdom> f \<then> Rep_VAL (f\<cdot>x) \<else> The (funK \<False>) \<fi>"
proof (cases "x \<in> \<zdom> f")
assume
c1: "x \<in> \<zdom> f"
then show
"?thesis"
apply simp
apply (rule pfun_beta [OF b1])
apply (simp add: VAL.Rep_inject)
apply (rule pfun_appl [OF a1 c1])
done
next
assume
c1: "x \<notin> \<zdom> f"
then have
c2: "(Rep_VAL x) \<notin> \<zdom> { a b | (a, b) \<in> f \<bullet> (Rep_VAL a, Rep_VAL b) }"
by (auto simp add: VAL.Rep_inject)
from c1 c2 show
"?thesis"
by (simp add: undef_beta eind_def funK_def)
qed
show
"(graph_VAL CT1 CT2 f)\<vappl>x = f\<cdot>x"
apply (cases "x \<in> \<zdom> f")
apply (simp add:
VAL_appl_def graph_VAL_def VAL.Abs_inverse map_pair_def image_conv
CU_graph [OF b1 [THEN pfun_rel]] b2 VAL.Rep_inverse eind_split)
apply (simp add: Domain_iff VAL.Rep_inject)
apply (simp add: VAL_appl_def graph_VAL_def)
apply (simp add:
VAL_appl_def graph_VAL_def VAL.Abs_inverse map_pair_def
image_conv CU_graph [OF b1 [THEN pfun_rel]] b2 VAL.Rep_inverse eind_split funK_def)
apply (simp add: undef_beta)
apply (simp add: Domain_iff VAL.Rep_inject)
done
qed
lemma graph_VAL_inv:
assumes
a1: "f \<in> \<chi> CT1 \<zpfun> \<chi> CT2" and
a2: "x \<in> \<zdom> f"
shows
"(graph_VAL CT1 CT2 f)\<vappl>x = f\<cdot>x"
by (simp add: graph_VAL_inv_raw [OF a1])
lemma VAL_beta2:
"(\<vinj>-[('a::svaltype) \<rightarrow> ('b::svaltype)] f) \<vappl> (\<vinj>-['a::svaltype] x)
= \<vinj>-['b::svaltype] (f x)"
proof -
have
"(\<vinj> f) \<vappl> (\<vinj> x)
= Abs_VAL
(((CU_graph
\<circ> (graph_CU \<^CT>{:'a:} \<^CT>{:'b:})
\<circ> image (Rep_VAL \<par> Rep_VAL) \<circ> VAL_graph) f)
\<cdot>(Rep_VAL (\<vinj> x)))"
apply (simp add: fun_vinj_def graph_VAL_def VAL_appl_def VAL.Abs_inverse)
apply (subst CU_graph)
using VAL_graph_rel [of "f"]
apply (mauto(fspace))
apply (auto simp add: vrank_def VAL.Abs_inverse)
using VAL_graph_tfun [of "f"] CT_of_char' [of "x"]
apply (mauto(fspace))
apply (auto simp add: image_conv rel_def VAL.Abs_inverse VAL.Rep_inject CT_of_char' Domain_iff
eind_def)
done
also from VAL_graph_rel [of f] have
"(CU_graph \<circ> (graph_CU \<^CT>{:'a:} \<^CT>{:'b:}) \<circ> image (Rep_VAL \<par> Rep_VAL) \<circ> VAL_graph) f
= (image (Rep_VAL \<par> Rep_VAL) \<circ> VAL_graph) f"
apply (simp)
apply (rule CU_graph)
apply (auto simp add: vrank_def map_pair_def image_conv rel_def VAL.Abs_inverse)
done
also have
"((image (Rep_VAL \<par> Rep_VAL) \<circ> VAL_graph) f)\<cdot>(Rep_VAL (\<vinj> x))
= Rep_VAL ((VAL_graph f)\<cdot>(\<vinj> x))"
apply (rule functional_beta)
using VAL_graph_functional [of "f", THEN functionalD] VAL_graph_tfun [of f] CT_of_char' [of "x"]
apply (mauto(fspace))
apply (auto intro!: functionalI functional_appl [OF VAL_graph_functional] simp add: map_pair_def image_conv VAL.Rep_inject)
done
finally show
"?thesis"
by (simp add: VAL.Rep_inverse VAL_graph_beta)
qed
text {*
In order to demonstrate that the @{text fun} operator preserves
@{text svcard}, we use the fact that it is isomorphic to the total
graphs, a type readily embedded in a Cartesian universe rank.
To simplify this proof, and others to follow we introduce an intermediate
lemma that the existence of a total injective graph into a type of
class @{text svcard} is enough to establish a claim to be in @{text svcard}.
*}
lemma rep_vcardI:
"\<^sEP>{:\<univ>-['a]:}{:\<univ>-['b::vcard]:} \<turnstile> OFCLASS('a, vcard_class)"
proof (intro_classes, simp add: subequipotent_def)
assume a1: "\<exists> f \<bullet> f \<in> \<univ>-['a] \<zinj> \<univ>-['b]"
from vcard have a2: "\<exists> f \<bullet> f \<in> \<univ>-['b] \<zinj> \<univ>-[VAL]"
by (simp add: subequipotent_def)
from a1 a2 show "\<exists> f \<bullet> f \<in> \<univ>-['a] \<zinj> \<univ>-[VAL]"
proof (msafe_no_assms(inference))
fix inj_d_a inj_d_b
assume b1: "inj_d_a \<in> \<univ>-['a] \<zinj> \<univ>-['b]" and
b2: "inj_d_b \<in> \<univ>-['b] \<zinj> \<univ>-[VAL]"
let ?inj = "inj_d_a \<zfcomp> inj_d_b"
from b1 b2 have "?inj \<in> \<univ> \<zinj> \<univ>"
by (auto intro!: fcomp_in_tinjI simp add: tinj_tfun [THEN tfun_dom])
then show "\<exists> f \<bullet> f \<in> \<univ>-['a] \<zinj> \<univ>-[VAL]"
by (auto)
qed
qed
lemma rep_vcardIa:
"f \<in> \<univ>-['a] \<zinj> \<univ>-['b::vcard] \<turnstile> OFCLASS('a, vcard_class)"
by (rule rep_vcardI, auto simp add: subequipotent_def)
lemma rep_vcardIb:
"inj (f::('a \<rightarrow> 'b::vcard)) \<turnstile> OFCLASS('a, vcard_class)"
by (rule rep_vcardIa, rule graph_of_f_inj)
lemma rep_svcardI:
"\<^sEP>{:\<univ>-['a]:}{:\<univ>-['b::svcard]:} \<turnstile> OFCLASS('a, svcard_class)"
proof (intro_classes, simp add: subequipotent_def)
assume a1: "\<exists> f \<bullet> f \<in> \<univ>-['a] \<zinj> \<univ>-['b]"
from svcard have a2: "\<exists> T f \<bullet> f \<in> \<univ>-['b] \<zinj> (\<chi> T::VAL set)"
by (simp add: subequipotent_def)
from a1 a2 show "\<exists> T f \<bullet> f \<in> \<univ>-['a] \<zinj> ((\<chi> T)::VAL set)"
(is "\<exists> T f \<bullet> ?Q T f")
proof (msafe_no_assms(inference))
fix T f g
assume b1: "f \<in> \<univ>-['a] \<zinj> \<univ>-['b]" and
b2: "g \<in> \<univ>-['b] \<zinj> (\<chi> T::VAL set)"
let ?f = "f \<zfcomp> g"
from b2 have b3: "\<zran> ?f \<subseteq> \<chi> T"
by (mauto(fspace))
from b1 b2 have "?f \<in> \<univ> \<zinj> \<univ>"
apply (intro fcomp_in_tinjI)
apply (auto simp add: tinj_tfun [THEN tfun_dom])
apply (mauto(fspace))
done
with b3 have "?f \<in> \<univ> \<zinj> \<chi> T"
by (auto dest: dr_tinjD1 dr_tinjD2 intro!: dr_tinjI
simp add: tinj_tfun [THEN tfun_dom])
then have "(\<exists> f \<bullet> ?Q T f)"
by (auto)
then show "(\<exists> T f \<bullet> ?Q T f)"
by (auto)
qed
qed
lemma rep_svcardIa:
"f \<in> \<univ>-['a] \<zinj> \<univ>-['b::svcard] \<turnstile> OFCLASS('a, svcard_class)"
by (rule rep_svcardI, auto simp add: subequipotent_def)
lemma rep_svcardIb:
"inj (f::('a \<rightarrow> 'b::svcard)) \<turnstile> OFCLASS('a, svcard_class)"
by (rule rep_svcardIa, rule graph_of_f_inj)
text {*
Now it is straightforward to observe that @{text "\<graphof>"} is the
necessary injection in the case of a function space.
NB Can't use simple proof in absence of Set type.
*}
(*
instance
"fun" :: (svcard, svcard)svcard
apply (rule rep_svcardIb [of "\<graphof>"])
apply (rule graph_of_inj)
*)
lemma fun_card:
fixes
f::"'a \<rightarrow> VAL" and S::CT and
g::"'b \<rightarrow> VAL" and T::CT
assumes
a1: "inj f" and
a2: "range f \<subseteq> (\<chi> S::VAL set)" and
a3: "inj g" and
a4: "range g \<subseteq> (\<chi> T::VAL set)"
shows
"inj (\<olambda> F \<bullet> vset_of (cprod S T) ({ x \<bullet> vprod_of (f x, g (F x))})) \<and>
range (\<olambda> F \<bullet> vset_of (cprod S T) ({ x \<bullet> vprod_of (f x, g (F x))})) \<subseteq> \<chi> (cset (cprod S T))"
(is "inj ?CL_G \<and> range ?CL_G \<subseteq> \<chi> (cset (cprod S T))")
proof (msafe_no_assms(inference))
let ?set_of = "(\<olambda> X::VAL set \<bullet> vset_of (cprod S T) X)"
let ?prod_img = "(\<olambda> X::(VAL \<times> VAL) set \<bullet> vprod_of\<lparr>X\<rparr>)"
let ?mk_graph = "(\<olambda> F \<bullet> { x \<bullet> (f x, g (F x))})"
let ?CL_F = "?set_of \<circ> ?prod_img \<circ> ?mk_graph"
have
"?prod_img \<circ> ?mk_graph = (\<olambda> F \<bullet> { x \<bullet> vprod_of (f x, g (F x))})"
apply (rule ext)
apply (auto simp add: eind_def)
done
then have
"?CL_G
= ?set_of \<circ> (?prod_img \<circ> ?mk_graph)"
apply (simp)
apply (simp add: comp_def)
done
also have "\<dots>
= ?CL_F"
by (simp add: o_assoc)
finally have
b0: "?CL_G = ?CL_F"
by (simp)
have
b1: "inj ?mk_graph"
proof (rule injI)
fix F G
assume
c1: "{ x \<bullet> (f x, g (F x))} = { x \<bullet> (f x, g (G x))}"
from a1 [THEN injD] have
c3: "functional { x \<bullet> (f x, g (F x))}"
apply (intro functionalI)
apply (auto)
done
show
"F = G"
proof (rule ext)
fix x
have
d1: "(f x, g (F x)) \<in> { x \<bullet> (f x, g (F x))}"
by (auto)
have
d2: "(f x, g (G x)) \<in> { x \<bullet> (f x, g (F x))}"
by (auto simp add: c1)
from c3 [THEN functionalD, OF d1 d2] have
"g (F x) = g (G x)"
by (this)
with a3 [THEN injD]
show
"F x = G x"
by (auto)
qed
qed
from a2 a4 have
b1': "range ?mk_graph \<subseteq> (\<pset> ((\<chi> S) \<times> (\<chi> T)))"
by (auto)
have
"inj_on ?prod_img (\<pset> ((\<chi> S) \<times> (\<chi> T)))"
proof (rule inj_onI)
fix X Y
assume
d1: "X \<in> \<pset> ((\<chi> S) \<times> (\<chi> T))" and
d2: "Y \<in> \<pset> ((\<chi> S) \<times> (\<chi> T))" and
d3: "?prod_img X = ?prod_img Y"
show
"X = Y"
proof (auto)
fix x y
assume
e1: "(x, y) \<in> X"
with d3 [symmetric] have
e2: "vprod_of (x, y) \<in> ?prod_img Y"
by (auto)
then obtain x' y'
where
e3: "(x', y') \<in> Y" and
e4: "vprod_of (x, y) = vprod_of (x', y')"
by (auto)
from e4 have
"(x, y) = (x', y')"
by (rule inj_vprod_of [THEN injD])
with e3
show
"(x, y) \<in> Y"
by (simp)
next
fix x y
assume
e1: "(x, y) \<in> Y"
with d3 have
e2: "vprod_of (x, y) \<in> ?prod_img X"
by (auto)
then obtain x' y'
where
e3: "(x', y') \<in> X" and
e4: "vprod_of (x, y) = vprod_of (x', y')"
by (auto)
from e4 have
"(x, y) = (x', y')"
by (rule inj_vprod_of [THEN injD])
with e3
show
"(x, y) \<in> X"
by (simp)
qed
qed
with b1' have
b2: "inj_on ?prod_img (range ?mk_graph)"
by (auto intro: subset_inj_on)
from b1' have
b2': "?prod_img\<lparr>range ?mk_graph\<rparr> \<subseteq> \<pset> (\<chi> (cprod S T))"
by (auto simp add: vrank_cprod eind_def)
have
"inj_on ?set_of (\<pset> (\<chi> (cprod S T)))"
by (rule inj_on_vset_of_t)
with b2' have
b3: "inj_on ?set_of (?prod_img\<lparr>range ?mk_graph\<rparr>)"
by (auto intro: subset_inj_on)
have
"inj ?CL_F"
apply (rule comp_inj_on)
apply (rule b1)
apply (rule comp_inj_on)
apply (rule b2)
apply (rule b3)
done
then
show
"inj ?CL_G"
by (simp add: b0)
have
"range ?CL_F
= ?set_of\<lparr>?prod_img\<lparr>range ?mk_graph\<rparr>\<rparr>"
by (simp add: image_compose)
also have "\<dots>
\<subseteq> ?set_of\<lparr>\<pset> (\<chi> (cprod S T))\<rparr>"
apply (rule image_mono)
apply (rule b2')
done
also have "\<dots>
= \<chi> (cset (cprod S T))"
by (simp add: vrank_cset)
finally
show
"range ?CL_G \<subseteq> \<chi> (cset (cprod S T))"
by (simp add: b0)
qed
instance
"fun" :: (svcard, svcard) svcard
proof (intro svcardI')
have
b1: "inj (scinj::'a \<rightarrow> VAL)"
by (rule scinj_inj)
have
b1': "range (scinj::'a \<rightarrow> VAL) \<subseteq> \<chi> (\<^scCT>[:'a:])"
by (rule scinj_bound_scCT)
have
b2: "inj (scinj::'b \<rightarrow> VAL)"
by (rule scinj_inj)
have
b2': "range (scinj::'b \<rightarrow> VAL) \<subseteq> \<chi> (\<^scCT>[:'b:])"
by (rule scinj_bound_scCT)
let ?inj = "(\<olambda> F::('a \<rightarrow> 'b) \<bullet> vset_of (cprod \<^scCT>[:'a:] \<^scCT>[:'b:]) ({ x \<bullet> vprod_of (scinj x, scinj (F x))}))"
from fun_card [OF b1 b1' b2 b2']
show
"inj ?inj"
"range ?inj \<subseteq> \<chi> (cset (cprod \<^scCT>[:'a:] \<^scCT>[:'b:]))"
by (auto)
qed
text {*
The default approach to introducing new types in HOL is through the
definition of a representation set. Association between definitional
types and their representation set is indicated by the
@{text type_definition} predicate. One consequence of the
@{text type_definition} predicate is the existence of an injection
into the representation set, so if the representation set is from
an existing @{text svcard}, the representation axiom immediately
establishes the new type in the @{text svcard} class.
*}
lemmas type_def_vcardI = type_definition.Rep_inj [THEN rep_vcardIb]
lemmas type_def_svcardI = type_definition.Rep_inj [THEN rep_svcardIb]
text {*
Some important examples of definitional types are @{text unit},
disjoint sums, @{text "\<nat>"}, @{text "\<real>"}, and the ordinals.
*}
instance
"unit" :: svcard
by (rule type_def_svcardI, rule type_definition_unit)
instantiation (* type: Product_Type.unit *)
Product_Type.unit :: svaltype
begin
definition
unit_vinj_def: "\<vinj>-[unit] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: unit_vinj_def)
done
end
instance
sum :: (svcard, svcard)svcard
by (rule type_def_svcardI, rule type_definition_sum)
instantiation (* type: + *)
sum :: (svaltype, svaltype)svaltype
begin
definition
sum_vinj_def: "\<vinj>-[('a::svaltype) + ('b::svaltype)] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: sum_vinj_def)
done
end
instance
nat :: svcard
by (rule type_def_svcardI, rule type_definition_nat)
instantiation (* type: nat *)
nat :: svaltype
begin
definition
nat_vinj_def: "\<vinj>-[nat] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: nat_vinj_def)
done
end
instance
int :: svcard
apply (rule rep_svcardIb)
apply (rule type_definition_int [THEN type_definition.Rep_inj])
done
instantiation (* type: Int.int *)
Int.int :: svaltype
begin
definition
int_vinj_def: "\<vinj>-[int] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: int_vinj_def)
done
end
text {*
HOL datatypes are just a special class of definitional types,
but proving them instances of @{text svcard} is complicated by
the fact that they are represented in the @{text "Datatype_Universe.Node"}
type, which is hidden in the default HOL distribution. In order,
do instance proofs for datatypes, we prove that the embedding
injection can span an intermediate type.
*}
lemma datatype_span:
assumes
a1: "type_definition (Rep_d_1::'b \<rightarrow> 'c) Abs_d_1 A_d_1" and
a2: "type_definition (Rep_d_2::'a \<rightarrow> 'b set) Abs_d_2 A_d_2"
shows "\<^sEP>{:\<univ>-['a]:}{:\<univ>-['c set]:}"
proof -
from a1 have a3: "inj Rep_d_1" by (rule type_definition.Rep_inj)
from a2 have a4: "inj Rep_d_2" by (rule type_definition.Rep_inj)
let ?f = "\<olambda> a \<bullet> Rep_d_1\<lparr>Rep_d_2 a\<rparr>"
have "inj ?f"
proof (auto intro!: inj_onI)
fix x y
assume b1: "Rep_d_1\<lparr>Rep_d_2 x\<rparr> = Rep_d_1\<lparr>Rep_d_2 y\<rparr>"
with a3 have "Rep_d_2 x = Rep_d_2 y"
by (simp add: inj_image_eq_iff)
with a4 show "x = y" by (simp add: inj_eq)
qed
then have "\<graphof> ?f \<in> \<univ> \<zinj> \<univ>"
by (rule graph_of_f_inj)
then show ?thesis
by (auto simp add: subequipotent_def)
qed
lemmas data_svcardI =
type_definition_node [THEN datatype_span, THEN rep_svcardI]
text {*
Proving datatype instances of @{text vcard} is now trivial.
*}
instance
num :: svcard
by (rule data_svcardI, rule type_definition_num)
instantiation (* type: Num.num *)
Num.num :: svaltype
begin
definition
num_vinj_def: "\<vinj>-[num] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: num_vinj_def)
done
end
instance
option :: (svcard)svcard
by (rule data_svcardI, rule type_definition_option)
instantiation (* type: Option.option *)
Option.option :: (svaltype)svaltype
begin
definition
option_vinj_def: "\<vinj>-[('a::svaltype)option] \<defs> scinj"
instance
apply (intro_classes)
apply (auto intro!: scinj_inj scinj_bound_inj simp add: option_vinj_def)
done
end
text {*
The @{text list} datatype is such a common and useful type constructor
that we find it useful to ensure that it preserves @{text valtype} as well as
@{text svaltype}.
*}
fun
linj :: "['a \<rightarrow> VAL, VAL, 'a list] \<rightarrow> VAL"
where
"linj f a [] = vprod_of (\<vinj>-[\<nat>] 0, a)"
| "linj f a (x#y) = vprod_of (\<vinj>-[\<nat>] 1, vprod_of (f x, linj f a y))"
lemma linj_inj:
assumes a1: "inj f"
shows "inj (linj f a)"
proof (rule inj_onI)
fix x::"'a list" and y::"'a list"
assume c1: "linj f a x = linj f a y"
have c2: "inj (vinj::\<nat> \<rightarrow> VAL)" by (rule vinj_inj)
have "\<forall> y | linj f a x = linj f a y \<bullet> x = y"
proof (induct x)
show "\<forall> y | linj f a [] = linj f a y \<bullet> [] = y"
proof (msafe_no_assms(inference))
fix y assume "linj f a [] = linj f a y"
with c2 show "[] = y"
by (cases y, auto simp add: inj_on_iff vprod_of_eq)
qed
next
fix x::"'a" and l::"'a list"
assume d1: "\<forall> l' | linj f a l = linj f a l' \<bullet> l = l'"
show "\<forall> l' | linj f a (x#l) = linj f a l' \<bullet> (x#l) = l'"
proof (msafe_no_assms(inference))
fix l'::"'a list" assume e1: "linj f a (x#l) = linj f a l'"
with c2 a1 d1 show "(x#l) = l'"
by (cases l', simp_all add: inj_on_iff vprod_of_eq)
qed
qed
with c1 show "x = y"
by (auto)
qed
instance
list :: (vcard)vcard
proof (intro_classes, simp add: subequipotent_def)
let ?linj = "linj (cinj::'a \<rightarrow> VAL) arbitrary"
from cinj_inj have "inj ?linj"
by (rule linj_inj)
then have "\<graphof> ?linj \<in> \<univ> \<zinj> \<univ>"
by (rule graph_of_f_inj)
then show "\<exists> f \<bullet> f \<in> \<univ>-['a list] \<zinj> \<univ>-[VAL]"
by (auto)
qed
instance
list :: (svcard)svcard
by (rule data_svcardI, rule type_definition_list)
instantiation (* type: List.list *)
List.list :: (valtype)valtype
begin
definition
list_vinj_def: "\<vinj>-['a list] \<defs>
(\<olambda> l \<bullet>
\<if> \<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T
\<then>
(\<olambda> f \<bullet> vset_of (cprod \<^CT>{:\<nat>:} (CT_of_val \<arb>-['a]))
{(n::\<nat>) (x::'a) | (n \<mapsto> x) \<in> f \<bullet> vprod_of (\<vinj> n, \<vinj>x)})
(\<glambda> n | n \<in> {0..<(length l)} \<bullet> nth l n)
\<else> linj \<vinj>-['a] \<arb> l
\<fi>)"
instance
apply (intro_classes)
apply (cases "\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T")
proof -
fix T
assume
b1: "\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T"
let
?J = "(\<olambda> f \<bullet> vset_of (cprod \<^CT>{:\<nat>:} (CT_of_val \<arb>-['a]))
{(n::\<nat>) (x::'a) | (n \<mapsto> x) \<in> f \<bullet> vprod_of (\<vinj> n, \<vinj>x)})"
have
b2: "inj ?J"
proof (rule inj_onI)
fix
f::"\<nat> \<leftrightarrow> 'a" and
g::"\<nat> \<leftrightarrow> 'a"
assume
c1: "?J f = ?J g"
from b1 have
c2: "range \<vinj>-['a] \<subseteq> \<chi> (CT_of_val \<arb>-['a])"
by (auto intro!: CT')
have c3: "range \<vinj>-[\<nat>] \<subseteq> \<chi> \<^CT>{:\<nat>:}"
by (rule CT)
have
c4: "{(n::\<nat>) (x::'a) | (n \<mapsto> x) \<in> f \<bullet> vprod_of (\<vinj> n, \<vinj>x)}
= {(n::\<nat>) (x::'a) | (n \<mapsto> x) \<in> g \<bullet> vprod_of (\<vinj> n, \<vinj>x)}"
(is "?X f = ?X g")
apply (rule inj_onD)
apply (rule inj_on_vset_of_t)
apply (rule c1)
apply (simp_all only: Pow_iff subset_def)
apply (insert c2 c3)
apply (auto simp add: image_def vrank_cprod)
done
show "f = g"
apply (simp add: set_eq_def)
apply (intro allI)
proof -
fix n::"\<nat>" and x::"'a"
have "(n \<mapsto> x) \<in> f
\<Leftrightarrow> vprod_of (\<vinj> n, \<vinj> x) \<in> ?X f"
proof (auto simp add: vprod_of_eq)
fix n'::"\<nat>" and x'::"'a"
assume e1: "\<vinj> n = \<vinj> n'" and e2: "\<vinj> x = \<vinj> x'" and
e3: "(n' \<mapsto> x') \<in> f"
have e4: "n = n'"
apply (rule inj_onD)
apply (rule vinj_inj)
apply (rule e1)
apply (auto)
done
have e5: "x = x'"
apply (rule inj_onD)
apply (rule vinj_inj)
apply (rule e2)
apply (auto)
done
from e3 e4 e5 show "(n \<mapsto> x) \<in> f"
by (simp)
qed
also from c4 have "\<dots>
\<Leftrightarrow> vprod_of (\<vinj> n, \<vinj> x) \<in> ?X g"
by (simp add: eind_def)
also have "\<dots>
\<Leftrightarrow> (n \<mapsto> x) \<in> g"
proof (auto simp add: vprod_of_eq)
fix n'::"\<nat>" and x'::"'a"
assume e1: "\<vinj> n = \<vinj> n'" and e2: "\<vinj> x = \<vinj> x'" and
e3: "(n' \<mapsto> x') \<in> g"
have e4: "n = n'"
apply (rule inj_onD)
apply (rule vinj_inj)
apply (rule e1)
apply (auto)
done
have e5: "x = x'"
apply (rule inj_onD)
apply (rule vinj_inj)
apply (rule e2)
apply (auto)
done
from e3 e4 e5 show "(n \<mapsto> x) \<in> g"
by (simp)
qed
finally show "(n \<mapsto> x) \<in> f \<Leftrightarrow> (n \<mapsto> x) \<in> g"
by (this)
qed
qed
have b3: "inj (\<olambda> l::'a list \<bullet> (\<glambda> n | n \<in> {0..<(length l)} \<bullet> nth l n))" (is "inj ?I")
proof (rule inj_onI)
fix k l
assume c1: "?I k = ?I l"
have c2: "\<forall> k l \<bullet> ?I k = ?I l \<Leftrightarrow> (\<forall> m x \<bullet> m < length k \<and> nth k m = x \<Leftrightarrow> m < length l \<and> nth l m = x)"
by (auto simp add: glambda_def set_eq_def)
have c3: "\<forall> k l \<bullet> ?I k = ?I l \<Rightarrow> length k = length l"
proof (msafe_no_assms(inference))
fix k l assume d1: "?I k = ?I l"
with c2 have d2: "(\<forall> m \<bullet> m < length k \<Leftrightarrow> m < length l)"
by (auto)
then show "length k = length l"
apply (rule contrapos_pp)
apply (simp add: nat_neq_iff)
apply (msafe_no_assms(inference))
apply (witness "length k")
apply (auto)
done
qed
with c2 have c4: "\<forall> k l \<bullet> ?I k = ?I l \<Rightarrow> (length k = length l) \<and> (\<forall> m x \<bullet> m < length k \<and> nth k m = x \<Leftrightarrow> m < length k \<and> nth l m = x)"
by (auto)
have c5: "\<forall> l \<bullet> (length k = length l) \<and> (\<forall> m x \<bullet> m < length k \<and> nth k m = x \<Leftrightarrow> m < length k \<and> nth l m = x) \<Rightarrow> k = l" (is "\<forall> l \<bullet> ?P k l")
proof (induct "k")
show "\<forall> l \<bullet> ?P [] l"
by (auto simp add: glambda_def)
next
fix x k
assume d1: "\<forall> l \<bullet> ?P k l"
show "\<forall> l \<bullet> ?P (x#k) l"
proof (rule allI)
fix l show "?P (x#k) l"
proof (induct l)
show "?P (x#k) []"
proof (msafe_no_assms(inference))
assume e1: "length (x#k) = length ([]::'a list)"
then show "(x#k) = []"
by (auto)
qed
next
fix y l
show "?P (x#k) (y#l)"
proof (auto)
assume e1: "length k = length l" and
e2: "\<forall> m z \<bullet> m < Suc (length l) \<and> nth (x#k) m = z \<Leftrightarrow> m < Suc (length l) \<and> nth (y#l) m = z"
from e2 [rule_format, of "0" "x"]
show "x = y"
by (simp)
from e2
have e3: "\<forall> m z \<bullet> 1 \<le> m \<and> m < Suc (length l) \<and> nth (x#k) m = z \<Leftrightarrow> 1 \<le> m \<and> m < Suc (length l) \<and> nth (y#l) m = z"
by (auto)
have "\<forall> m z \<bullet> 1 \<le> (Suc m) \<and> Suc m < Suc (length l) \<and> nth (x#k) (Suc m) = z \<Leftrightarrow> 1 \<le> (Suc m) \<and> Suc m < Suc (length l) \<and> nth (y#l) (Suc m) = z"
apply (rule allI)
apply (simp only: e3)
apply (auto)
done
then have "\<forall> m z \<bullet> m < (length l) \<and> nth k m = z \<Leftrightarrow> m < (length l) \<and> nth l m = z"
by (simp)
with e1 d1
show "k = l"
by (auto)
qed
qed
qed
qed
from c5 [rule_format] c4 [rule_format, OF c1]
show "k = l"
by (auto)
qed
have b4: "inj (?J \<circ> ?I)"
apply (rule comp_inj_on)
apply (rule b3)
apply (rule subset_inj_on [OF b2])
apply (auto)
done
with b1 show "inj \<vinj>-['a list]"
by (simp add: list_vinj_def comp_def)
next
assume
b1: "\<not>(\<exists> T \<bullet> range \<vinj>-['a] \<subseteq> \<chi> T)"
have
"inj (linj \<vinj>-['a] \<arb>)"
apply (rule linj_inj)
apply (rule vinj_inj)
done
with b1 show
"inj \<vinj>-['a list]"
by (simp add: list_vinj_def comp_def)
qed
end
instance
list :: (svaltype)svaltype
proof (intro_classes)
have b1: "range \<vinj>-['a] \<subseteq> \<chi> \<^CT>{:'a:}"
by (rule CT)
have b2: "range \<vinj>-[\<nat>] \<subseteq> \<chi> \<^CT>{:\<nat>:}"
by (rule CT)
{
fix l::"'a list"
from b1 b2 have "\<vinj>-['a list] l \<in> \<chi> (cset (cprod \<^CT>{:\<nat>:} \<^CT>{:'a:}))"
apply (auto simp add: list_vinj_def vrank_cset)
apply (simp add: image_conv subset_def CT_of_val_eq)
apply (witness "{n x | (n, x) \<in> (\<glambda> n | n < length l \<bullet> l ! n) \<bullet> vprod_of (vinj n, vinj x)}")
apply (auto simp add: vrank_cprod)
done
}
then have
"range \<vinj>-['a list] \<subseteq> \<chi> (cset (cprod \<^CT>{:\<nat>:} \<^CT>{:'a:}))"
by (auto)
then show
"\<exists> T \<bullet> range \<vinj>-['a list] \<subseteq> \<chi> T"
apply (witness "cset (cprod \<^CT>{:\<nat>:} \<^CT>{:'a:})")
apply (assumption)
done
qed
text {*
So when a new type is added by definition or as a datatype,
it is a simple matter of using the appropriate proof outline to
make the new type usable in system specifications. This process can easily
be automated by the HiVe tool.
*}
end
|
State Before: ctx : Context
m₁ m₂ : Mon
⊢ denote ctx (m₁ ++ m₂) = denote ctx m₁ * denote ctx m₂ State After: no goals Tactic: match m₁ with
| [] => simp! [Nat.one_mul]
| v :: m₁ => simp! [append_denote ctx m₁ m₂, Nat.mul_assoc] State Before: ctx : Context
m₁ m₂ : Mon
⊢ denote ctx ([] ++ m₂) = denote ctx [] * denote ctx m₂ State After: no goals Tactic: simp! [Nat.one_mul] State Before: ctx : Context
m₁✝ m₂ : Mon
v : Var
m₁ : List Var
⊢ denote ctx (v :: m₁ ++ m₂) = denote ctx (v :: m₁) * denote ctx m₂ State After: no goals Tactic: simp! [append_denote ctx m₁ m₂, Nat.mul_assoc] |
module moduleExample_2_mod
implicit none
!
! Procedure Interfaces
!
interface print_matrix
module procedure print_matrix_integer
module procedure print_matrix_real
end interface print_matrix
!
! Here are subroutines and functions for my program.
!
CONTAINS
!
subroutine print_matrix_integer(matrix,header)
!
! This subroutine prints a square integer matrix whose dimension is less than 6.
!
implicit none
integer,dimension(:,:),intent(in)::matrix
character(len=*),intent(in),optional::header
integer::i
!
! Print the matrix.
!
1000 Format(I10,4x,I10,4x,I10,4x,I10,4x,I10,4x,I10)
2000 Format(1x,A)
if(PRESENT(header)) write(*,2000) TRIM(header)
do i = 1,Size(matrix,1)
write(*,1000) matrix(i,:)
endDo
!
return
end subroutine print_matrix_integer
subroutine print_matrix_real(matrix,header)
!
! This subroutine prints a square real matrix whose dimension is less than 6.
!
implicit none
real,dimension(:,:),intent(in)::matrix
character(len=*),intent(in),optional::header
integer::i
!
! Print the matrix.
!
1000 Format(f10.5,4x,f10.5,4x,f10.5,4x,f10.5,4x,f10.5,4x,f10.5)
2000 Format(1x,A)
if(PRESENT(header)) write(*,2000) TRIM(header)
do i = 1,Size(matrix,1)
write(*,1000) matrix(i,:)
endDo
!
return
end subroutine print_matrix_real
!
end module moduleExample_2_mod
program moduleExample_2
!
! This is an example program demonstrating some uses of modules.
!
USE moduleExample_2_mod
implicit none
integer,dimension(5,5)::matrixI,matrixJ,matrixK
real,dimension(5,5)::matrixA,matrixB,matrixC
!
! Fill real matrixA and matrixB with random numbers.
!
call random_number(matrixA)
call random_number(matrixB)
write(*,*)' Matrix A:'
write(*,*) matrixA
write(*,*)' Here is Matrix A:'
call print_matrix(matrixA)
write(*,*)' Here is Matrix B:'
call print_matrix(matrixB)
!
! Fill integer matrixI and matrixJ with random numbers.
!
call random_number(matrixC)
matrixI = matrixC*100
write(*,*)' Matrix I:'
write(*,*) matrixI
write(*,*)' Here is matrixI:'
call print_matrix(matrixI)
!
! Form matrixC = sqrt(matrixA)
!
matrixC = SQRT(matrixA)
write(*,*)' Here is matrixC:'
call print_matrix(header='Here is matrixC in the print routine...',matrix=matrixC)
!
end program moduleExample_2
|
[STATEMENT]
lemma of_bl_0 [simp]: "of_bl (replicate n False) = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. of_bl (replicate n False) = 0
[PROOF STEP]
by transfer (simp add: bl_to_bin_rep_False) |
A little teaze from our friends at the Rip Curl Stew. The contest will be held this June 11th & 12th in Tofino, BC.
Kudo for the trailer! Look good boys! |
(* This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.
\:w
Some proofs were added by Yutaka Nagashima.*)
theory TIP_propositional_Sound
imports "../../Test_Base"
begin
datatype ('a, 'b) pair = pair2 "'a" "'b"
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Form = x "Form" "Form" | Not "Form" | Var "int"
fun z :: "'a list => 'a list => 'a list" where
"z (nil2) y2 = y2"
| "z (cons2 z2 xs) y2 = cons2 z2 (z xs y2)"
fun y :: "int => ((int, bool) pair) list => bool list" where
"y x2 (nil2) = nil2"
| "y x2 (cons2 (pair2 y22 True) x22) = cons2 (x2 = y22) (y x2 x22)"
| "y x2 (cons2 (pair2 y22 False) x22) = y x2 x22"
fun or2 :: "bool list => bool" where
"or2 (nil2) = False"
| "or2 (cons2 y2 xs) = (y2 | (or2 xs))"
fun models7 :: "int => ((int, bool) pair) list =>
((int, bool) pair) list" where
"models7 x2 (nil2) = nil2"
| "models7 x2 (cons2 z2 xs) =
(if (x2 ~= (case z2 of pair2 x22 y22 => x22)) then
cons2 z2 (models7 x2 xs)
else
models7 x2 xs)"
fun models6 :: "int => ((int, bool) pair) list => bool list" where
"models6 x2 (nil2) = nil2"
| "models6 x2 (cons2 (pair2 y22 True) x22) = models6 x2 x22"
| "models6 x2 (cons2 (pair2 y22 False) x22) =
cons2 (x2 = y22) (models6 x2 x22)"
fun models5 :: "int => ((int, bool) pair) list =>
((int, bool) pair) list" where
"models5 x2 (nil2) = nil2"
| "models5 x2 (cons2 z2 xs) =
(if (x2 ~= (case z2 of pair2 x22 y22 => x22)) then
cons2 z2 (models5 x2 xs)
else
models5 x2 xs)"
fun models4 :: "int => ((int, bool) pair) list => bool list" where
"models4 x2 (nil2) = nil2"
| "models4 x2 (cons2 (pair2 y22 True) x22) =
cons2 (x2 = y22) (models4 x2 x22)"
| "models4 x2 (cons2 (pair2 y22 False) x22) = models4 x2 x22"
function models :: "(((int, bool) pair) list) list => Form =>
(((int, bool) pair) list) list => (((int, bool) pair) list) list"
and
models2 :: "Form => (((int, bool) pair) list) list =>
(((int, bool) pair) list) list"
and
models3 :: "Form => ((int, bool) pair) list =>
(((int, bool) pair) list) list" where
"models x2 q (nil2) = models2 q x2"
| "models x2 q (cons2 z2 x22) = cons2 z2 (models x2 q x22)"
| "models2 q (nil2) = nil2"
| "models2 q (cons2 y2 z2) = models z2 q (models3 q y2)"
| "models3 (x p q) y2 = models2 q (models3 p y2)"
| "models3 (Not (x r q2)) y2 =
z (models3 (Not r) y2) (models3 (x r (Not q2)) y2)"
| "models3 (Not (Not p2)) y2 = models3 p2 y2"
| "models3 (Not (Var x22)) y2 =
(if (~ (or2 (models4 x22 y2))) then
cons2 (cons2 (pair2 x22 False) (models5 x22 y2)) (nil2)
else
nil2)"
| "models3 (Var x3) y2 =
(if (~ (or2 (models6 x3 y2))) then
cons2 (cons2 (pair2 x3 True) (models7 x3 y2)) (nil2)
else
nil2)"
by pat_completeness auto
fun t2 :: "((int, bool) pair) list => Form => bool" where
"t2 x2 (x p q) = ((t2 x2 p) & (t2 x2 q))"
| "t2 x2 (Not r) = (~ (t2 x2 r))"
| "t2 x2 (Var z2) = or2 (y z2 x2)"
fun formula :: "Form => (((int, bool) pair) list) list =>
bool" where
"formula p (nil2) = True"
| "formula p (cons2 y2 xs) = ((t2 y2 p) & (formula p xs))"
theorem property0 :
"formula p (models3 p (nil2))"
oops
end
|
> module Double.Predicates
> import Data.So
> %default total
> %access public export
> %auto_implicits on
* EQ
> |||
> data EQ : Double -> Double -> Type where
> MkEQ : {x : Double} -> {y : Double} -> So (x == y) -> EQ x y
* LT
> |||
> data LT : Double -> Double -> Type where
> MkLT : {x : Double} -> {y : Double} -> So (x < y) -> LT x y
* LTE
> |||
> data LTE : Double -> Double -> Type where
> MkLTE : {x : Double} -> {y : Double} -> So (x <= y) -> LTE x y
* Non-negative, positive
> -- |||
> -- data NonNegative : Double -> Type where
> -- MkNonNegative : {x : Double} -> So (0.0 <= x) -> NonNegative x
> -- |||
> -- data Positive : Double -> Type where
> -- MkPositive : {x : Double} -> So (0.0 < x) -> Positive x
> |||
> NonNegative : (x : Double) -> Type
> NonNegative x = 0.0 `LTE` x
> |||
> Positive : (x : Double) -> Type
> Positive x = 0.0 `LT` x
|
classdef PTKCoronalAnalysis < PTKPlugin
% PTKCoronalAnalysis. Plugin for performing analysis of density using bins
% along the anterior-posterior axis
%
% This is a plugin for the Pulmonary Toolkit. Plugins can be run using
% the gui, or through the interfaces provided by the Pulmonary Toolkit.
% See PTKPlugin.m for more information on how to run plugins.
%
% Plugins should not be run directly from your code.
%
% PTKAxialAnalysis divides the cranial-caudal axis into bins and
% performs analysis of the tissue density, air/tissue fraction and
% emphysema percentaein each bin.
%
%
% Licence
% -------
% Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
% Author: Tom Doel, 2013. www.tomdoel.com
% Distributed under the GNU GPL v3 licence. Please see website for details.
%
properties
ButtonText = 'Coronal<br>analysis'
ToolTip = 'Performs density analysis in bins along the anterior-posterior axis'
Category = 'Analysis'
Context = PTKContextSet.Any
AllowResultsToBeCached = true
AlwaysRunPlugin = false
PluginType = 'DoNothing'
HidePluginInDisplay = true
FlattenPreviewImage = false
PTKVersion = '2'
ButtonWidth = 6
ButtonHeight = 1
GeneratePreview = false
end
methods (Static)
function results = RunPlugin(dataset, context, reporting)
% Get the density image
roi = dataset.GetResult('PTKLungROI', PTKContext.LungROI);
if ~roi.IsCT
reporting.ShowMessage('PTKCoronalAnalysis:NotCTImage', 'Cannot perform density analysis as this is not a CT image');
return;
end
% Get a mask for the current region to analyse
context_mask = dataset.GetTemplateMask(context);
% Create a region mask excluding the airways
context_no_airways = dataset.GetResult('PTKGetMaskForContextExcludingAirways', context);
% Divide the lung into bins along the cranial-caudal axis
bins = dataset.GetResult('PTKDivideLungsIntoCoronalBins', PTKContext.Lungs);
results = PTKMultipleRegionAnalysis(bins, roi, context_mask, context_no_airways, 'Coronal distance from lung edge (mm)', reporting);
end
end
end |
#!/usr/bin/env python
""" NB: This has been modified from it's original to
work with just the two sessions of data provided. However,
if all data is available one need only change the
"sess_indx" dict to include all sessions.
=================================================
Classification Accuracy as a Substantive
Quantity of Interest: Measuring Polarization
in Westminster Systems
Andrew Peterson & Arthur Spirling 2017
=================================================
Generate term-document matrices
for UK Parliamentary speeches,
augmented with topic-indicators
Inputs:
(1) csv data (from xml2csv.py script)
(2) session_index.pkl (from xml2csv.py script)
Outputs:
(1) vocab_min200.pkl
(2) sparse scipy matrices and session_topics.pkl.
"""
# Authors:
# Andrew Peterson, NYU <andrew.peterson at unige dot ch>
# Arthur Spirling, NYU
# License: BSD 3 clause
# run with:
# python gen_mats.py
import os
import cPickle as pickle
import sys
import logging
import pandas as pd
import numpy as np
import re
import string
from glob import glob
import itertools
import os.path
import time
import scipy
from scipy.io import mmwrite
from scipy.sparse import csr_matrix
from sklearn import preprocessing
from sklearn.preprocessing import maxabs_scale
from sklearn.feature_extraction.text import CountVectorizer
from utils import has_regex, prep_year_data, augment_with_topics
#----------------------------------------------------------
# Identify vocab & save
#----------------------------------------------------------
def gen_fixed_vocab(data_in, mat_dir, sess_indx):
print("generating vocab...")
dfall = pd.DataFrame()
for indx, yrmth in sess_indx.items()[:79]:
print(yrmth)
df = prep_year_data(data_in, yrmth, minlen=40)
dfall = pd.concat([dfall, df])
#logging.info(dfall.info())
vectorizer = CountVectorizer(decode_error='ignore', min_df =200)
text = dfall.text
dfall = []
X = vectorizer.fit_transform(text)
wordlist = vectorizer.get_feature_names()
wordlist2 = [x for x in wordlist if not has_regex(r'[0-9]', x) ]
pickle.dump(wordlist2, open(mat_dir + "vocab_min200.pkl", "wb"))
logging.info("Length vocab: %d" % len(wordlist))
logging.info(str(len(text)))
worddict = vectorizer.vocabulary_
pickle.dump(worddict, open(mat_dir + "vocab_min200_freqdict.pkl", "wb" ) )
wd = pd.DataFrame(data=zip(worddict.keys(), worddict.values()), columns=['word','count'])
wd.to_csv(mat_dir + "vocab_min200_freqDF.csv", index=False, encoding='utf-8')
#--------------------------------------------------
# generate the matrices
#--------------------------------------------------
def gen_mats(data_in, mat_dir, sess_indx, normalize):
print("generating matrices...")
sess_topics = {}
vocab = pickle.load(open(mat_dir + "vocab_min200.pkl", 'rb'))
vectorizer = CountVectorizer(decode_error='ignore', vocabulary=vocab)
errors = []
for indx, yrmth in sess_indx.items()[:79]:
logging.info("Starting session: %s " % yrmth)
#df = pd.DataFrame()
try:
logging.info("loading data...")
df = prep_year_data(data_in, yrmth, minlen=40)
logging.info(str(len(df)))
except:
logging.error("failed getting year-month %s" % yrmth)
errors.append(yrmth)
df.reset_index(inplace=True)
y = df.y_binary
if (np.mean(y)==0 or np.mean(y)==1 or len(df)==0):
logging.warning("no variation in year: ", yrmth)
errors.append(yrmth)
continue
logging.info("vectorizing text...")
X = vectorizer.fit_transform(df.text)
logging.info("vocab shape: %s" % str(X.shape))
#if aug_w_topics:
X, topics = augment_with_topics(X, df)
sess_topics[indx] = topics
logging.info("writing data...")
if normalize:
X = maxabs_scale(X) # not sparse: X = preprocessing.scale(X)
logging.info("w/ topics: %s" % str(X.shape))
mmwrite(mat_dir + 'topic_aug_mat_normalized_j5_' + str(indx) + '.mtx' , X)
logging.info("saved augmented,normalized matrix")
logging.info("normalized X.")
else:
logging.info("w/ topics: %s" % str(X.shape))
mmwrite(mat_dir + 'topic_aug_mat_' + str(indx) + '.mtx' , X)
logging.info("saved augmented matrix")
logging.info("Done generating matrices.")
logging.error("errors: %d" % len(errors))
pickle.dump(sess_topics, open(mat_dir + "session_topics.pkl", "wb" ) )
#--------------------------------------------------
#--------------------------------------------------
def main():
curr_dir = os.getcwd()
curr_dir = re.sub('/UK_data', '', curr_dir)
logging.basicConfig(filename= curr_dir + '/log_files/gen_mats.log',level=logging.INFO,format='%(asctime)s %(lineno)s: %(message)s')
logging.info('Start.')
normalize = 1 # sys.argv[1]
data_in = curr_dir + "/data/" #sys.argv[2]
mat_dir = curr_dir + "/" #sys.argv[3]
#sess_indx_file = sys.argv[4] # load sess_indx_file for full data.
#sess_indx = pickle.load(open(sess_indx_file, 'rb'))
sess_indx = {9: '1944-11', 74: '2008-12'}
gen_fixed_vocab(data_in, mat_dir, sess_indx)
gen_mats(data_in, mat_dir, sess_indx, normalize)
if __name__ == "__main__":
main()
|
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include "ccl.h"
#include "ccl_params.h"
//
// Macros for replacing relative paths
#define EXPAND_STR(s) STRING(s)
#define STRING(s) #s
const ccl_configuration default_config = {ccl_boltzmann_class, ccl_halofit, ccl_nobaryons, ccl_tinker10, ccl_duffy2008, ccl_emu_strict};
const ccl_gsl_params default_gsl_params = {GSL_EPSREL, // EPSREL
GSL_N_ITERATION, // N_ITERATION
GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_GAUSS_KRONROD_POINTS
GSL_EPSREL, // INTEGRATION_EPSREL
GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS
GSL_EPSREL, // INTEGRATION_LIMBER_EPSREL
GSL_EPSREL_DIST, // INTEGRATION_DISTANCE_EPSREL
GSL_EPSREL_DNDZ, // INTEGRATION_DNDZ_EPSREL
GSL_EPSREL_SIGMAR, // INTEGRATION_SIGMAR_EPSREL
GSL_EPSREL_NU, // INTEGRATION_NU_EPSREL
GSL_EPSABS_NU, // INTEGRATION_NU_EPSABS
GSL_EPSREL, // ROOT_EPSREL
GSL_N_ITERATION, // ROOT_N_ITERATION
GSL_EPSREL_GROWTH // ODE_GROWTH_EPSREL
};
/* ------- ROUTINE: ccl_cosmology_read_config ------
INPUTS: none, but will look for ini file in include/ dir
TASK: fill out global variables of splines with user defined input.
The variables are defined in ccl_params.h.
The following are the relevant global variables:
*/
ccl_spline_params * ccl_splines=NULL; // Global variable
ccl_gsl_params * ccl_gsl=NULL; // Global variable
void ccl_cosmology_read_config(void)
{
int CONFIG_LINE_BUFFER_SIZE=100;
int MAX_CONFIG_VAR_LEN=100;
FILE *fconfig;
char buf[CONFIG_LINE_BUFFER_SIZE];
char var_name[MAX_CONFIG_VAR_LEN];
char* rtn;
double var_dbl;
// Get parameter .ini filename from environment variable or default location
const char* param_file;
const char* param_file_env = getenv("CCL_PARAM_FILE");
if (param_file_env != NULL) {
param_file = param_file_env;
}
else {
// Use default ini file
param_file = EXPAND_STR(__CCL_DATA_DIR__) "/ccl_params.ini";
}
if ((fconfig=fopen(param_file, "r")) == NULL) {
ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, "ccl_core.c: Failed to open config file: %s", param_file);
return;
}
if(ccl_splines == NULL) {
ccl_splines = malloc(sizeof(ccl_spline_params));
}
if(ccl_gsl == NULL) {
ccl_gsl = malloc(sizeof(ccl_gsl_params));
memcpy(ccl_gsl, &default_gsl_params, sizeof(ccl_gsl_params));
}
/* Exit gracefully if we couldn't allocate memory */
if(ccl_splines==NULL || ccl_gsl==NULL) {
ccl_raise_exception(CCL_ERROR_MEMORY, "ccl_core.c: Failed to allocate memory for config file data.");
return;
}
#define MATCH(s, action) if (0 == strcmp(var_name, s)) { action ; continue;} do{} while(0)
int lineno = 0;
while(! feof(fconfig)) {
rtn = fgets(buf, CONFIG_LINE_BUFFER_SIZE, fconfig);
lineno ++;
if (buf[0]==';' || buf[0]=='[' || buf[0]=='\n') {
continue;
}
else {
sscanf(buf, "%99[^=]=%le\n",var_name, &var_dbl);
// Spline parameters
MATCH("A_SPLINE_NA", ccl_splines->A_SPLINE_NA=(int) var_dbl);
MATCH("A_SPLINE_NLOG", ccl_splines->A_SPLINE_NLOG=(int) var_dbl);
MATCH("A_SPLINE_MINLOG", ccl_splines->A_SPLINE_MINLOG=var_dbl);
MATCH("A_SPLINE_MIN", ccl_splines->A_SPLINE_MIN=var_dbl);
MATCH("A_SPLINE_MINLOG_PK", ccl_splines->A_SPLINE_MINLOG_PK=var_dbl);
MATCH("A_SPLINE_MIN_PK", ccl_splines->A_SPLINE_MIN_PK=var_dbl);
MATCH("A_SPLINE_MAX", ccl_splines->A_SPLINE_MAX=var_dbl);
MATCH("LOGM_SPLINE_DELTA", ccl_splines->LOGM_SPLINE_DELTA=var_dbl);
MATCH("LOGM_SPLINE_NM", ccl_splines->LOGM_SPLINE_NM=(int) var_dbl);
MATCH("LOGM_SPLINE_MIN", ccl_splines->LOGM_SPLINE_MIN=var_dbl);
MATCH("LOGM_SPLINE_MAX", ccl_splines->LOGM_SPLINE_MAX=var_dbl);
MATCH("A_SPLINE_NA_PK", ccl_splines->A_SPLINE_NA_PK=(int) var_dbl);
MATCH("A_SPLINE_NLOG_PK", ccl_splines->A_SPLINE_NLOG_PK=(int) var_dbl);
MATCH("K_MAX_SPLINE", ccl_splines->K_MAX_SPLINE=var_dbl);
MATCH("K_MAX", ccl_splines->K_MAX=var_dbl);
MATCH("K_MIN", ccl_splines->K_MIN=var_dbl);
MATCH("N_K", ccl_splines->N_K=(int) var_dbl);
// 3dcorr parameters
MATCH("N_K_3DCOR", ccl_splines->N_K_3DCOR=(int) var_dbl);
// GSL parameters
MATCH("GSL_EPSREL", ccl_gsl->EPSREL=var_dbl);
MATCH("GSL_N_ITERATION", ccl_gsl->N_ITERATION=(size_t) var_dbl);
MATCH("GSL_INTEGRATION_GAUSS_KRONROD_POINTS", ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS=(int) var_dbl);
MATCH("GSL_INTEGRATION_EPSREL", ccl_gsl->INTEGRATION_EPSREL=var_dbl);
MATCH("GSL_INTEGRATION_DISTANCE_EPSREL", ccl_gsl->INTEGRATION_DISTANCE_EPSREL=var_dbl);
MATCH("GSL_INTEGRATION_DNDZ_EPSREL", ccl_gsl->INTEGRATION_DNDZ_EPSREL=var_dbl);
MATCH("GSL_INTEGRATION_SIGMAR_EPSREL", ccl_gsl->INTEGRATION_SIGMAR_EPSREL=var_dbl);
MATCH("GSL_INTEGRATION_NU_EPSREL", ccl_gsl->INTEGRATION_NU_EPSREL=var_dbl);
MATCH("GSL_INTEGRATION_NU_EPSABS", ccl_gsl->INTEGRATION_NU_EPSABS=var_dbl);
MATCH("GSL_INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS", ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS=(int) var_dbl);
MATCH("GSL_INTEGRATION_LIMBER_EPSREL", ccl_gsl->INTEGRATION_LIMBER_EPSREL=var_dbl);
MATCH("GSL_ROOT_EPSREL", ccl_gsl->ROOT_EPSREL=var_dbl);
MATCH("GSL_ROOT_N_ITERATION", ccl_gsl->ROOT_N_ITERATION=(int) var_dbl);
MATCH("GSL_ODE_GROWTH_EPSREL", ccl_gsl->ODE_GROWTH_EPSREL=var_dbl);
ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, "ccl_core.c: Failed to parse config file at line %d: %s", lineno, buf);
}
}
#undef MATCH
fclose(fconfig);
}
/* ------- ROUTINE: ccl_cosmology_create ------
INPUTS: ccl_parameters params
ccl_configuration config
TASK: creates the ccl_cosmology struct and passes some values to it
DEFINITIONS:
chi: comoving distance [Mpc]
growth: growth function (density)
fgrowth: logarithmic derivative of the growth (density) (dlnD/da?)
E: E(a)=H(a)/H0
accelerator: interpolation accelerator for functions of a
accelerator_achi: interpolation accelerator for functions of chi
growth0: growth at z=0, defined to be 1
sigma: ?
p_lin: linear matter power spectrum at z=0?
p_lnl: nonlinear matter power spectrum at z=0?
computed_distances, computed_growth,
computed_power, computed_sigma: store status of the computations
*/
ccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config)
{
ccl_cosmology * cosmo = malloc(sizeof(ccl_cosmology));
cosmo->params = params;
cosmo->config = config;
cosmo->data.chi = NULL;
cosmo->data.growth = NULL;
cosmo->data.fgrowth = NULL;
cosmo->data.E = NULL;
cosmo->data.accelerator=NULL;
cosmo->data.accelerator_achi=NULL;
cosmo->data.accelerator_m=NULL;
cosmo->data.accelerator_d=NULL;
cosmo->data.accelerator_k=NULL;
cosmo->data.growth0 = 1.;
cosmo->data.achi=NULL;
cosmo->data.logsigma = NULL;
cosmo->data.dlnsigma_dlogm = NULL;
// hmf parameter for interpolation
cosmo->data.alphahmf = NULL;
cosmo->data.betahmf = NULL;
cosmo->data.gammahmf = NULL;
cosmo->data.phihmf = NULL;
cosmo->data.etahmf = NULL;
cosmo->data.p_lin = NULL;
cosmo->data.p_nl = NULL;
//cosmo->data.nu_pspace_int = NULL;
cosmo->computed_distances = false;
cosmo->computed_growth = false;
cosmo->computed_power = false;
cosmo->computed_sigma = false;
cosmo->computed_hmfparams = false;
cosmo->status = 0;
ccl_cosmology_set_status_message(cosmo, "");
return cosmo;
}
/* ------ ROUTINE: ccl_parameters_fill_initial -------
INPUT: ccl_parameters: params
TASK: fill parameters not set by ccl_parameters_create with some initial values
DEFINITIONS:
Omega_g = (Omega_g*h^2)/h^2 is the radiation parameter; "g" is for photons, as in CLASS
T_CMB: CMB temperature in Kelvin
Omega_l: Lambda
A_s: amplitude of the primordial PS, enforced here to initially set to NaN
sigma8: variance in 8 Mpc/h spheres for normalization of matter PS, enforced here to initially set to NaN
z_star: recombination redshift
*/
void ccl_parameters_fill_initial(ccl_parameters * params, int *status)
{
// Fixed radiation parameters
// Omega_g * h**2 is known from T_CMB
params->T_CMB = TCMB;
// kg / m^3
double rho_g = 4. * STBOLTZ / pow(CLIGHT, 3) * pow(params->T_CMB, 4);
// kg / m^3
double rho_crit = RHO_CRITICAL * SOLAR_MASS/pow(MPC_TO_METER, 3) * pow(params->h, 2);
params->Omega_g = rho_g/rho_crit;
// Get the N_nu_rel from Neff and N_nu_mass
params->N_nu_rel = params->Neff - params->N_nu_mass * pow(TNCDM, 4) / pow(4./11.,4./3.);
// Temperature of the relativistic neutrinos in K
double T_nu= (params->T_CMB) * pow(4./11.,1./3.);
// in kg / m^3
double rho_nu_rel = params->N_nu_rel* 7.0/8.0 * 4. * STBOLTZ / pow(CLIGHT, 3) * pow(T_nu, 4);
params-> Omega_n_rel = rho_nu_rel/rho_crit;
// If non-relativistic neutrinos are present, calculate the phase_space integral.
if((params->N_nu_mass)>0) {
// Pass NULL for the accelerator here because we don't have our cosmology object defined yet.
params->Omega_n_mass = ccl_Omeganuh2(1.0, params->N_nu_mass, params->mnu, params->T_CMB, NULL, status) / ((params->h)*(params->h));
ccl_check_status_nocosmo(status);
}
else{
params->Omega_n_mass = 0.;
}
params->Omega_m = params->Omega_b + params-> Omega_c;
params->Omega_l = 1.0 - params->Omega_m - params->Omega_g - params->Omega_n_rel -params->Omega_n_mass- params->Omega_k;
// Initially undetermined parameters - set to nan to trigger
// problems if they are mistakenly used.
if (isfinite(params->A_s)) {params->sigma8 = NAN;}
if (isfinite(params->sigma8)) {params->A_s = NAN;}
params->z_star = NAN;
if(fabs(params->Omega_k)<1E-6)
params->k_sign=0;
else if(params->Omega_k>0)
params->k_sign=-1;
else
params->k_sign=1;
params->sqrtk=sqrt(fabs(params->Omega_k))*params->h/CLIGHT_HMPC;
}
/* ------ ROUTINE: ccl_parameters_create -------
INPUT: numbers for the basic cosmological parameters needed by CCL
TASK: fill params with some initial values provided by the user
DEFINITIONS:
Omega_c: cold dark matter
Omega_b: baryons
Omega_m: matter
Omega_k: curvature
little omega_x means Omega_x*h^2
Neff : Effective number of neutrino speces
mnu : Pointer to either sum of neutrino masses or list of three masses.
mnu_type : how the neutrino mass(es) should be treated
w0: Dark energy eq of state parameter
wa: Dark energy eq of state parameter, time variation
H0: Hubble's constant in km/s/Mpc.
h: Hubble's constant divided by (100 km/s/Mpc).
A_s: amplitude of the primordial PS
n_s: index of the primordial PS
*/
ccl_parameters ccl_parameters_create(
double Omega_c, double Omega_b, double Omega_k,
double Neff, double* mnu, ccl_mnu_convention mnu_type,
double w0, double wa, double h, double norm_pk,
double n_s, double bcm_log10Mc, double bcm_etab,
double bcm_ks, int nz_mgrowth, double *zarr_mgrowth,
double *dfarr_mgrowth, int *status)
{
#ifndef USE_GSL_ERROR
gsl_set_error_handler_off ();
#endif
ccl_parameters params;
// Initialize params
params.mnu = NULL;
params.z_mgrowth=NULL;
params.df_mgrowth=NULL;
params.sigma8 = NAN;
params.A_s = NAN;
params.Omega_c = Omega_c;
params.Omega_b = Omega_b;
params.Omega_k = Omega_k;
params.Neff = Neff;
// Set the sum of neutrino masses
params.sum_nu_masses = *mnu;
double mnusum = *mnu;
double *mnu_in = NULL;
/* Check whether ccl_splines and ccl_gsl exist. If either is not set yet, load
parameters from the config file. */
if(ccl_splines==NULL || ccl_gsl==NULL) {
ccl_cosmology_read_config();
}
// Decide how to split sum of neutrino masses between 3 neutrinos. We use
// a Newton's rule numerical solution (thanks M. Jarvis).
if (mnu_type==ccl_mnu_sum){
// Normal hierarchy
mnu_in = malloc(3*sizeof(double));
// Check if the sum is zero
if (*mnu<1e-15){
mnu_in[0] = 0.;
mnu_in[1] = 0.;
mnu_in[2] = 0.;
} else{
mnu_in[0] = 0.; // This is a starting guess.
double sum_check;
// Check that sum is consistent
mnu_in[1] = sqrt(DELTAM12_sq);
mnu_in[2] = sqrt(DELTAM13_sq_pos);
sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];
if (ccl_mnu_sum < sum_check){
*status = CCL_ERROR_MNU_UNPHYSICAL;
}
double dsdm1;
// This is the Newton's method
while (fabs(*mnu - sum_check) > 1e-15){
dsdm1 = 1. + mnu_in[0] / mnu_in[1] + mnu_in[0] / mnu_in[2];
mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1;
mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq);
mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_pos);
sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];
}
}
} else if (mnu_type==ccl_mnu_sum_inverted){
// Inverted hierarchy
mnu_in = malloc(3*sizeof(double));
// Check if the sum is zero
if (*mnu<1e-15){
mnu_in[0] = 0.;
mnu_in[1] = 0.;
mnu_in[2] = 0.;
} else{
mnu_in[0] = 0.; // This is a starting guess.
double sum_check;
// Check that sum is consistent
mnu_in[1] = sqrt(-1.* DELTAM13_sq_neg - DELTAM12_sq);
mnu_in[2] = sqrt(-1.* DELTAM13_sq_neg);
sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];
if (ccl_mnu_sum < sum_check){
*status = CCL_ERROR_MNU_UNPHYSICAL;
}
double dsdm1;
// This is the Newton's method
while (fabs(*mnu- sum_check) > 1e-15){
dsdm1 = 1. + (mnu_in[0] / mnu_in[1]) + (mnu_in[0] / mnu_in[2]);
mnu_in[0] = mnu_in[0] - (sum_check - *mnu) / dsdm1;
mnu_in[1] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM12_sq);
mnu_in[2] = sqrt(mnu_in[0]*mnu_in[0] + DELTAM13_sq_neg);
sum_check = mnu_in[0] + mnu_in[1] + mnu_in[2];
}
}
} else if (mnu_type==ccl_mnu_sum_equal){
// Split the sum of masses equally
mnu_in = malloc(3*sizeof(double));
mnu_in[0] = params.sum_nu_masses / 3.;
mnu_in[1] = params.sum_nu_masses / 3.;
mnu_in[2] = params.sum_nu_masses / 3.;
} else if (mnu_type == ccl_mnu_list){
// A list of neutrino masses was already passed in
params.sum_nu_masses = mnu[0] + mnu[1] + mnu[2];
mnu_in = malloc(3*sizeof(double));
for(int i=0; i<3; i++) mnu_in[i] = mnu[i];
} else {
*status = CCL_ERROR_NOT_IMPLEMENTED;
}
// Check for errors in the neutrino set up (e.g. unphysical mnu)
ccl_check_status_nocosmo(status);
// Check which of the neutrino species are non-relativistic today
int N_nu_mass = 0;
for(int i = 0; i<3; i=i+1){
if (mnu_in[i] > 0.00017){ // Limit taken from Lesgourges et al. 2012
N_nu_mass = N_nu_mass + 1;
}
}
params.N_nu_mass = N_nu_mass;
// Fill the array of massive neutrinos
if (N_nu_mass>0){
params.mnu = malloc(params.N_nu_mass*sizeof(double));
int relativistic[3] = {0, 0, 0};
for (int i = 0; i < N_nu_mass; i = i + 1){
for (int j = 0; j<3; j = j +1){
if ((mnu_in[j]>0.00017) && (relativistic[j]==0)){
relativistic[j]=1;
params.mnu[i] = mnu_in[j];
break;
}
} // end loop over neutrinos
} // end loop over massive neutrinos
} else{
params.mnu = malloc(sizeof(double));
params.mnu[0] = 0.;
}
// Free mnu_in
if (mnu_in != NULL) free(mnu_in);
// Dark Energy
params.w0 = w0;
params.wa = wa;
// Hubble parameters
params.h = h;
params.H0 = h*100;
// Primordial power spectra
if(norm_pk<1E-5)
params.A_s=norm_pk;
else
params.sigma8=norm_pk;
params.n_s = n_s;
//Baryonic params
if(bcm_log10Mc<0)
params.bcm_log10Mc=log10(1.2e14);
else
params.bcm_log10Mc=bcm_log10Mc;
if(bcm_etab<0)
params.bcm_etab=0.5;
else
params.bcm_etab=bcm_etab;
if(bcm_ks<0)
params.bcm_ks=55.0;
else
params.bcm_ks=bcm_ks;
// Set remaining standard and easily derived parameters
ccl_parameters_fill_initial(¶ms, status);
//Trigger modified growth function if nz>0
if(nz_mgrowth>0) {
params.has_mgrowth=true;
params.nz_mgrowth=nz_mgrowth;
params.z_mgrowth=malloc(params.nz_mgrowth*sizeof(double));
params.df_mgrowth=malloc(params.nz_mgrowth*sizeof(double));
memcpy(params.z_mgrowth,zarr_mgrowth,params.nz_mgrowth*sizeof(double));
memcpy(params.df_mgrowth,dfarr_mgrowth,params.nz_mgrowth*sizeof(double));
}
else {
params.has_mgrowth=false;
params.nz_mgrowth=0;
params.z_mgrowth=NULL;
params.df_mgrowth=NULL;
}
return params;
}
/* ------- ROUTINE: ccl_parameters_create_flat_lcdm --------
INPUT: some cosmological parameters needed to create a flat LCDM model
TASK: call ccl_parameters_create to produce an LCDM model
*/
ccl_parameters ccl_parameters_create_flat_lcdm(double Omega_c, double Omega_b, double h,
double norm_pk, double n_s, int *status)
{
double Omega_k = 0.0;
double Neff = 3.046;
double w0 = -1.0;
double wa = 0.0;
double *mnu;
double mnuval = 0.; // a pointer to the variable is not kept past the lifetime of this function
mnu = &mnuval;
ccl_mnu_convention mnu_type = ccl_mnu_sum;
ccl_parameters params = ccl_parameters_create(Omega_c, Omega_b, Omega_k, Neff,
mnu, mnu_type, w0, wa, h, norm_pk, n_s, -1, -1, -1, -1, NULL, NULL, status);
return params;
}
/**
* Write a cosmology parameters object to a file in yaml format.
* @param cosmo Cosmological parameters
* @param f FILE* pointer opened for reading
* @return void
*/
void ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int *status)
{
FILE * f = fopen(filename, "w");
if (!f){
*status = CCL_ERROR_FILE_WRITE;
return;
}
#define WRITE_DOUBLE(name) fprintf(f, #name ": %le\n",params->name)
#define WRITE_INT(name) fprintf(f, #name ": %d\n",params->name)
// Densities: CDM, baryons, total matter, curvature
WRITE_DOUBLE(Omega_c);
WRITE_DOUBLE(Omega_b);
WRITE_DOUBLE(Omega_m);
WRITE_DOUBLE(Omega_k);
WRITE_INT(k_sign);
// Dark Energy
WRITE_DOUBLE(w0);
WRITE_DOUBLE(wa);
// Hubble parameters
WRITE_DOUBLE(H0);
WRITE_DOUBLE(h);
// Neutrino properties
WRITE_DOUBLE(Neff);
WRITE_INT(N_nu_mass);
WRITE_DOUBLE(N_nu_rel);
if (params->N_nu_mass>0){
fprintf(f, "mnu: [");
for (int i=0; i<params->N_nu_mass; i++){
fprintf(f, "%le, ", params->mnu[i]);
}
fprintf(f, "]\n");
}
WRITE_DOUBLE(sum_nu_masses);
WRITE_DOUBLE(Omega_n_mass);
WRITE_DOUBLE(Omega_n_rel);
// Primordial power spectra
WRITE_DOUBLE(A_s);
WRITE_DOUBLE(n_s);
// Radiation parameters
WRITE_DOUBLE(Omega_g);
WRITE_DOUBLE(T_CMB);
// BCM baryonic model parameters
WRITE_DOUBLE(bcm_log10Mc);
WRITE_DOUBLE(bcm_etab);
WRITE_DOUBLE(bcm_ks);
// Derived parameters
WRITE_DOUBLE(sigma8);
WRITE_DOUBLE(Omega_l);
WRITE_DOUBLE(z_star);
WRITE_INT(has_mgrowth);
WRITE_INT(nz_mgrowth);
if (params->has_mgrowth){
fprintf(f, "z_mgrowth: [");
for (int i=0; i<params->nz_mgrowth; i++){
fprintf(f, "%le, ", params->z_mgrowth[i]);
}
fprintf(f, "]\n");
fprintf(f, "df_mgrowth: [");
for (int i=0; i<params->nz_mgrowth; i++){
fprintf(f, "%le, ", params->df_mgrowth[i]);
}
fprintf(f, "]\n");
}
#undef WRITE_DOUBLE
#undef WRITE_INT
fclose(f);
}
/**
* Write a cosmology parameters object to a file in yaml format.
* @param cosmo Cosmological parameters
* @param f FILE* pointer opened for reading
* @return void
*/
ccl_parameters ccl_parameters_read_yaml(const char * filename, int *status)
{
FILE * f = fopen(filename, "r");
if (!f){
*status = CCL_ERROR_FILE_READ;
ccl_parameters bad_params;
ccl_raise_exception(CCL_ERROR_FILE_READ, "ccl_core.c: Failed to read parameters from file.");
return bad_params;
}
#define READ_DOUBLE(name) double name; *status |= (0==fscanf(f, #name ": %le\n",&name));
#define READ_INT(name) int name; *status |= (0==fscanf(f, #name ": %d\n",&name))
// Densities: CDM, baryons, total matter, curvature
READ_DOUBLE(Omega_c);
READ_DOUBLE(Omega_b);
READ_DOUBLE(Omega_m);
READ_DOUBLE(Omega_k);
READ_INT(k_sign);
// Dark Energy
READ_DOUBLE(w0);
READ_DOUBLE(wa);
// Hubble parameters
READ_DOUBLE(H0);
READ_DOUBLE(h);
// Neutrino properties
READ_DOUBLE(Neff);
READ_INT(N_nu_mass);
READ_DOUBLE(N_nu_rel);
double mnu[3] = {0.0, 0.0, 0.0};
if (N_nu_mass>0){
*status |= (0==fscanf(f, "mnu: ["));
for (int i=0; i<N_nu_mass; i++){
*status |= (0==fscanf(f, "%le, ", mnu+i));
}
*status |= (0==fscanf(f, "]\n"));
}
READ_DOUBLE(sum_nu_masses);
READ_DOUBLE(Omega_n_mass);
READ_DOUBLE(Omega_n_rel);
// Primordial power spectra
READ_DOUBLE(A_s);
READ_DOUBLE(n_s);
// Radiation parameters
READ_DOUBLE(Omega_g);
READ_DOUBLE(T_CMB);
// BCM baryonic model parameters
READ_DOUBLE(bcm_log10Mc);
READ_DOUBLE(bcm_etab);
READ_DOUBLE(bcm_ks);
// Derived parameters
READ_DOUBLE(sigma8);
READ_DOUBLE(Omega_l);
READ_DOUBLE(z_star);
READ_INT(has_mgrowth);
READ_INT(nz_mgrowth);
double *z_mgrowth;
double *df_mgrowth;
if (has_mgrowth){
z_mgrowth = malloc(nz_mgrowth*sizeof(double));
df_mgrowth = malloc(nz_mgrowth*sizeof(double));
*status |= (0==fscanf(f, "z_mgrowth: ["));
for (int i=0; i<nz_mgrowth; i++){
*status |= (0==fscanf(f, "%le, ", z_mgrowth+i));
}
*status |= (0==fscanf(f, "]\n"));
*status |= (0==fscanf(f, "df_mgrowth: ["));
for (int i=0; i<nz_mgrowth; i++){
*status |= (0==fscanf(f, "%le, ", df_mgrowth+i));
}
*status |= (0==fscanf(f, "]\n"));
}
else{
z_mgrowth = NULL;
df_mgrowth = NULL;
}
#undef READ_DOUBLE
#undef READ_INT
fclose(f);
if (status){
char msg[256];
snprintf(msg, 256, "ccl_core.c: Structure of YAML file incorrect: %s", filename);
ccl_raise_exception(*status, msg);
}
double norm_pk;
if (isnan(A_s)){
norm_pk = sigma8;
}
else{
norm_pk = A_s;
}
ccl_parameters params = ccl_parameters_create(
Omega_c, Omega_b, Omega_k,
Neff, mnu, ccl_mnu_list,
w0, wa, h, norm_pk,
n_s, bcm_log10Mc, bcm_etab,
bcm_ks, nz_mgrowth, z_mgrowth,
df_mgrowth, status);
if(z_mgrowth) free(z_mgrowth);
if (df_mgrowth) free(df_mgrowth);
return params;
}
/* ------- ROUTINE: ccl_data_free --------
INPUT: ccl_data
TASK: free the input data
*/
void ccl_data_free(ccl_data * data)
{
//We cannot assume that all of these have been allocated
//TODO: it would actually make more sense to do this within ccl_cosmology_free,
//where we could make use of the flags "computed_distances" etc. to figure out
//what to free up
gsl_spline_free(data->chi);
gsl_spline_free(data->growth);
gsl_spline_free(data->fgrowth);
gsl_interp_accel_free(data->accelerator);
gsl_interp_accel_free(data->accelerator_achi);
gsl_spline_free(data->E);
gsl_spline_free(data->achi);
gsl_spline_free(data->logsigma);
gsl_spline_free(data->dlnsigma_dlogm);
gsl_spline2d_free(data->p_lin);
gsl_spline2d_free(data->p_nl);
gsl_spline_free(data->alphahmf);
gsl_spline_free(data->betahmf);
gsl_spline_free(data->gammahmf);
gsl_spline_free(data->phihmf);
gsl_spline_free(data->etahmf);
gsl_interp_accel_free(data->accelerator_d);
gsl_interp_accel_free(data->accelerator_m);
gsl_interp_accel_free(data->accelerator_k);
}
/* ------- ROUTINE: ccl_cosmology_set_status_message --------
INPUT: ccl_cosmology struct, status_string
TASK: set the status message safely.
*/
void ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * message, ...)
{
const int trunc = 480; /* must be < 500 - 4 */
va_list va;
va_start(va, message);
vsnprintf(cosmo->status_message, trunc, message, va);
va_end(va);
/* if truncation happens, message[trunc - 1] is not NULL, ... will show up. */
strcpy(&cosmo->status_message[trunc], "...");
}
/* ------- ROUTINE: ccl_parameters_free --------
INPUT: ccl_parameters struct
TASK: free allocated quantities in the parameters struct
*/
void ccl_parameters_free(ccl_parameters * params)
{
if (params->mnu != NULL){
free(params->mnu);
params->mnu = NULL;
}
if (params->z_mgrowth != NULL){
free(params->z_mgrowth);
params->z_mgrowth = NULL;
}
if (params->df_mgrowth != NULL){
free(params->df_mgrowth);
params->df_mgrowth = NULL;
}
}
/* ------- ROUTINE: ccl_cosmology_free --------
INPUT: ccl_cosmology struct
TASK: free the input data and the cosmology struct
*/
void ccl_cosmology_free(ccl_cosmology * cosmo)
{
ccl_data_free(&cosmo->data);
free(cosmo);
}
|
New York State Route 368 ( NY 368 ) was a state highway in Onondaga County , New York , in the United States . It was one of the shortest routes in the county , extending for only 1 @.@ 69 miles ( 2 @.@ 72 km ) between NY 321 and NY 5 in the town of Elbridge . NY 368 was known as Halfway Road for the hamlet it served near its midpoint . The route was assigned in the 1930s and removed in 1980 as part of a highway maintenance swap between the state of New York and Onondaga County .
|
module WithApp where
f
: {A : Set}
→ A
→ A
f x
with x
... | y
= y
g
: {A : Set}
→ A
→ A
→ A
g x y
with x
... | _
with y
... | _
= x
|
#include "Decoder.h"
#include <boost/python.hpp>
#include <boost/python/str.hpp>
#include <boost_opencv_converter.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
namespace py = boost::python;
cv::Mat Stream_getFrame(Stream& self) {
u32 height, width;
u8* img_data;
img_data = self.GetFrame(&width, &height);
cv::Mat img_buffer(height+height/2, width, CV_8UC1, (uchar *)img_data);
cv::Mat original;
cv::cvtColor(img_buffer, original, cv::COLOR_YUV2RGB_YV12);
return original;
}
int Stream_broadwayDecode(Stream& self) {
StreamStatus status = self.BroadwayDecode();
return (int)status;
}
void Stream_setStream(Stream& self, const cv::Mat& strmBuffer) {
u8* buffer = strmBuffer.data;
u32 buff_length = (u32)strmBuffer.rows;
self.SetStream(buffer, buff_length);
}
void Stream_updateStream(Stream& self, const cv::Mat& strmBuffer) {
u8* buffer = strmBuffer.data;
u32 buff_length = (u32)strmBuffer.rows;
self.UpdateStream(buffer, buff_length);
}
BOOST_PYTHON_MODULE(h264_decoder)
{
ExportConverters();
py::class_<Stream, boost::noncopyable>("Stream")
.def("GetFrame", &Stream_getFrame)
.def("BroadwayDecode", &Stream_broadwayDecode)
.def("SetStream", &Stream_setStream)
.def("UpdateStream", &Stream_updateStream)
;
} |
function this = read_matrix_from_workspace(this, inputMatrix)
% Reads in matrix from workspace, updates dimInfo according to data
% dimensions
%
% Y = MrDataNd()
% Y.read_matrix_from_workspace()
%
% This is a method of class MrDataNd.
%
% IN
%
% OUT
%
% EXAMPLE
% read_matrix_from_workspace
%
% See also MrDataNd
% Author: Saskia Bollmann & Lars Kasper
% Created: 2016-10-12
% Copyright (C) 2016 Institute for Biomedical Engineering
% University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
% <http://www.gnu.org/licenses/>.
% check whether valid dimInfo now
% TODO: update dimInfo, but keeping information that is unaltered by
% changing data dimensions...
% e.g. via dimInfo.merge
hasDimInfo = isa(this.dimInfo, 'MrDimInfo');
this.data = inputMatrix;
% remove singleton 2nd dimension kept by size command
nSamples = size(this.data);
if numel(nSamples) == 2
nSamples(nSamples==1) = [];
end
resolutions = ones(1, numel(nSamples));
% set dimInfo or update according to actual number of samples
if ~hasDimInfo
this.dimInfo = MrDimInfo('nSamples', nSamples, ...
'resolutions', resolutions);
else
if any(nSamples) % only update dimInfo, if any samples loaded
if (numel(nSamples) ~= this.dimInfo.nDims)
% only display the warning of an non-empty dimInfo (i.e. nDims
% ~=0) has been given
if (this.dimInfo.nDims ~=0)
warning('Number of dimensions in dimInfo (%d) does not match dimensions in data (%d), resetting dimInfo', ...
this.dimInfo.nDims, numel(nSamples));
end
this.dimInfo = MrDimInfo('nSamples', nSamples, ...
'resolutions', resolutions);
elseif ~isequal(this.dimInfo.nSamples, nSamples)
% if nSamples are correct already, leave it at that, otherwise:
currentResolution = this.dimInfo.resolutions;
isValidResolution = ~any(isnan(currentResolution)) || ...
~any(isinf(currentResolution)) && ...
numel(currentResolution) == numel(nSamples);
if isValidResolution
% use update of nSamples to keep existing offset of samplingPoints
this.dimInfo.nSamples = nSamples;
else % update with default resolutions = 1
this.dimInfo.set_dims(1:this.dimInfo.nDims, 'nSamples', ...
nSamples, 'resolutions', resolutions);
end
end
end
end
|
\chapter{A SAMPLE APPENDIX}
\label{app:app1}
Just put in text as you would into any chapter with sections and
whatnot. That's the end of it.
More details on how to use these specific packages are available along
with the documentation of the respective packages. |
/*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under 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.
*/
#include <stdarg.h>
#include <boost/assert.hpp>
#include "cetty/util/Exception.h"
#include "cetty/util/internal/ConversionUtil.h"
#include "cetty/channel/Channel.h"
#include "cetty/channel/ChannelPipelineFactory.h"
#include "cetty/channel/ChannelState.h"
#include "cetty/channel/UpstreamChannelStateEvent.h"
#include "cetty/channel/DownstreamChannelStateEvent.h"
#include "cetty/channel/UpstreamMessageEvent.h"
#include "cetty/channel/DownstreamMessageEvent.h"
#include "cetty/channel/DefaultChannelFuture.h"
#include "cetty/channel/DefaultChannelPipeline.h"
#include "cetty/channel/DefaultChildChannelStateEvent.h"
#include "cetty/channel/DefaultWriteCompletionEvent.h"
#include "cetty/channel/DefaultExceptionEvent.h"
#include "cetty/channel/FailedChannelFuture.h"
#include "cetty/channel/AbstractChannel.h"
#include "cetty/channel/SucceededChannelFuture.h"
#include "cetty/channel/Channels.h"
namespace cetty { namespace channel {
using namespace cetty::util;
using namespace cetty::util::internal;
class CloneChannelPipelineFactory : public ChannelPipelineFactory {
public:
CloneChannelPipelineFactory(ChannelPipeline* pipeline)
: cloneFromPipeline(pipeline) {
}
virtual ~CloneChannelPipelineFactory() {}
ChannelPipeline* getPipeline() {
return Channels::pipeline(cloneFromPipeline);
}
private:
ChannelPipeline* cloneFromPipeline;
};
ChannelPipeline* Channels::pipeline() {
return new DefaultChannelPipeline();
}
ChannelPipeline* Channels::pipeline(ChannelPipeline* pipeline) {
ChannelPipeline* newPipeline = Channels::pipeline();
BOOST_ASSERT(newPipeline);
ChannelPipeline::ChannelHandlers handlers = pipeline->toMap();
ChannelPipeline::ChannelHandlers::iterator itr = handlers.begin();
for (; itr != handlers.end(); ++itr) {
newPipeline->addLast(itr->first, itr->second->clone());
}
return newPipeline;
}
ChannelPipeline* Channels::pipeline(const ChannelHandlerPtr& handler) {
ChannelPipeline* newPipeline = pipeline();
if (handler) { newPipeline->addLast("0", handler); }
return newPipeline;
}
ChannelPipeline* Channels::pipeline(const ChannelHandlerPtr& handler0,
const ChannelHandlerPtr& handler1) {
ChannelPipeline* newPipeline = pipeline();
if (handler0) { newPipeline->addLast("0", handler0); }
if (handler1) { newPipeline->addLast("1", handler1); }
return newPipeline;
}
ChannelPipeline* Channels::pipeline(const ChannelHandlerPtr& handler0,
const ChannelHandlerPtr& handler1,
const ChannelHandlerPtr& handler2) {
ChannelPipeline* newPipeline = pipeline();
if (handler0) { newPipeline->addLast("0", handler0); }
if (handler1) { newPipeline->addLast("1", handler1); }
if (handler1) { newPipeline->addLast("2", handler2); }
return newPipeline;
}
ChannelPipeline* Channels::pipeline(const ChannelHandlerPtr& handler0,
const ChannelHandlerPtr& handler1,
const ChannelHandlerPtr& handler2,
const ChannelHandlerPtr& handler3) {
ChannelPipeline* newPipeline = pipeline();
if (handler0) { newPipeline->addLast("0", handler0); }
if (handler1) { newPipeline->addLast("1", handler1); }
if (handler1) { newPipeline->addLast("2", handler2); }
if (handler1) { newPipeline->addLast("3", handler3); }
return newPipeline;
}
ChannelPipeline* Channels::pipeline(const std::vector<ChannelHandlerPtr>& handlers) {
ChannelPipeline* newPipeline = Channels::pipeline();
BOOST_ASSERT(newPipeline);
for (size_t i = 0; i < handlers.size(); ++i) {
const ChannelHandlerPtr& h = handlers[i];
if (!h) {
continue;
}
newPipeline->addLast(ConversionUtil::toString((int)i), handlers[i]);
}
return newPipeline;
}
ChannelPipelineFactoryPtr Channels::pipelineFactory(ChannelPipeline* pipeline ) {
return ChannelPipelineFactoryPtr(new CloneChannelPipelineFactory(pipeline));
}
ChannelFuturePtr Channels::future(Channel& channel, bool cancellable) {
return ChannelFuturePtr(new DefaultChannelFuture(channel, cancellable));
}
ChannelFuturePtr Channels::failedFuture(Channel& channel, const Exception& cause) {
return ChannelFuturePtr(new FailedChannelFuture(channel, cause));
}
void Channels::fireChannelOpen(Channel& channel) {
// Notify the parent handler.
Channel* parent = channel.getParent();
if (parent != NULL) {
fireChildChannelStateChanged(*parent, channel);
}
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::OPEN, boost::any(true)));
}
void Channels::fireChannelOpen(ChannelHandlerContext& ctx) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::OPEN, boost::any(true)));
}
void Channels::fireChannelBound(Channel& channel, const SocketAddress& localAddress) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::BOUND, boost::any(&localAddress)));
}
void Channels::fireChannelBound(ChannelHandlerContext& ctx, const SocketAddress& localAddress) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::BOUND, boost::any(&localAddress)));
}
void Channels::fireChannelConnected(Channel& channel, const SocketAddress& remoteAddress) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::CONNECTED, boost::any(&remoteAddress)));
}
void Channels::fireChannelConnected(ChannelHandlerContext& ctx, const SocketAddress& remoteAddress) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::CONNECTED, boost::any(&remoteAddress)));
}
void Channels::fireMessageReceived(Channel& channel, const ChannelMessage& message) {
channel.getPipeline().sendUpstream(
UpstreamMessageEvent(channel, message, channel.getRemoteAddress()));
}
void Channels::fireMessageReceived(Channel& channel, const ChannelMessage& message, const SocketAddress& remoteAddress) {
channel.getPipeline().sendUpstream(
UpstreamMessageEvent(channel, message, remoteAddress));
}
void Channels::fireMessageReceived(ChannelHandlerContext& ctx, const ChannelMessage& message) {
Channel& channel = ctx.getChannel();
ctx.sendUpstream(
UpstreamMessageEvent(channel, message, channel.getRemoteAddress()));
}
void Channels::fireMessageReceived(ChannelHandlerContext& ctx, const ChannelMessage& message, const SocketAddress& remoteAddress) {
ctx.sendUpstream(
UpstreamMessageEvent(ctx.getChannel(), message, remoteAddress));
}
void Channels::fireWriteCompleted(Channel& channel, long amount) {
if (amount == 0) return;
channel.getPipeline().sendUpstream(DefaultWriteCompletionEvent(channel, amount));
}
void Channels::fireWriteCompleted(ChannelHandlerContext& ctx, long amount) {
ctx.sendUpstream(DefaultWriteCompletionEvent(ctx.getChannel(), amount));
}
void Channels::fireChannelInterestChanged(Channel& channel, int interestOps) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::INTEREST_OPS, boost::any(interestOps)));
}
void Channels::fireChannelInterestChanged(ChannelHandlerContext& ctx, int interestOps) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::INTEREST_OPS, boost::any(interestOps)));
}
void Channels::fireChannelDisconnected(Channel& channel) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::CONNECTED, boost::any()));
}
void Channels::fireChannelDisconnected(ChannelHandlerContext& ctx) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::CONNECTED, boost::any()));
}
void Channels::fireChannelUnbound(Channel& channel) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::BOUND, boost::any()));
}
void Channels::fireChannelUnbound(ChannelHandlerContext& ctx) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::BOUND, boost::any()));
}
void Channels::fireChannelClosed(Channel& channel) {
channel.getPipeline().sendUpstream(UpstreamChannelStateEvent(
channel, ChannelState::OPEN, boost::any()));
// Notify the parent handler.
Channel* parent = channel.getParent();
if (parent != NULL) {
fireChildChannelStateChanged(*parent, channel);
}
}
void Channels::fireChannelClosed(ChannelHandlerContext& ctx) {
ctx.sendUpstream(UpstreamChannelStateEvent(
ctx.getChannel(), ChannelState::OPEN, boost::any()));
}
void Channels::fireExceptionCaught(Channel& channel, const Exception& cause) {
channel.getPipeline().sendUpstream(
DefaultExceptionEvent(channel, cause));
}
void Channels::fireExceptionCaught(ChannelHandlerContext& ctx, const Exception& cause) {
ctx.sendUpstream(DefaultExceptionEvent(ctx.getChannel(), cause));
}
ChannelFuturePtr Channels::bind(Channel& channel, const SocketAddress& localAddress) {
ChannelFuturePtr future = Channels::future(channel);
channel.getPipeline().sendDownstream(DownstreamChannelStateEvent(
channel, future, ChannelState::BOUND, boost::any(localAddress)));
return future;
}
void Channels::bind(ChannelHandlerContext& ctx, const ChannelFuturePtr& future, const SocketAddress& localAddress) {
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::BOUND, boost::any(localAddress)));
}
ChannelFuturePtr Channels::unbind(Channel& channel) {
return channel.unbind();
}
void Channels::unbind(ChannelHandlerContext& ctx, const ChannelFuturePtr& future) {
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::BOUND));
}
ChannelFuturePtr Channels::connect(Channel& channel, const SocketAddress& remoteAddress) {
ChannelFuturePtr future = Channels::future(channel, true);
channel.getPipeline().sendDownstream(DownstreamChannelStateEvent(
channel, future, ChannelState::CONNECTED, boost::any(remoteAddress)));
return future;
}
void Channels::connect(ChannelHandlerContext& ctx, const ChannelFuturePtr& future, const SocketAddress& remoteAddress) {
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::CONNECTED, boost::any(remoteAddress)));
}
ChannelFuturePtr Channels::write(Channel& channel,
const ChannelMessage& message,
bool withFuture) {
return channel.write(message, withFuture);
}
void Channels::write(ChannelHandlerContext& ctx,
const ChannelFuturePtr& future,
const ChannelMessage& message) {
write(ctx, future, message, ctx.getChannel().getRemoteAddress());
}
ChannelFuturePtr Channels::write(Channel& channel,
const ChannelMessage& message,
const SocketAddress& remoteAddress,
bool withFuture) {
return channel.write(message, remoteAddress, withFuture);
}
void Channels::write(ChannelHandlerContext& ctx,
const ChannelFuturePtr& future,
const ChannelMessage& message,
const SocketAddress& remoteAddress) {
ctx.sendDownstream(
DownstreamMessageEvent(ctx.getChannel(), future, message, remoteAddress));
}
ChannelFuturePtr Channels::setInterestOps(Channel& channel, int interestOps) {
return channel.setInterestOps(interestOps);
}
void Channels::setInterestOps(ChannelHandlerContext& ctx,
const ChannelFuturePtr& future,
int interestOps) {
validateInterestOps(interestOps);
interestOps = filterDownstreamInterestOps(interestOps);
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::INTEREST_OPS, boost::any(interestOps)));
}
ChannelFuturePtr Channels::disconnect(Channel& channel) {
return channel.disconnect();
}
void Channels::disconnect(ChannelHandlerContext& ctx, const ChannelFuturePtr& future) {
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::CONNECTED));
}
ChannelFuturePtr Channels::close(Channel& channel) {
return channel.close();
}
void Channels::close(ChannelHandlerContext& ctx, const ChannelFuturePtr& future) {
ctx.sendDownstream(DownstreamChannelStateEvent(
ctx.getChannel(), future, ChannelState::OPEN));
}
void Channels::fireChildChannelStateChanged(Channel& channel, Channel& childChannel) {
channel.getPipeline().sendUpstream(
DefaultChildChannelStateEvent(channel, childChannel));
}
void Channels::validateInterestOps(int interestOps) {
switch (interestOps) {
case Channel::OP_NONE:
case Channel::OP_READ:
case Channel::OP_WRITE:
case Channel::OP_READ_WRITE:
break;
default:
throw InvalidArgumentException(
std::string("Invalid interestOps: ") + Integer::toString(interestOps));
}
}
int Channels::filterDownstreamInterestOps(int interestOps) {
return interestOps & (~Channel::OP_WRITE);
}
int Channels::validateAndFilterDownstreamInteresOps(int interestOps) {
validateInterestOps(interestOps);
return filterDownstreamInterestOps(interestOps);
}
}} |
//
// Created by yche on 12/13/17.
//
#include <iostream>
#include <boost/program_options.hpp>
#include "simrank.h"
int main(int argc, char *argv[]) {
string data_name = argv[1];
int a = atoi(argv[2]);
int b = atoi(argv[3]);
DirectedG g;
load_graph("./datasets/edge_list/" + data_name + ".txt", g);
TruthSim ts(data_name, g, 0.6, 0.00001);
cout << format("ground truth: %s") % ts.sim(a, b) << endl;
} |
import Lean4Axiomatic.Integer.Impl.Generic.Sign
import Lean4Axiomatic.Integer.Impl.Difference.Multiplication
import Lean4Axiomatic.Integer.Impl.Difference.Negation
namespace Lean4Axiomatic.Integer.Impl.Difference
variable {ℕ : Type} [Natural ℕ]
open Coe (coe)
open Signed (Negative Positive)
/--
A `Difference` of natural numbers is zero exactly when the numbers are
equivalent.
**Property intuition**: Subtracting a value from itself always gives zero.
**Proof intuition**: Expand the definition of `Difference` equivalence and add
or remove zeros.
-/
theorem zero_diff_eqv {n m : ℕ} : n——m ≃ 0 ↔ n ≃ m := by
apply Iff.intro
case mp =>
intro (_ : n——m ≃ 0)
show n ≃ m
have : n——m ≃ 0——0 := ‹n——m ≃ 0›
have : n + 0 ≃ 0 + m := ‹n——m ≃ 0——0›
exact Natural.add_swapped_zeros_eqv.mp ‹n + 0 ≃ 0 + m›
case mpr =>
intro (_ : n ≃ m)
show n——m ≃ 0
show n——m ≃ 0——0
show n + 0 ≃ 0 + m
exact Natural.add_swapped_zeros_eqv.mpr ‹n ≃ m›
/--
A `Difference` of natural numbers is negative exactly when the first component
is less than the second.
**Property intuition**: Subtracting a larger value from a smaller will give a
negative result.
**Proof intuition**: There's no simple trick for this proof. Just expand the
definitions of `Negative` and `(· < ·)` and show that the equivalence for one
implies the other.
-/
theorem neg_diff_lt {n m : ℕ} : Negative (n——m) ↔ n < m := by
have neg_diff {k : ℕ} : 0——k ≃ -1 * coe k := by
apply Rel.symm
calc
(-1) * coe k ≃ _ := Rel.refl
(-1) * k——0 ≃ _ := mul_neg_one
(-(k——0)) ≃ _ := Rel.refl
0——k ≃ _ := Rel.refl
apply Iff.intro
case mp =>
intro (_ : Negative (n——m))
show n < m
apply Natural.lt_defn_add.mpr
show ∃ (k : ℕ), Positive k ∧ m ≃ n + k
have
(NonzeroWithSign.intro (k : ℕ) (_ : Positive k) (_ : n——m ≃ -1 * coe k))
:= Generic.negative_iff_sign_neg1.mp ‹Negative (n——m)›
have : n——m ≃ 0——k := Rel.trans ‹n——m ≃ -1 * coe k› (Rel.symm neg_diff)
have : n + k ≃ 0 + m := ‹n——m ≃ 0——k›
have : m ≃ n + k := calc
m ≃ _ := Rel.symm AA.identL
0 + m ≃ _ := Rel.symm ‹n + k ≃ 0 + m›
n + k ≃ _ := Rel.refl
exact Exists.intro k (And.intro ‹Positive k› ‹m ≃ n + k›)
case mpr =>
intro (_ : n < m)
show Negative (n——m)
apply Generic.negative_iff_sign_neg1.mpr
show NonzeroWithSign (n——m) (-1)
have (Exists.intro k (And.intro (_ : Positive k) (_ : m ≃ n + k))) :=
Natural.lt_defn_add.mp ‹n < m›
apply NonzeroWithSign.intro k ‹Positive k›
show n——m ≃ -1 * coe k
have : 0——k ≃ -1 * coe k := neg_diff
apply (Rel.trans · ‹0——k ≃ -1 * coe k›)
show n——m ≃ 0——k
show n + k ≃ 0 + m
calc
n + k ≃ _ := Rel.symm ‹m ≃ n + k›
m ≃ _ := Rel.symm AA.identL
0 + m ≃ _ := Rel.refl
/--
A `Difference` of natural numbers is positive exactly when the first component
is greater than the second.
**Property intuition**: Subtracting a smaller value from a larger will give a
positive result.
**Proof intuition**: By definition, `n > m` is the same as `m < n`. And we
already know (from `neg_diff_lt`) that `m < n` is equivalent to
`Negative (m——n)`. So if we can show that `Positive (n——m)` iff
`Negative (m——n)`, then that will prove the result.
-/
theorem pos_diff_gt {n m : ℕ} : Positive (n——m) ↔ n > m := by
apply Iff.intro
case mp =>
intro (_ : Positive (n——m))
have
(NonzeroWithSign.intro (k : ℕ) (_ : Positive k) (_ : n——m ≃ 1 * coe k))
:= Generic.positive_iff_sign_pos1.mp ‹Positive (n——m)›
show m < n
apply neg_diff_lt.mp
show Negative (m——n)
apply Generic.negative_iff_sign_neg1.mpr
show NonzeroWithSign (m——n) (-1)
apply NonzeroWithSign.intro k ‹Positive k›
show m——n ≃ -1 * coe k
calc
m——n ≃ _ := Rel.symm neg_involutive
(-(-(m——n))) ≃ _ := Rel.refl
(-(n——m)) ≃ _ := AA.subst₁ ‹n——m ≃ 1 * coe k›
(-(1 * coe k)) ≃ _ := AA.scompatL
(-1) * coe k ≃ _ := Rel.refl
case mpr =>
intro (_ : m < n)
show Positive (n——m)
apply Generic.positive_iff_sign_pos1.mpr
show NonzeroWithSign (n——m) 1
have : Negative (m——n) := neg_diff_lt.mpr ‹m < n›
have
(NonzeroWithSign.intro (k : ℕ) (_ : Positive k) (_ : m——n ≃ -1 * coe k))
:= Generic.negative_iff_sign_neg1.mp ‹Negative (m——n)›
apply NonzeroWithSign.intro k ‹Positive k›
show n——m ≃ 1 * coe k
calc
n——m ≃ _ := Rel.symm neg_involutive
(-(-(n——m))) ≃ _ := Rel.refl
(-(m——n)) ≃ _ := AA.subst₁ ‹m——n ≃ -1 * coe k›
(-(-1 * coe k)) ≃ _ := AA.subst₁ (Rel.symm AA.scompatL)
(-(-(1 * coe k))) ≃ _ := neg_involutive
1 * coe k ≃ _ := Rel.refl
/--
Every natural number difference is equivalent to exactly one of the following:
* zero;
* a positive natural number;
* the negation of a positive natural number.
**Proof intuition**: This property is equivalent to the trichotomy of order on
the natural number components of differences. Given a difference `n——m`, it is
equal to
* zero when `n ≃ m`;
* a positive natural number when `n > m`;
* the negation of a positive natural number when `n < m`.
The whole proof is just translating from one form of trichotomy into the other.
-/
theorem sign_trichotomy
(a : Difference ℕ) : AA.ExactlyOneOfThree (a ≃ 0) (Positive a) (Negative a)
:= by
revert a; intro (n——m)
show AA.ExactlyOneOfThree (n——m ≃ 0) (Positive (n——m)) (Negative (n——m))
have natOrderTri : AA.ExactlyOneOfThree (n < m) (n ≃ m) (n > m) :=
Natural.trichotomy n m
apply AA.ExactlyOneOfThree.mk
case atLeastOne =>
show AA.OneOfThree (n——m ≃ 0) (Positive (n——m)) (Negative (n——m))
match natOrderTri.atLeastOne with
| AA.OneOfThree.first (_ : n < m) =>
have : Negative (n——m) := neg_diff_lt.mpr ‹n < m›
exact AA.OneOfThree.third ‹Negative (n——m)›
| AA.OneOfThree.second (_ : n ≃ m) =>
have : n——m ≃ 0 := zero_diff_eqv.mpr ‹n ≃ m›
exact AA.OneOfThree.first ‹n——m ≃ 0›
| AA.OneOfThree.third (_ : n > m) =>
have : Positive (n——m) := pos_diff_gt.mpr ‹n > m›
exact AA.OneOfThree.second ‹Positive (n——m)›
case atMostOne =>
intro (h : AA.TwoOfThree (n——m ≃ 0) (Positive (n——m)) (Negative (n——m)))
have twoOfThree : AA.TwoOfThree (n < m) (n ≃ m) (n > m) := match h with
| AA.TwoOfThree.oneAndTwo (_ : n——m ≃ 0) (_ : Positive (n——m)) =>
have : n ≃ m := zero_diff_eqv.mp ‹n——m ≃ 0›
have : n > m := pos_diff_gt.mp ‹Positive (n——m)›
AA.TwoOfThree.twoAndThree ‹n ≃ m› ‹n > m›
| AA.TwoOfThree.oneAndThree (_ : n——m ≃ 0) (_ : Negative (n——m)) =>
have : n < m := neg_diff_lt.mp ‹Negative (n——m)›
have : n ≃ m := zero_diff_eqv.mp ‹n——m ≃ 0›
AA.TwoOfThree.oneAndTwo ‹n < m› ‹n ≃ m›
| AA.TwoOfThree.twoAndThree (_ : Positive (n——m)) (_ : Negative (n——m)) =>
have : n < m := neg_diff_lt.mp ‹Negative (n——m)›
have : n > m := pos_diff_gt.mp ‹Positive (n——m)›
AA.TwoOfThree.oneAndThree ‹n < m› ‹n > m›
show False
have notTwoOfThree : ¬ AA.TwoOfThree (n < m) (n ≃ m) (n > m) :=
natOrderTri.atMostOne
exact absurd twoOfThree notTwoOfThree
/--
Implementation of the
[signum function](https://en.wikipedia.org/wiki/Sign_function) for differences.
**Definition intuition**: For a difference `n——m`, gives the correct sign value
according to the ordering of `n` and `m`.
-/
def sgn : Difference ℕ → Difference ℕ
| n——m => ord_sgn (compare n m)
/--
Zero is the only difference with sign value zero.
**Property intuition**: Zero is neither positive nor negative, so it gets its
own sign value.
**Proof intuition**: All differences with value zero have components that are
equivalent. The `sgn` function evaluates to zero in that case.
-/
theorem sgn_zero {a : Difference ℕ} : a ≃ 0 ↔ sgn a ≃ 0 := by
revert a; intro (n——m)
apply Iff.intro
case mp =>
intro (_ : n——m ≃ 0)
show sgn (n——m) ≃ 0
have : n ≃ m := zero_diff_eqv.mp ‹n——m ≃ 0›
have : compare n m = Ordering.eq := Natural.compare_eq.mpr this
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.eq :=
ord_sgn_subst (ℤ := Difference ℕ) this
have : ord_sgn (compare n m) ≃ 0 := this
have : sgn (n——m) ≃ 0 := this
exact this
case mpr =>
intro (_ : sgn (n——m) ≃ 0)
show n——m ≃ 0
have : ord_sgn (compare n m) ≃ 0 := ‹sgn (n——m) ≃ 0›
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.eq := this
have : compare n m = Ordering.eq := ord_sgn_inject this
have : n ≃ m := Natural.compare_eq.mp this
have : n——m ≃ 0 := zero_diff_eqv.mpr this
exact this
/--
Only positive differences have sign value one.
**Property intuition**: The definition of the `sgn` function is for all, and
only, positive integers to have sign value one.
**Proof intuition**: All positive differences have a first component that's
greater than their second component. The `sgn` function evaluates to one in
that case.
-/
theorem sgn_positive {a : Difference ℕ} : Positive a ↔ sgn a ≃ 1 := by
revert a; intro (n——m)
apply Iff.intro
case mp =>
intro (_ : Positive (n——m))
show sgn (n——m) ≃ 1
have : n > m := pos_diff_gt.mp ‹Positive (n——m)›
have : compare n m = Ordering.gt := Natural.compare_gt.mpr this
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.gt :=
ord_sgn_subst (ℤ := Difference ℕ) this
have : ord_sgn (compare n m) ≃ 1 := this
have : sgn (n——m) ≃ 1 := this
exact this
case mpr =>
intro (_ : sgn (n——m) ≃ 1)
show Positive (n——m)
have : ord_sgn (compare n m) ≃ 1 := ‹sgn (n——m) ≃ 1›
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.gt := this
have : compare n m = Ordering.gt := ord_sgn_inject this
have : n > m := Natural.compare_gt.mp this
have : Positive (n——m) := pos_diff_gt.mpr this
exact this
/--
Only negative differences have sign value negative one.
**Property intuition**: The definition of the `sgn` function is for all, and
only, negative integers to have sign value negative one.
**Proof intuition**: All negative differences have a first component that's
less than their second component. The `sgn` function evaluates to negative one
in that case.
-/
theorem sgn_negative {a : Difference ℕ} : Negative a ↔ sgn a ≃ -1 := by
revert a; intro (n——m)
apply Iff.intro
case mp =>
intro (_ : Negative (n——m))
show sgn (n——m) ≃ -1
have : n < m := neg_diff_lt.mp ‹Negative (n——m)›
have : compare n m = Ordering.lt := Natural.compare_lt.mpr this
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.lt :=
ord_sgn_subst (ℤ := Difference ℕ) this
have : ord_sgn (compare n m) ≃ -1 := this
have : sgn (n——m) ≃ -1 := this
exact this
case mpr =>
intro (_ : sgn (n——m) ≃ -1)
show Negative (n——m)
have : ord_sgn (compare n m) ≃ -1 := ‹sgn (n——m) ≃ -1›
have : ord_sgn (compare n m) ≃ ord_sgn Ordering.lt := this
have : compare n m = Ordering.lt := ord_sgn_inject this
have : n < m := Natural.compare_lt.mp this
have : Negative (n——m) := neg_diff_lt.mpr this
exact this
/--
If two differences have the same sign value, their sum will as well.
**Property intuition**: If we visualize differences as arrows on a number line,
an arrow's length is its magnitude and its direction is its sign. Two positive
or two negative numbers will have their arrows pointing in the same direction;
adding them produces a longer arrow, again pointing in the same direction.
**Proof intuition**: Convert statements about signs of differences into
comparisons of their underlying natural numbers. Use the property that adding
pairs of natural numbers that are ordered in the same way produces a pair with
the same ordering.
-/
theorem add_preserves_sign
{s a b : Difference ℕ} : sgn a ≃ s → sgn b ≃ s → sgn (a + b) ≃ s
:= by
revert a; intro (n——m); revert b; intro (k——j)
intro (_ : sgn (n——m) ≃ s) (_ : sgn (k——j) ≃ s)
show sgn (n——m + k——j) ≃ s
have : ord_sgn (compare n m) ≃ s := ‹sgn (n——m) ≃ s›
have : ord_sgn (compare k j) ≃ s := ‹sgn (k——j) ≃ s›
have : ord_sgn (compare n m) ≃ ord_sgn (compare k j) :=
Rel.trans ‹ord_sgn (compare n m) ≃ s› (Rel.symm this)
have : compare n m = compare k j := ord_sgn_inject this
have : compare (n + k) (m + j) = compare k j :=
Natural.add_preserves_compare this rfl
have : sgn (n——m + k——j) ≃ s := calc
sgn (n——m + k——j) ≃ _ := Rel.refl
sgn ((n + k)——(m + j)) ≃ _ := Rel.refl
ord_sgn (compare (n + k) (m + j)) ≃ _ := ord_sgn_subst this
ord_sgn (compare k j) ≃ _ := ‹ord_sgn (compare k j) ≃ s›
s ≃ _ := Rel.refl
exact this
instance sign_props : Sign.Props (Difference ℕ) := {
positive_iff_sign_pos1 := Generic.positive_iff_sign_pos1
negative_iff_sign_neg1 := Generic.negative_iff_sign_neg1
nonzero_iff_nonzero_impl := Generic.nonzero_iff_nonzero_impl
sign_trichotomy := sign_trichotomy
}
instance sgn_ops : Sgn.Ops (ℤ := Difference ℕ) (Difference ℕ) := {
sgn := sgn
}
instance sgn_props : Sgn.Props (Difference ℕ) := {
sgn_zero := sgn_zero
sgn_positive := sgn_positive
sgn_negative := sgn_negative
add_preserves_sign := add_preserves_sign
}
instance sign : Sign (Difference ℕ) := {
toSignedOps := Generic.signed_ops
toSignProps := sign_props
toSgnOps := sgn_ops
toSgnProps := sgn_props
}
end Lean4Axiomatic.Integer.Impl.Difference
|
State Before: α : Type u
β : α → Type v
inst✝ : DecidableEq α
a a' : α
b : β a
s✝ : Finmap β
s : AList β
⊢ a' ∈ replace a b ⟦s⟧ ↔ a' ∈ ⟦s⟧ State After: no goals Tactic: simp |
(* Authors: Dongchen Jiang and Tobias Nipkow *)
theory Marriage
imports Main
begin
theorem marriage_necessary:
fixes A :: "'a \<Rightarrow> 'b set" and I :: "'a set"
assumes "finite I" and "\<forall> i\<in>I. finite (A i)"
and "\<exists>R. (\<forall>i\<in>I. R i \<in> A i) \<and> inj_on R I" (is "\<exists>R. ?R R A & ?inj R A")
shows "\<forall>J\<subseteq>I. card J \<le> card (UNION J A)"
proof clarify
fix J
assume "J \<subseteq> I"
show "card J \<le> card (UNION J A)"
proof-
from assms(3) obtain R where "?R R A" and "?inj R A" by auto
have "inj_on R J" by(rule subset_inj_on[OF `?inj R A` `J\<subseteq>I`])
moreover have "(R ` J) \<subseteq> (UNION J A)" using `J\<subseteq>I` `?R R A` by auto
moreover have "finite (UNION J A)" using `J\<subseteq>I` assms
by (metis finite_UN_I finite_subset set_mp)
ultimately show ?thesis by (rule card_inj_on_le)
qed
qed
text{* The proof by Halmos and Vaughan: *}
theorem marriage_HV:
fixes A :: "'a \<Rightarrow> 'b set" and I :: "'a set"
assumes "finite I" and "\<forall> i\<in>I. finite (A i)"
and "\<forall>J\<subseteq>I. card J \<le> card (UNION J A)" (is "?M A I")
shows "\<exists>R. (\<forall>i\<in>I. R i \<in> A i) \<and> inj_on R I"
(is "?SDR A I" is "\<exists>R. ?R R A I & ?inj R A I")
proof-
{ fix I
have "finite I \<Longrightarrow> \<forall>i\<in>I. finite (A i) \<Longrightarrow> ?M A I \<Longrightarrow> ?SDR A I"
proof(induct arbitrary: A rule: finite_psubset_induct)
case (psubset I)
show ?case
proof (cases)
assume "I={}" then show ?thesis by simp
next
assume "I \<noteq> {}"
have "\<forall>i\<in>I. A i \<noteq> {}"
proof (rule ccontr)
assume "\<not> (\<forall>i\<in>I. A i\<noteq>{})"
then obtain i where "i\<in>I" "A i = {}" by blast
hence "{i}\<subseteq> I" by auto
from mp[OF spec[OF psubset.prems(2)] this] `A i={}`
show False by simp
qed
show ?thesis
proof cases
assume case1: "\<forall>K\<subset>I. K\<noteq>{} \<longrightarrow> card (UNION K A) \<ge> card K + 1"
show ?thesis
proof-
from `I\<noteq>{}` obtain n where "n\<in>I" by auto
with `\<forall>i\<in>I. A i \<noteq> {}` have "A n \<noteq> {}" by auto
then obtain x where "x \<in> A n" by auto
let ?A' = "\<lambda>i. A i - {x}" let ?I' = "I - {n}"
from `n\<in>I` have "?I' \<subset> I"
by (metis DiffD2 Diff_subset insertI1 psubset_eq)
have fin': "\<forall>i\<in>?I'. finite (?A' i)" using psubset.prems(1) by auto
have "?M ?A' ?I'"
proof clarify
fix J
assume "J \<subseteq> ?I'"
hence "J \<subset> I" by (metis `I - {n} \<subset> I` subset_psubset_trans)
show "card J \<le> card (UNION J ?A')"
proof cases
assume "J = {}" thus ?thesis by auto
next
assume "J \<noteq> {}"
hence "card J + 1 \<le> card(UNION J A)" using case1 `J\<subset>I` by blast
moreover
have "card(UNION J A) - 1 \<le> card(UNION J ?A')" (is "?l \<le> ?r")
proof-
have "finite J" using `J \<subset> I` psubset(1)
by (metis psubset_imp_subset finite_subset)
hence 1: "finite(UNION J A)"
using `\<forall>i\<in>I. finite(A i)` `J\<subset>I` by force
have "?l = card(UNION J A) - card{x}" by simp
also have "\<dots> \<le> card(UNION J A - {x})" using 1
by (metis diff_card_le_card_Diff finite.intros)
also have "UNION J A - {x} = UNION J ?A'" by blast
finally show ?thesis .
qed
ultimately show ?thesis by arith
qed
qed
from psubset(2)[OF `?I'\<subset>I` fin' `?M ?A' ?I'`]
obtain R' where "?R R' ?A' ?I'" "?inj R' ?A' ?I'" by auto
let ?Rx = "R'(n := x)"
have "?R ?Rx A I" using `x\<in>A n` `?R R' ?A' ?I'` by force
have "\<forall>i\<in>?I'. ?Rx i \<noteq> x" using `?R R' ?A' ?I'` by auto
hence "?inj ?Rx A I" using `?inj R' ?A' ?I'`
by(auto simp: inj_on_def)
with `?R ?Rx A I` show ?thesis by auto
qed
next
assume "\<not> (\<forall>K\<subset>I. K\<noteq>{} \<longrightarrow> card (UNION K A) \<ge> card K + 1)"
then obtain K where
"K\<subset>I" "K\<noteq>{}" and c1: "\<not>(card (UNION K A) \<ge> card K + 1)" by auto
with psubset.prems(2) have "card (UNION K A) \<ge> card K" by auto
with c1 have case2: "card (UNION K A)= card K" by auto
from `K\<subset>I` `finite I` have "finite K" by (auto intro:finite_subset)
from psubset.prems `K\<subset>I`
have "\<forall>i\<in>K. finite (A i)" "\<forall>J\<subseteq>K. card J \<le> card(UNION J A)" by auto
from psubset(2)[OF `K\<subset>I` this]
obtain R1 where "?R R1 A K" "?inj R1 A K" by auto
let ?AK = "\<lambda>i. A i - UNION K A" let ?IK = "I - K"
from `K\<noteq>{}` `K\<subset>I` have "?IK\<subset>I" by auto
have "\<forall>i\<in>?IK. finite (?AK i)" using psubset.prems(1) by auto
have "?M ?AK ?IK"
proof clarify
fix J assume "J \<subseteq> ?IK"
with `finite I` have "finite J" by(auto intro: finite_subset)
show "card J \<le> card (UNION J ?AK)"
proof-
from `J\<subseteq>?IK` have "J \<inter> K = {}" by auto
have "card J = card(J\<union>K) - card K"
using `finite J` `finite K` `J\<inter>K={}`
by (auto simp: card_Un_disjoint)
also have "card(J\<union>K) \<le> card(UNION (J\<union>K) A)"
proof -
from `J\<subseteq>?IK` `K\<subset>I` have "J \<union> K \<subseteq> I" by auto
with psubset.prems(2) show ?thesis by blast
qed
also have "\<dots> - card K = card(UNION J ?AK \<union> UNION K A) - card K"
proof-
have "UNION (J\<union>K) A = UNION J ?AK \<union> UNION K A"
using `J\<subseteq>?IK` by auto
thus ?thesis by simp
qed
also have "\<dots> = card(UNION J ?AK) + card(UNION K A) - card K"
proof-
have "finite (UNION J ?AK)" using `finite J` `J\<subseteq>?IK` psubset(3)
by(blast intro: finite_UN_I finite_Diff)
moreover have "finite (UNION K A)"
using `finite K` `\<forall>i\<in>K. finite (A i)` by auto
moreover have "UNION J ?AK \<inter> UNION K A = {}" by auto
ultimately show ?thesis
by (simp add: card_Un_disjoint del:Un_Diff_cancel2)
qed
also have "\<dots> = card(UNION J ?AK)" using case2 by simp
finally show ?thesis by simp
qed
qed
from psubset(2)[OF `?IK\<subset>I` `\<forall>i\<in>?IK. finite (?AK i)` `\<forall>J\<subseteq>?IK. card J\<le>card(UNION J ?AK)`]
obtain R2 where "?R R2 ?AK ?IK" "?inj R2 ?AK ?IK" by auto
let ?R12 = "\<lambda>i. if i\<in>K then R1 i else R2 i"
have "\<forall>i\<in>I. ?R12 i \<in> A i" using `?R R1 A K``?R R2 ?AK ?IK` by auto
moreover have "\<forall>i\<in>I. \<forall>j\<in>I. i\<noteq>j\<longrightarrow>?R12 i \<noteq> ?R12 j"
proof clarify
fix i j assume "i\<in>I" "j\<in>I" "i\<noteq>j" "?R12 i = ?R12 j"
show False
proof-
{ assume "i\<in>K \<and> j\<in>K \<or> i\<notin>K\<and>j\<notin>K"
with `?inj R1 A K` `?inj R2 ?AK ?IK` `?R12 i=?R12 j` `i\<noteq>j` `i\<in>I` `j\<in>I`
have ?thesis by (fastforce simp: inj_on_def)
} moreover
{ assume "i\<in>K \<and> j\<notin>K \<or> i\<notin>K \<and> j\<in>K"
with `?R R1 A K` `?R R2 ?AK ?IK` `?R12 i=?R12 j` `j\<in>I` `i\<in>I`
have ?thesis by auto (metis Diff_iff)
} ultimately show ?thesis by blast
qed
qed
ultimately show ?thesis unfolding inj_on_def by fast
qed
qed
qed
}
with assms `?M A I` show ?thesis by auto
qed
text{* The proof by Rado: *}
theorem marriage_Rado:
fixes A :: "'a \<Rightarrow> 'b set" and I :: "'a set"
assumes "finite I" and "\<forall> i\<in>I. finite (A i)"
and "\<forall>J\<subseteq>I. card J \<le> card (UNION J A)" (is "?M A")
shows "\<exists>R. (\<forall>i\<in>I. R i \<in> A i) \<and> inj_on R I"
(is "?SDR A" is "\<exists>R. ?R R A & ?inj R A")
proof-
{ have "\<forall>i\<in>I. finite (A i) \<Longrightarrow> ?M A \<Longrightarrow> ?SDR A"
proof(induct n == "\<Sum>i\<in>I. card(A i) - 1" arbitrary: A)
case 0
have "\<forall>i\<in>I.\<exists>a. A(i) = {a}"
proof (rule ccontr)
assume "\<not> (\<forall>i\<in>I.\<exists>a. A i = {a})"
then obtain i where i: "i:I" "\<forall>a. A i \<noteq> {a}" by blast
hence "{i}\<subseteq> I" by auto
from "0"(1-2) mp[OF spec[OF "0.prems"(2)] `{i}\<subseteq>I`] `finite I` i
show False by (auto simp: card_le_Suc_iff)
qed
then obtain R where R: "\<forall>i\<in>I. A i = {R i}" by metis
then have "\<forall>i\<in>I. R i \<in> A i" by blast
moreover have "inj_on R I"
proof (auto simp: inj_on_def)
fix x y assume "x \<in> I" "y \<in> I" "R x = R y"
with R spec[OF "0.prems"(2), of "{x,y}"] show "x=y"
by (simp add:le_Suc_eq card_insert_if split: if_splits)
qed
ultimately show ?case by blast
next
case (Suc n)
from Suc.hyps(2)[symmetric, THEN setsum_SucD]
obtain i where i: "i:I" "2 \<le> card(A i)" by auto
then obtain x1 x2 where "x1 : A i" "x2 : A i" "x1 \<noteq> x2"
using Suc(3) by (fastforce simp: card_le_Suc_iff eval_nat_numeral)
let "?Ai x" = "A i - {x}" let "?A x" = "A(i:=?Ai x)"
let "?U J" = "UNION J A" let "?Ui J x" = "?U J \<union> ?Ai x"
have n1: "n = (\<Sum>j\<in>I. card (?A x1 j) - 1)"
using Suc.hyps(2) Suc.prems(1) i `finite I` `x1:A i`
by (auto simp: setsum.remove card_Diff_singleton)
have n2: "n = (\<Sum>j\<in>I. card (?A x2 j) - 1)"
using Suc.hyps(2) Suc.prems(1) i `finite I` `x2:A i`
by (auto simp: setsum.remove card_Diff_singleton)
have finx1: "\<forall>j\<in>I. finite (?A x1 j)" by (simp add: Suc(3))
have finx2: "\<forall>j\<in>I. finite (?A x2 j)" by (simp add: Suc(3))
{ fix x assume "\<not> ?M (A(i:= ?Ai x))"
with Suc.prems(2) obtain J
where J: "J \<subseteq> I" "card J > card(UNION J (A(i:= ?Ai x)))"
by (auto simp add:not_less_eq_eq Suc_le_eq)
note fJi = finite_Diff[OF finite_subset[OF `J\<subseteq>I` `finite I`], of "{i}"]
have fU: "finite(?U (J-{i}))" using `J\<subseteq>I`
by (metis Diff_iff Suc(3) finite_UN[OF fJi] subsetD)
have "i \<in> J" using J Suc.prems(2)
by (simp_all add: UNION_fun_upd not_le[symmetric] del: fun_upd_apply split: if_splits)
hence "card(J-{i}) \<ge> card(?Ui (J-{i}) x)"
using fJi J by(simp add: UNION_fun_upd del: fun_upd_apply)
hence "\<exists>J\<subseteq>I. i \<notin> J \<and> card(J) \<ge> card(?Ui J x) \<and> finite(?U J)"
by (metis DiffD2 J(1) fU `i \<in> J` insertI1 subset_insertI2 subset_insert_iff)
} note lem = this
have "?M (?A x1) \<or> ?M (?A x2)" -- "Rado's Lemma"
proof(rule ccontr)
assume "\<not> (?M (?A x1) \<or> ?M (?A x2))"
with lem obtain J1 J2 where
J1: "J1\<subseteq>I" "i\<notin>J1" "card J1 \<ge> card(?Ui J1 x1)" "finite(?U J1)" and
J2: "J2\<subseteq>I" "i\<notin>J2" "card J2 \<ge> card(?Ui J2 x2)" "finite(?U J2)"
by metis
note fin1 = finite_subset[OF `J1\<subseteq>I` assms(1)]
note fin2 = finite_subset[OF `J2\<subseteq>I` assms(1)]
have finUi1: "finite(?Ui J1 x1)" using Suc(3) by(blast intro: J1(4) i(1))
have finUi2: "finite(?Ui J2 x2)" using Suc(3) by(blast intro: J2(4) i(1))
have "card J1 + card J2 + 1 = card(J1 \<union> J2) + 1 + card(J1 \<inter> J2)"
by simp (metis card_Un_Int fin1 fin2)
also have "card(J1 \<union> J2) + 1 = card(insert i (J1 \<union> J2))"
using `i\<notin>J1` `i\<notin>J2` fin1 fin2 by simp
also have "\<dots> \<le> card(UNION (insert i (J1 \<union> J2)) A)" (is "_ \<le> card ?M")
by (metis J1(1) J2(1) Suc(4) Un_least i(1) insert_subset)
also have "?M = ?Ui J1 x1 \<union> ?Ui J2 x2" using `x1\<noteq>x2` by auto
also have "card(J1 \<inter> J2) \<le> card(UNION (J1 \<inter> J2) A)"
by (metis J2(1) Suc(4) le_infI2)
also have "\<dots> \<le> card(?U J1 \<inter> ?U J2)" by(blast intro: card_mono J1(4))
also have "\<dots> \<le> card(?Ui J1 x1 \<inter> ?Ui J2 x2)"
using Suc(3) `i\<in>I` by(blast intro: card_mono J1(4))
finally show False using J1(3) J2(3)
by(auto simp add: card_Un_Int[symmetric, OF finUi1 finUi2])
qed
thus ?case using Suc.hyps(1)[OF n1 finx1] Suc.hyps(1)[OF n2 finx2]
by (metis DiffD1 fun_upd_def)
qed
} with assms `?M A` show ?thesis by auto
qed
end |
module Verifier where
open import Definitions
open import DeMorgan using (deMorgan)
check : {A B : Set} → ¬ A ∧ ¬ B → ¬ (A ∨ B)
check = deMorgan
|
{-# OPTIONS --without-K #-}
open import level
open import algebra.group.core
open import algebra.monoid.mset
open import algebra.monoid.morphism
open import function.extensionality
open import function.isomorphism
open import equality.calculus
open import equality.core
open import sum
open import hott.level
open import hott.equivalence
open import hott.univalence
module algebra.group.gset {i}(G : Set i) ⦃ gG : IsGroup G ⦄ where
open IsGroup ⦃ ... ⦄
IsGSet : ∀ {j}(X : Set j) → Set (i ⊔ j)
IsGSet X = IsMSet G X
GSet : ∀ j → Set (i ⊔ lsuc j)
GSet j = Σ (Set j) IsGSet
GSet₀ : ∀ j → Set (i ⊔ lsuc j)
GSet₀ j = Σ (Type j 2) λ { (X , hX) → G → X → X }
GSet₁ : ∀ {j} → GSet₀ j → Set (i ⊔ j)
GSet₁ ((X , _) , _◂_) =
((g₁ g₂ : G)(x : X) → (g₁ * g₂) ◂ x ≡ g₁ ◂ (g₂ ◂ x))
× ((x : X) → e ◂ x ≡ x)
gset₁-level : ∀ {j}(X : GSet₀ j)
→ h 1 (GSet₁ X)
gset₁-level ((X , hX) , act) = ×-level
(Π-level λ g₁ → Π-level λ g₂ → Π-level λ x → hX _ _)
(Π-level λ x → hX _ _)
gset-struct-iso : ∀ {j} → GSet j ≅ Σ (GSet₀ j) GSet₁
gset-struct-iso = record
{ to = λ { (X , xG) → (((X , IsMSet.mset-level xG) , IsMSet._◂_ xG) ,
(IsMSet.◂-hom xG , IsMSet.◂-id xG)) }
; from = λ { (((X , hX) , _◂_) , (◂-hom , ◂-id))
→ (X , mk-is-mset _◂_ ◂-hom ◂-id hX) }
; iso₁ = λ _ → refl
; iso₂ = λ _ → refl }
open IsMSet ⦃ ... ⦄
module _ {j k}
{X : Set j} ⦃ xG : IsGSet X ⦄
{Y : Set k} ⦃ yG : IsGSet Y ⦄ where
IsGSetMorphism : (X → Y) → Set (i ⊔ j ⊔ k)
IsGSetMorphism = IsMSetMorphism G
module _ {j k}
(X : Set j) ⦃ xG : IsGSet X ⦄
(Y : Set k) ⦃ yG : IsGSet Y ⦄ where
GSetMorphism : Set (i ⊔ j ⊔ k)
GSetMorphism = Σ (X → Y) IsGSetMorphism
gsetmorphism-equality : h 2 Y → {f g : X → Y}
(f-mor : IsGSetMorphism f) (g-mor : IsGSetMorphism g)
→ f ≡ g
→ _≡_ {A = GSetMorphism}
(f , f-mor)
(g , g-mor)
gsetmorphism-equality hY {f} f-mor g-mor refl =
ap (λ m → (f , m)) (h1⇒prop (is-mset-morphism-level G hY f) _ _)
module _ {j} (X : Set j) ⦃ xG : IsGSet X ⦄
(Y : Set j) ⦃ yG : IsGSet Y ⦄ where
𝑋 𝑌 : GSet j
𝑋 = (X , xG)
𝑌 = (Y , yG)
X₀ Y₀ : GSet₀ j
X₀ = ((X , IsMSet.mset-level xG) , _◂_)
Y₀ = ((Y , IsMSet.mset-level yG) , _◂_)
GSet-univalence : (𝑋 ≡ 𝑌)
≅ (Σ (GSetMorphism X Y) λ { (f , _) → weak-equiv f })
GSet-univalence = begin
(𝑋 ≡ 𝑌)
≅⟨ iso≡ gset-struct-iso ·≅ sym≅ (subtype-equality gset₁-level) ⟩
(X₀ ≡ Y₀)
≅⟨ sym≅ Σ-split-iso ⟩
( Σ (proj₁ X₀ ≡ proj₁ Y₀) λ p →
subst (λ { (X , _) → G → X → X }) p (proj₂ X₀) ≡ proj₂ Y₀ )
≅⟨ ( Σ-ap-iso (sym≅ (subtype-equality λ X → hn-h1 2 X)) λ p
→ trans≡-iso (sym (subst-naturality (λ X → G → X → X)
proj₁ p (proj₂ X₀)))) ⟩
( Σ (X ≡ Y) λ p → subst (λ X → G → X → X) p (proj₂ X₀) ≡ proj₂ Y₀ )
≅⟨ Σ-ap-iso refl≅ (λ p → sym≅ (lem₁ p _ _)) ⟩
( Σ (X ≡ Y) λ p → ∀ g w → coerce p (proj₂ X₀ g w)
≡ proj₂ Y₀ g (coerce p w) )
≅⟨ ( Σ-ap-iso uni-iso λ p → refl≅ ) ⟩
( Σ (X ≈ Y) λ f → ∀ g w → apply≈ f (proj₂ X₀ g w)
≡ proj₂ Y₀ g (apply≈ f w))
≅⟨ record
{ to = λ { ((f , we), mor) → ((f , mor) , we) }
; from = λ { ((f , mor) , we) → ((f , we) , mor) }
; iso₁ = λ _ → refl
; iso₂ = λ _ → refl } ⟩
(Σ (GSetMorphism X Y) λ { (f , _) → weak-equiv f })
∎
where
open ≅-Reasoning
lem₁ : {U V : Set j}(p : U ≡ V)
→ (act : G → U → U)
→ (act' : G → V → V)
→ (∀ g u → coerce p (act g u) ≡ act' g (coerce p u))
≅ (subst (λ { X → G → X → X }) p act ≡ act')
lem₁ refl act act' = (Π-ap-iso refl≅ λ g → strong-funext-iso)
·≅ strong-funext-iso
instance
GisGSet : IsGSet G
GisGSet = record
{ _◂_ = _*_
; ◂-hom = assoc
; ◂-id = lunit
; mset-level = is-set }
module _ {j} {X : Set j} (hX : h 2 X) ⦃ xG : IsGSet X ⦄ where
GSet-repr : (ϕ : G → X) → IsGSetMorphism ϕ
→ (g : G) → ϕ g ≡ g ◂ ϕ e
GSet-repr ϕ ϕ-mor g = ap ϕ (sym (runit g)) · ϕ-mor g e
GSet-repr-iso : GSetMorphism G X ≅ X
GSet-repr-iso = iso f g α β
where
f : GSetMorphism G X → X
f (ϕ , _) = ϕ e
g : X → GSetMorphism G X
g x = (ϕ , ϕ-mor)
where
ϕ : G → X
ϕ g = g ◂ x
ϕ-mor : IsGSetMorphism ϕ
ϕ-mor g₁ g₂ = ◂-hom g₁ g₂ x
α : (ϕ : GSetMorphism G X) → g (f ϕ) ≡ ϕ
α (ϕ , ϕ-mor) = gsetmorphism-equality G X hX _ _
(funext λ g → sym (GSet-repr ϕ ϕ-mor g))
β : (x : X) → f (g x) ≡ x
β x = (IsMSet.◂-id xG) x
|
Require Import ssreflect Arith.
Require Import Arith.EqNat.
Require Import Arith.Compare_dec.
Require Import List.
Require Import Omega.
Require Import untypedLambda.
Set Printing Universes.
(*Krivine Abstract Machine*)
(*Syntax*)
Inductive inst :=
| Access: nat -> inst
| Grab: inst
| Push: code -> inst
with code: Type :=
| cnil: code
| cCons: inst -> code -> code.
Inductive environment : Type :=
| nul: environment
| cons: code -> environment -> environment -> environment.
Definition state := prod (prod code environment) environment.
Check inst->code.
Check Set.
Check code.
Check Set -> Type.
Check environment.
Check environment_ind.
Check prod_curry cons (cnil,nul) nul.
(*Semantics*)
Fixpoint exec_inst (s: state): state:=
match s with
| (cCons (Access 0) c, cons c0 e0 e, stack) => (c0, e0, stack)
| (cCons (Access n) c, cons c0 e0 e, stack) => (cCons (Access (n-1)) c, e, stack)
| (cCons (Push c) c0, e, stack) => (c0, e, cons c e stack)
| (cCons Grab c, e, cons c0 e0 stack) => (c, cons c0 e0 e, stack)
| s => s
end.
(*Compiling*)
Fixpoint compile (t: term): code :=
match t with
| Var n => cCons (Access n) cnil
| Lambda t1 => cCons Grab (compile t1)
| App t1 t2 => cCons (Push (compile t2)) (compile t1)
end.
Fixpoint tau_code (c: code): term :=
match c with
| cnil => Var 0
| (cCons (Access n) _ ) => Var n
| (cCons (Push c1) c0) => App (tau_code c0) (tau_code c1)
| (cCons Grab c0) => Lambda (tau_code c0)
end.
Check multiple_substitution.
Fixpoint tau_env (e: environment): list term :=
match e with
| nul => nil
| cons c0 e0 e1 =>
(multiple_substitution 0 (tau_code c0) (tau_env e0)) :: tau_env e1
end.
Check state.
Fixpoint transform_stk (stk: environment): list term :=
match stk with
| cons c0 e0 nul => multiple_substitution 0 (tau_code c0) (tau_env e0) :: nil
| cons c0 e0 e1 => (multiple_substitution 0 (tau_code c0) (tau_env e0) :: (transform_stk e1))
| nul => nil
end.
Check fold_left.
Fixpoint tau (s: state): term :=
match s with
| (c, e, stk) =>
match stk with
| nul => multiple_substitution 0 (tau_code c) (tau_env e)
| stk => fold_left (fun t1 t2 => App t1 t2) (transform_stk stk) (multiple_substitution 0 (tau_code c) (tau_env e))
end
end.
(*Compiling results*)
Lemma tau_nil_env: forall t: term, tau (compile t, nul, nul) = tau_code (compile t).
Proof.
induction t.
simpl.
have: beq_nat v v = true.
apply beq_nat_true_iff.
reflexivity.
intro h0.
rewrite h0.
rewrite -minus_n_O.
have: leb v 0 = false \/ leb v 0 = true.
apply dic.
intro h1.
case:h1.
intro h1.
rewrite h1.
trivial.
intro h1.
rewrite h1.
move:h1.
case v.
done.
done.
simpl.
rewrite -lambda_equivalence.
apply id_substitution.
simpl.
rewrite app_equivalence.
split.
apply id_substitution.
apply id_substitution.
Qed.
Theorem invert_comp: forall (t: term), tau (compile t, nul, nul) = t.
Proof.
induction t.
simpl.
have: beq_nat v v = true.
apply beq_nat_true_iff.
reflexivity.
intro h0.
rewrite h0.
rewrite -minus_n_O.
have: leb v 0 = false \/ leb v 0 = true.
apply dic.
intro h1.
case:h1.
intro h1.
rewrite h1.
trivial.
intro h1.
rewrite h1.
move:h1.
case v.
done.
done.
simpl.
rewrite -lambda_equivalence.
rewrite tau_nil_env in IHt.
rewrite IHt.
apply id_substitution.
simpl.
rewrite app_equivalence.
rewrite tau_nil_env in IHt1.
rewrite tau_nil_env in IHt2.
split.
rewrite IHt1.
apply id_substitution.
rewrite IHt2.
apply id_substitution.
Qed.
(*Correct state*)
Fixpoint length (e: environment): nat :=
match e with
| nul => 0
| cons c0 e0 e1 => 1 + (length e1)
end.
Lemma length_inv: forall e:environment, length e = Datatypes.length (tau_env e).
Proof.
intros.
induction e.
done.
simpl.
omega.
Qed.
Inductive correct_stk : environment -> Prop :=
|Corr_stk_nul: correct_stk nul
|Corr_stk: forall (e e0:environment) (c0:code), (C (length e0) (tau_code c0)) -> correct_stk e0 ->
correct_stk e -> correct_stk (cons c0 e0 e).
Fixpoint corr_stk (stk: environment): Prop:=
match stk with
| nul => True
| cons c0 e0 e => ((correct_stk e0) /\ (correct_stk e) /\ (C (length e0) (tau_code c0)))
end.
Inductive correc_state: state -> Prop:=
|Corr_state: forall (c:code) (e stk:environment), (correct_stk e) -> (correct_stk stk) -> (C (length e) (tau_code c)) -> correc_state (c,e,stk).
Fixpoint correct_state (s:state):Prop:=
match s with
| (c, e, stk) => (correct_stk e) /\ (correct_stk stk) /\ (C (length e) (tau_code c))
end.
Definition c_list_i (i:nat) (lu: list term) : Prop :=
forall k: nat, k < Datatypes.length lu -> C i (nth k lu (Var 0)).
Fixpoint closed_list (i:nat) (lu: list term): Prop :=
match lu with
| nil => True
| x :: xs => C i x /\ closed_list i xs
end.
Lemma closed_list_eq: forall (lu: list term) (i: nat), closed_list i lu <-> c_list_i i lu.
Proof.
induction lu.
simpl.
unfold c_list_i.
split.
simpl.
intros.
omega.
trivial.
simpl.
split.
intros.
unfold c_list_i.
intro.
case k.
simpl.
intros.
tauto.
simpl.
intros.
apply IHlu.
tauto.
omega.
intro.
split.
unfold c_list_i in H.
apply (H 0).
simpl.
omega.
apply IHlu.
unfold c_list_i.
intro.
case k.
intro.
apply (H 1).
simpl.
omega.
intros.
apply (H (S (S n))).
simpl.
omega.
Qed.
Lemma lift_len_inv: forall (lu: list term) (i k: nat), Datatypes.length lu = Datatypes.length (lift_all i k lu).
Proof.
admit.
Qed.
Lemma list_lift_free: forall (lu : list term) (i k : nat), c_list_i i lu -> c_list_i (i + 1) (lift_all 1 k lu).
Proof.
admit.
Qed.
Lemma mult_sub_clos: forall (t: term) (u: list term) (i: nat), closed_list i u -> C (i+Datatypes.length u) t -> C i (multiple_substitution i t u).
Proof.
induction t.
simpl.
intros.
have: beq_nat v v = true.
apply beq_nat_true_iff.
done.
intro.
rewrite x.
have:leb v (i + Datatypes.length u - 1) = true.
apply leb_iff.
omega.
intro.
rewrite x0.
rewrite Bool.andb_true_r.
have:leb i v = false \/ leb i v = true.
apply dic.
intro.
case x1.
intro.
rewrite H1.
simpl.
apply leb_iff_conv in H1.
trivial.
intro.
rewrite H1.
apply leb_iff in x0.
apply leb_iff in H1.
apply closed_list_eq in H.
unfold c_list_i in H.
apply H.
omega.
simpl.
intros.
apply (IHt (lift_all 1 0 u) (i+1)).
apply closed_list_eq.
apply closed_list_eq in H.
apply list_lift_free.
done.
rewrite -(lift_len_inv _ 1 0).
have: i + Datatypes.length u + 1 = i + 1 + Datatypes.length u.
omega.
intro.
rewrite -x.
trivial.
simpl.
intros.
split.
apply IHt1.
done.
tauto.
apply IHt2.
done.
tauto.
Qed.
(*Lemma mult_sub_clos: forall (t: term) (u: list term) (i: nat), c_list_i i u -> C (i+Datatypes.length u) t -> C i (multiple_substitution t u i (Datatypes.length u)).
Proof.
induction t.
simpl.
intros.
have: beq_nat v v = true.
apply beq_nat_true_iff.
done.
intro.
rewrite x.
have:leb v (i + Datatypes.length u - 1) = true.
apply leb_iff.
omega.
intro.
rewrite x0.
rewrite Bool.andb_true_r.
have:leb i v = false \/ leb i v = true.
apply dic.
intro.
case x1.
intro.
rewrite H1.
simpl.
apply leb_iff_conv in H1.
trivial.
intro.
rewrite H1.
apply H.
apply leb_iff in H1.
omega.
simpl.
intros.
rewrite (lift_len_inv _ 1 0).
apply (IHt (lift_all 1 0 u) (i+1)).
apply list_lift_free.
done.
rewrite -(lift_len_inv _ 1 0).
have: i + Datatypes.length u + 1 = i + 1 + Datatypes.length u.
omega.
intro.
rewrite -x.
trivial.
simpl.
intros.
split.
apply IHt1.
done.
tauto.
apply IHt2.
done.
tauto.
Qed.*)
Lemma closed_env: forall e:environment, correct_stk e -> closed_list 0 (tau_env e).
Proof.
induction e.
simpl.
trivial.
intros.
inversion H.
simpl.
split.
apply mult_sub_clos.
apply IHe1.
trivial.
simpl.
rewrite -length_inv.
trivial.
apply IHe2.
trivial.
Qed.
Theorem transition_inv_1: forall (c c0: code) (e e0 stack: environment),
correct_state ((cCons (Access 0) c, cons c0 e0 e, stack)) -> correct_state (c0, e0, stack).
Proof.
simpl.
intros.
destruct H.
inversion H.
tauto.
Qed.
Theorem transition_inv_2: forall (c c0: code) (e e0 stack: environment) (n: nat), (n > 0) -> correct_state (cCons (Access n) c, cons c0 e0 e, stack) -> correct_state (cCons (Access (n-1)) c, e, stack).
Proof.
simpl.
intros.
destruct H0.
destruct H1.
inversion H0.
split.
trivial.
split.
trivial.
omega.
Qed.
Theorem transition_inv_3: forall (c c0: code) (e stack: environment), correct_state (cCons (Push c) c0, e, stack) -> correct_state (c0, e, cons c e stack).
Proof.
simpl.
intros.
destruct H.
destruct H0.
destruct H1.
split.
trivial.
split.
apply Corr_stk.
trivial.
trivial.
trivial.
trivial.
Qed.
Theorem transition_inv_4: forall (c c0: code) (e e0 stack: environment),
correct_state (cCons Grab c, e, cons c0 e0 stack) -> correct_state (c, cons c0 e0 e, stack).
Proof.
simpl.
intros.
destruct H as [H0 [H1 H2]].
inversion H1.
split.
apply Corr_stk.
trivial.
trivial.
trivial.
split.
trivial.
rewrite plus_comm in H2.
trivial.
Qed.
Theorem correct_invariance: forall s: state, correct_state s -> correct_state (exec_inst s).
Proof.
intro.
destruct s.
destruct p.
move: e e0.
induction c.
trivial.
case i.
intros n e e0.
case e0.
case n.
trivial.
trivial.
intros p e1.
unfold exec_inst.
case n.
intro.
Search "transition_inv_1".
apply transition_inv_1.
intros n0 e2.
apply transition_inv_2.
omega.
unfold exec_inst.
intros e e0.
case e.
trivial.
intros c0 e1 e2.
apply transition_inv_4.
intros c0 e e0.
apply transition_inv_3.
Qed.
Lemma correct_reduction_1: forall (c c0: code) (e s: environment), correct_state (cCons (Push c0) c,e,s) -> reduces (tau (cCons (Push c0) c,e,s)) (tau (c, e, cons c0 e s)).
Proof.
intros.
simpl.
case s.
simpl.
apply sym.
intros.
simpl in H.
simpl.
apply sym.
Qed.
Lemma correct_reduction_2: forall (c c0: code) (e e0 s: environment),
correct_state ((cCons (Access 0) c, cons c0 e0 e, s)) -> reduces (tau (cCons (Access 0) c, cons c0 e0 e, s)) (tau (c0, e0, s)).
Proof.
simpl.
intros.
case s.
apply sym.
intros.
apply sym.
Qed.
Lemma correct_reduction_3: forall (c c0: code) (e e0 s: environment) (n: nat), (n > 0) -> correct_state (cCons (Access n) c, cons c0 e0 e, s) -> reduces (tau (cCons (Access n) c, cons c0 e0 e, s)) (tau (exec_inst (cCons (Access n) c, cons c0 e0 e, s))).
Proof.
intros.
unfold exec_inst.
move:H H0.
case n.
intros.
omega.
intros.
inversion H0.
move : H0.
case s.
case e.
simpl.
intros.
destruct H0.
destruct H1.
omega.
intros.
destruct H3.
omega.
unfold tau.
rewrite NPeano.Nat.sub_succ.
rewrite -minus_n_O.
unfold tau_code.
intros.
simpl in H0.
destruct H0 as [h1 [h2 h3]].
have: closed_list 0 (tau_env (cons c0 e0 (cons c1 e1 e2))).
apply closed_env.
trivial.
intro.
unfold tau_env.
case n0.
simpl.
apply sym.
intros.
simpl.
rewrite mult_sub_clos.
simpl in H0.
destruct H0 as [[h1 [h2 h3]] [h4 h5]].
have: n0 <= length e - 1.
omega.
intro.
rewrite ?plus_O_n.
have: S n0 <= length (cons (c0,e0) e) - 1.
simpl.
omega.
intro.
apply leb_iff in x.
rewrite ?x.
apply leb_iff in x0.
rewrite x0.
have: 0 <= n0.
omega.
intro.
apply leb_iff in x1.
rewrite x1.
Search "andb".
have: 0 <= S n0.
omega.
intro.
apply leb_iff in x2.
rewrite x2.
simpl.
rewrite ?h0.
rewrite -minus_n_O.
apply sym.
Qed.
Lemma correct_reduction_4: forall (c c0: code) (e e0 s: environment), correct_state (cCons Grab c, e, cons (c0,e0) s) -> reduces (tau (cCons Grab c, e, cons (c0,e0) s)) (tau (c, cons (c0,e0) e, s)).
Proof.
intros.
simpl in H.
destruct H as [h0 [h1 h2]].
destruct h1.
destruct H0.
case s.
unfold tau.
unfold transform_stk.
unfold fold_left.
unfold tau_code.
fold tau_code.
simpl.
apply (ind _ (substitution 0 (multiple_substitution 1 (tau_code c) (lift_all 1 0 (tau_env e)))
(multiple_substitution 0 (tau_code c0) (tau_env e0))) _).
apply removeLamb.
rewrite mult_sub_inv.
rewrite -?length_inv.
simpl.
unfold correct_stk in h0.
induction e.
simpl.
intros.
admit.
admit.
admit.
admit.
Qed.
Theorem correct_confluence: forall s: state, correct_state s -> reduces (tau s) (tau (exec_inst s)).
Proof.
intro s.
destruct s as ((c, e), s).
move: e s.
induction c.
intros.
apply sym.
case i.
intros n e s.
case n.
intros.
unfold exec_inst.
move:H.
case e.
intro.
apply sym.
intros.
rewrite (surjective_pairing p).
apply correct_reduction_2.
rewrite -(surjective_pairing p).
done.
case e.
intros.
unfold exec_inst.
apply sym.
intros p e0 n0.
rewrite (surjective_pairing p).
intro.
apply correct_reduction_3.
omega.
done.
unfold exec_inst.
intros.
move:H.
case s.
intro.
apply sym.
intros.
rewrite (surjective_pairing p).
apply correct_reduction_4.
rewrite -(surjective_pairing p).
done.
unfold exec_inst.
intros.
apply correct_reduction_1.
done.
Qed.
(*Unify every transition*)
|
import plotly.express as px
import pandas as pd
import requests
import networkx as nx
G = nx.read_graphml('METABOLOMICS-SNETS-V2-1ad7bc36-download_cytoscape_data-main.graphml')
df ={"cosine_score":[]}
for edge in G.edges(data = True):
df["cosine_score"].append(edge[2]["cosine_score"])
fig = px.histogram(df,x= "cosine_score")
fig.show()
|
function [ymax, yu, xpos, xu] = max(s)
%tstoolbox/@signal/max
% Syntax:
% * [maximum, yunit, xpos, xunit] = max(s)
%
% Give information about maximum of scalar signal s.
%
% Example:
%disp('maximum of signal : ')
%disp(['y = ' num2str(m) ' ' label(yunit(s))]);
%disp(['x = ' num2str(xpos) ' ' label(a)]);
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt
narginchk(1,1);
if ndim(s) ~= 1
help(mfilename)
return
end
[m, ind] = max(data(s));
a = getaxis(s, 1);
xpos = first(a) + delta(a) * (ind-1); % determine position of maximum
% disp('maximum of signal : ')
% disp(['y = ' num2str(m) ' ' label(yunit(s))]);
% disp(['x = ' num2str(xpos) ' ' label(a)]);
xu = unit(a);
yu = yunit(s);
ymax = m;
|
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <SofaConstraint/LMConstraintDirectSolver.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaConstraint/ContactDescription.h>
#include <sofa/core/ObjectFactory.h>
#include <Eigen/QR>
#include <Eigen/SVD>
namespace sofa
{
namespace component
{
namespace constraintset
{
LMConstraintDirectSolver::LMConstraintDirectSolver()
: solverAlgorithm(initData(&solverAlgorithm, "solverAlgorithm", "Algorithm used to solve the system W.Lambda=c"))
{
//Add here other algo
sofa::helper::OptionsGroup algo(1,"SVD");
solverAlgorithm.setValue(algo);
}
bool LMConstraintDirectSolver::buildSystem(const core::ConstraintParams* cParams, MultiVecId res1, MultiVecId res2)
{
bool sucess = LMConstraintSolver::buildSystem(cParams, res1, res2);
return sucess;
}
bool LMConstraintDirectSolver::solveSystem(const core::ConstraintParams* cParams, MultiVecId res1, MultiVecId res2)
{
//First, do n iterations of Gauss Seidel
bool success = LMConstraintSolver::solveSystem(cParams, res1, res2);
if (cParams->constOrder() != core::ConstraintParams::VEL) return success;
//Then process to a direct solution of the system
//We need to find all the constraint related to contact
// 1. extract the information about the state of the contact and build the new L, L^T matrices
// 2. build the full system
// 3. solve
//------------------------------------------------------------------
// extract the information about the state of the contact
//------------------------------------------------------------------
//************************************************************
#ifdef SOFA_DUMP_VISITOR_INFO
sofa::simulation::Visitor::printNode("AnalyseConstraints");
#endif
const helper::vector< sofa::core::behavior::BaseLMConstraint* > &LMConstraints=LMConstraintVisitor.getConstraints();
JacobianRows rowsL ; rowsL.reserve(numConstraint);
JacobianRows rowsLT; rowsLT.reserve(numConstraint);
helper::vector< unsigned int > rightHandElements;
analyseConstraints(LMConstraints, cParams->constOrder(),
rowsL, rowsLT, rightHandElements);
#ifdef SOFA_DUMP_VISITOR_INFO
sofa::simulation::Visitor::printCloseNode("AnalyseConstraints");
#endif
if (rowsL.empty() || rowsLT.empty()) return success;
#ifdef SOFA_DUMP_VISITOR_INFO
sofa::simulation::Visitor::printNode("BuildFullSystem");
#endif
//------------------------------------------------------------------
// build c: right hand term
//------------------------------------------------------------------
VectorEigen previousC(c);
//TODO: change newC by c
c=VectorEigen::Zero(rowsL.size());
unsigned int idx=0;
for (helper::vector<unsigned int >::const_iterator it=rightHandElements.begin(); it!=rightHandElements.end(); ++it)
c[idx++]=previousC[*it];
//------------------------------------------------------------------
// build the L and LT matrices
//------------------------------------------------------------------
DofToMatrix LMatricesDirectSolver;
DofToMatrix LTMatricesDirectSolver;
for (DofToMatrix::iterator it=LMatrices.begin(); it!=LMatrices.end(); ++it)
{
//------------------------------------------------------------------
const SparseMatrixEigen& matrix= it->second;
//Init the manipulator with the full matrix
linearsolver::LMatrixManipulator manip;
manip.init(matrix);
//------------------------------------------------------------------
SparseMatrixEigen L (rowsL.size(), matrix.cols());
L.reserve(rowsL.size()*matrix.cols());
manip.buildLMatrix(rowsL ,L);
L.finalize();
LMatricesDirectSolver.insert (std::make_pair(it->first,L ));
//------------------------------------------------------------------
SparseMatrixEigen LT(rowsLT.size(), matrix.cols());
LT.reserve(rowsLT.size()*matrix.cols());
manip.buildLMatrix(rowsLT,LT);
LT.finalize();
LTMatricesDirectSolver.insert(std::make_pair(it->first,LT));
}
//------------------------------------------------------------------
// build the full system
//------------------------------------------------------------------
const int rows=rowsL.size();
const int cols=rowsLT.size();
SparseColMajorMatrixEigen Wsparse(rows,cols);
buildLeftRectangularMatrix(invMassMatrix, LMatricesDirectSolver, LTMatricesDirectSolver, Wsparse,invMass_Ltrans);
//------------------------------------------------------------------
// conversion from sparse to dense matrix
//------------------------------------------------------------------
Lambda=VectorEigen::Zero(rows);
W=MatrixEigen::Zero(rows,cols);
SparseMatrixEigen Wresult(Wsparse);
for (int k=0; k<Wresult.outerSize(); ++k)
for (SparseMatrixEigen::InnerIterator it(Wresult,k); it; ++it) W(it.row(),it.col()) = it.value();
#ifdef SOFA_DUMP_VISITOR_INFO
sofa::simulation::Visitor::printCloseNode("BuildFullSystem");
#endif
//------------------------------------------------------------------
// Solve the system
//------------------------------------------------------------------
const std::string &algo=solverAlgorithm.getValue().getSelectedItem() ;
#ifdef SOFA_DUMP_VISITOR_INFO
simulation::Visitor::TRACE_ARGUMENT arg1;
arg1.push_back(std::make_pair("Algorithm", algo));
arg1.push_back(std::make_pair("Dimension", printDimension(W)));
sofa::simulation::Visitor::printNode("DirectSolveSystem", "",arg1);
#endif
if(algo == "SVD")
{
Eigen::JacobiSVD< MatrixEigen > solverSVD(W);
VectorEigen invSingularValues(solverSVD.singularValues());
for (int i=0; i<invSingularValues.size(); ++i)
{
if (invSingularValues[i] < 1e-10) invSingularValues[i]=0;
else invSingularValues[i]=1/invSingularValues[i];
}
Lambda.noalias() = solverSVD.matrixV()*invSingularValues.asDiagonal()*solverSVD.matrixU().transpose()*c;
}
if (this->f_printLog.getValue())
{
sout << "W" << printDimension(W) << " Lambda" << printDimension(Lambda) << " c" << printDimension(c) << sendl;
sout << "\nW ===============================================\n" << W
<< "\nLambda===============================================\n" << Lambda
<< "\nc ===============================================\n" << c << sendl;
}
#ifdef SOFA_DUMP_VISITOR_INFO
sofa::simulation::Visitor::printCloseNode("DirectSolveSystem");
#endif
return success;
}
void LMConstraintDirectSolver::analyseConstraints(const helper::vector< sofa::core::behavior::BaseLMConstraint* > &LMConstraints, core::ConstraintParams::ConstOrder order,
JacobianRows &rowsL,JacobianRows &rowsLT, helper::vector< unsigned int > &rightHandElements) const
{
//Iterate among all the Sofa LMConstraint
for (unsigned int componentConstraint=0; componentConstraint<LMConstraints.size(); ++componentConstraint)
{
sofa::core::behavior::BaseLMConstraint *constraint=LMConstraints[componentConstraint];
//Find the constraint dealing with contact
if (ContactDescriptionHandler* contactDescriptor=dynamic_cast<ContactDescriptionHandler*>(constraint))
{
const helper::vector< sofa::core::behavior::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order);
//Iterate among all the contacts
for (helper::vector< sofa::core::behavior::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup)
{
const sofa::core::behavior::ConstraintGroup* group=*itGroup;
const sofa::component::constraintset::ContactDescription& contact=contactDescriptor->getContactDescription(group);
const unsigned int idxEquation=group->getConstraint(0).idx;
switch(contact.state)
{
case VANISHING:
{
// serr <<"Constraint " << idxEquation << " VANISHING" << sendl;
//0 equation
break;
}
case STICKING:
{
// serr << "Constraint " <<idxEquation << " STICKING" << sendl;
const unsigned int i=rowsL.size();
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation ));
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1));
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2));
//3 equations
rowsLT.push_back(rowsL[i ]);
rowsLT.push_back(rowsL[i+1]);
rowsLT.push_back(rowsL[i+2]);
rightHandElements.push_back(idxEquation );
rightHandElements.push_back(idxEquation+1);
rightHandElements.push_back(idxEquation+2);
break;
}
case SLIDING:
{
// serr << "Constraint " <<idxEquation << " SLIDING" << sendl;
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation ));
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1));
rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2));
//1 equation with the response force along the Coulomb friction cone
rowsLT.push_back(linearsolver::LLineManipulator()
.addCombination(idxEquation ,contact.coeff[0])
.addCombination(idxEquation+1,contact.coeff[1])
.addCombination(idxEquation+2,contact.coeff[2]));
rightHandElements.push_back(idxEquation );
rightHandElements.push_back(idxEquation+1);
rightHandElements.push_back(idxEquation+2);
break;
}
}
}
}
else
{
//Non contact constraints: we add all the equations
const helper::vector< sofa::core::behavior::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order);
for (helper::vector< sofa::core::behavior::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup)
{
const sofa::core::behavior::ConstraintGroup* group=*itGroup;
std::pair< sofa::core::behavior::ConstraintGroup::EquationConstIterator,sofa::core::behavior::ConstraintGroup::EquationConstIterator> range=group->data();
for ( sofa::core::behavior::ConstraintGroup::EquationConstIterator it=range.first; it!=range.second; ++it)
{
rowsL.push_back(linearsolver::LLineManipulator().addCombination(it->idx));
rowsLT.push_back(rowsL.back());
rightHandElements.push_back(it->idx);
}
}
}
}
}
void LMConstraintDirectSolver::buildLeftRectangularMatrix(const DofToMatrix& invMassMatrix,
DofToMatrix& LMatrix, DofToMatrix& LTMatrix,
SparseColMajorMatrixEigen &LeftMatrix, DofToMatrix &invMass_Ltrans) const
{
invMass_Ltrans.clear();
for (SetDof::const_iterator itDofs=setDofs.begin(); itDofs!=setDofs.end(); ++itDofs)
{
const sofa::core::behavior::BaseMechanicalState* dofs=*itDofs;
const SparseMatrixEigen &invMass=invMassMatrix.find(dofs)->second;
const SparseMatrixEigen &L =LMatrix[dofs];
const SparseMatrixEigen <=LTMatrix[dofs];
SparseMatrixEigen invMass_LT=invMass*LT.transpose();
invMass_Ltrans.insert(std::make_pair(dofs, invMass_LT));
//SparseColMajorMatrixEigen temp=L*invMass_LT;
LeftMatrix += L*invMass_LT;
}
}
int LMConstraintDirectSolverClass = core::RegisterObject("A Direct Constraint Solver working specifically with LMConstraint based components")
.add< LMConstraintDirectSolver >();
SOFA_DECL_CLASS(LMConstraintDirectSolver);
} // namespace constraintset
} // namespace component
} // namespace sofa
|
Altered is a pretty intense thriller, with lots of suspense and even a little paranormal thrown in! The writing style is unique, really teenager oriented, and the characters are gritty and real.
“But how are we supposed to meet with them if we don’t know if we can trust them?” Anton asked swiftly. They had to keep this meeting short. It had taken them a while to all get to the abandoned house safely. The Academy was watching every move now, waiting for a mistake.
The group turned to Ann. Toni, Melvin, Anton and Lieutenant had all seen people who seemed to be hinting that they wanted to join their mini rebellion.
“What do you mean?” Toni asked.
“But what if they don’t understand that they have to act on their own?” Anton asked.
“Or get too scared of acting by themselves?” Lieutenant questioned.
“I think Ann just got promoted to Captain,” Lieutenant said, clapping her hand to Ann’s and pulling their fingers apart.
New Feature!: What's My Story? |
Formal statement is: lemma\<^marker>\<open>tag important\<close> lmeasurable_iff_integrable: "S \<in> lmeasurable \<longleftrightarrow> integrable lebesgue (indicator S :: 'a::euclidean_space \<Rightarrow> real)" Informal statement is: A set $S$ is Lebesgue measurable if and only if the indicator function of $S$ is integrable. |
module abstract_get_pseudo_ensperts_mod
type, abstract :: abstract_get_pseudo_ensperts_class
integer, allocatable :: dummy(:)
contains
procedure(get_pseudo_ensperts), deferred, pass(this) :: get_pseudo_ensperts
end type abstract_get_pseudo_ensperts_class
abstract interface
subroutine get_pseudo_ensperts(this,en_perts,nelen)
use gsi_bundlemod, only: gsi_bundle
use kinds, only: i_kind
import abstract_get_pseudo_ensperts_class
implicit none
class(abstract_get_pseudo_ensperts_class), intent(inout) :: this
type(gsi_bundle),allocatable, intent(in ) :: en_perts(:,:)
integer(i_kind), intent(in ) :: nelen
end subroutine get_pseudo_ensperts
end interface
end module abstract_get_pseudo_ensperts_mod
|
(*<*)
(* Author: Kyndylan Nienhuis *)
theory ExceptionFlag
imports
"CHERI-core.CheriLemmas"
begin
(*>*)
section \<open>Invariance of @{const getExceptionSignalled}\<close>
named_theorems ExceptionSignalledI
lemma ExceptionSignalled_to_HoareTriple:
fixes m :: "state \<Rightarrow> 'a \<times> state"
assumes "\<And>s. getExceptionSignalled (StatePart m s) = True"
shows "HoareTriple (return True) m (\<lambda>_. read_state getExceptionSignalled)"
using assms
by - HoareTriple
lemmas nonExceptionCase_exceptions =
ExceptionSignalled_to_HoareTriple[OF setSignalException_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalCP2UnusableException_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalCapException_internal_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalCapException_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalCapException_noReg_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalTLBException_getExceptionSignalled]
ExceptionSignalled_to_HoareTriple[OF setSignalTLBCapException_getExceptionSignalled]
(* Code generation - start - ExceptionSignalled invariant *)
lemma ExceptionSignalled_raise'exception [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (raise'exception v)"
unfolding raise'exception_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_PIC_update [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (PIC_update v)"
unfolding PIC_update_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_PIC_initialise [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (PIC_initialise v)"
unfolding PIC_initialise_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_PIC_load [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (PIC_load v)"
unfolding PIC_load_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_PIC_store [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (PIC_store v)"
unfolding PIC_store_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_update_interrupt_bit [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (JTAG_UART_update_interrupt_bit v)"
unfolding JTAG_UART_update_interrupt_bit_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_load [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) JTAG_UART_load"
unfolding JTAG_UART_load_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_input [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (JTAG_UART_input v)"
unfolding JTAG_UART_input_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_store [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (JTAG_UART_store v)"
unfolding JTAG_UART_store_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_output [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) JTAG_UART_output"
unfolding JTAG_UART_output_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_JTAG_UART_initialise [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (JTAG_UART_initialise v)"
unfolding JTAG_UART_initialise_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_gpr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (gpr v)"
unfolding gpr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'gpr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'gpr v)"
unfolding write'gpr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_GPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (GPR v)"
unfolding GPR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'GPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'GPR v)"
unfolding write'GPR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_UserMode [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) UserMode"
unfolding UserMode_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SupervisorMode [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) SupervisorMode"
unfolding SupervisorMode_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_KernelMode [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) KernelMode"
unfolding KernelMode_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_BigEndianMem [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) BigEndianMem"
unfolding BigEndianMem_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_ReverseEndian [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) ReverseEndian"
unfolding ReverseEndian_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_BigEndianCPU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) BigEndianCPU"
unfolding BigEndianCPU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CheckBranch [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) CheckBranch"
unfolding CheckBranch_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_BranchNotTaken [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) BranchNotTaken"
unfolding BranchNotTaken_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_BranchLikelyNotTaken [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) BranchLikelyNotTaken"
unfolding BranchLikelyNotTaken_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_initCoreStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) initCoreStats"
unfolding initCoreStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_printCoreStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) printCoreStats"
unfolding printCoreStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_next_unknown [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (next_unknown v)"
unfolding next_unknown_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_PCC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) PCC"
unfolding PCC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'PCC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'PCC v)"
unfolding write'PCC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CAPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (CAPR v)"
unfolding CAPR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'CAPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'CAPR v)"
unfolding write'CAPR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SCAPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SCAPR v)"
unfolding SCAPR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'SCAPR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'SCAPR v)"
unfolding write'SCAPR_alt_def
by (Invariant intro: ExceptionSignalledI)
(* Code generation - override - SignalException *)
lemma ExceptionSignalled_SignalException [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalException v)"
unfolding SignalException_alt_def
by (HoareTriple intro: ExceptionSignalledI)
(* Code generation - end override *)
lemma ExceptionSignalled_SignalCP2UnusableException [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) SignalCP2UnusableException"
unfolding SignalCP2UnusableException_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalCapException_internal [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalCapException_internal v)"
unfolding SignalCapException_internal_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalCapException [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalCapException v)"
unfolding SignalCapException_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalCapException_noReg [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalCapException_noReg v)"
unfolding SignalCapException_noReg_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ERET [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'ERET"
unfolding dfn'ERET_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_TLB_direct [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (TLB_direct v)"
unfolding TLB_direct_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'TLB_direct [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'TLB_direct v)"
unfolding write'TLB_direct_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_TLB_assoc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (TLB_assoc v)"
unfolding TLB_assoc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'TLB_assoc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'TLB_assoc v)"
unfolding write'TLB_assoc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_LookupTLB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (LookupTLB v)"
unfolding LookupTLB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalTLBException_internal [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalTLBException_internal v)"
unfolding SignalTLBException_internal_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalTLBException [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalTLBException v)"
unfolding SignalTLBException_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CheckSegment [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (CheckSegment v)"
unfolding CheckSegment_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_check_cca [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (check_cca v)"
unfolding check_cca_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_TLB_next_random [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (TLB_next_random v)"
unfolding TLB_next_random_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_AddressTranslation [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (AddressTranslation v)"
unfolding AddressTranslation_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CP0TLBEntry [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (CP0TLBEntry v)"
unfolding CP0TLBEntry_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_SignalTLBCapException [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (SignalTLBCapException v)"
unfolding SignalTLBCapException_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_printMemStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) printMemStats"
unfolding printMemStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_initMemStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) initMemStats"
unfolding initMemStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_data_reads_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_data_reads_updt v)"
unfolding stats_data_reads_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_data_writes_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_data_writes_updt v)"
unfolding stats_data_writes_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_inst_reads_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_inst_reads_updt v)"
unfolding stats_inst_reads_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_valid_cap_reads_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_valid_cap_reads_updt v)"
unfolding stats_valid_cap_reads_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_valid_cap_writes_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_valid_cap_writes_updt v)"
unfolding stats_valid_cap_writes_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_invalid_cap_reads_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_invalid_cap_reads_updt v)"
unfolding stats_invalid_cap_reads_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_stats_invalid_cap_writes_updt [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (stats_invalid_cap_writes_updt v)"
unfolding stats_invalid_cap_writes_updt_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_MEM [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (MEM v)"
unfolding MEM_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'MEM [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'MEM v)"
unfolding write'MEM_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_InitMEM [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) InitMEM"
unfolding InitMEM_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_ReadData [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (ReadData v)"
unfolding ReadData_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_WriteData [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (WriteData v)"
unfolding WriteData_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_ReadInst [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (ReadInst v)"
unfolding ReadInst_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_ReadCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (ReadCap v)"
unfolding ReadCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_WriteCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (WriteCap v)"
unfolding WriteCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_AdjustEndian [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (AdjustEndian v)"
unfolding AdjustEndian_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_initMemAccessStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) initMemAccessStats"
unfolding initMemAccessStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_printMemAccessStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) printMemAccessStats"
unfolding printMemAccessStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_getVirtualAddress [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (getVirtualAddress v)"
unfolding getVirtualAddress_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_LoadMemoryCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (LoadMemoryCap v)"
unfolding LoadMemoryCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_LoadMemory [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (LoadMemory v)"
unfolding LoadMemory_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_LoadCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (LoadCap v)"
unfolding LoadCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_StoreMemoryCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (StoreMemoryCap v)"
unfolding StoreMemoryCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_StoreMemory [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (StoreMemory v)"
unfolding StoreMemory_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_StoreCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (StoreCap v)"
unfolding StoreCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_Fetch [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) Fetch"
unfolding Fetch_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CP0R [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (CP0R v)"
unfolding CP0R_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'CP0R [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'CP0R v)"
unfolding write'CP0R_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_resetStats [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) resetStats"
unfolding resetStats_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_HI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) HI"
unfolding HI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'HI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'HI v)"
unfolding write'HI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_LO [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) LO"
unfolding LO_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_write'LO [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (write'LO v)"
unfolding write'LO_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_mtc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (mtc v)"
unfolding mtc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dmtc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dmtc v)"
unfolding dmtc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_mfc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (mfc v)"
unfolding mfc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dmfc [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dmfc v)"
unfolding dmfc_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ADDI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ADDI v)"
unfolding dfn'ADDI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ADDIU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ADDIU v)"
unfolding dfn'ADDIU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DADDI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DADDI v)"
unfolding dfn'DADDI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DADDIU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DADDIU v)"
unfolding dfn'DADDIU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLTI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLTI v)"
unfolding dfn'SLTI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLTIU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLTIU v)"
unfolding dfn'SLTIU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ANDI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ANDI v)"
unfolding dfn'ANDI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ORI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ORI v)"
unfolding dfn'ORI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'XORI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'XORI v)"
unfolding dfn'XORI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LUI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LUI v)"
unfolding dfn'LUI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ADD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ADD v)"
unfolding dfn'ADD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ADDU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ADDU v)"
unfolding dfn'ADDU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SUB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SUB v)"
unfolding dfn'SUB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SUBU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SUBU v)"
unfolding dfn'SUBU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DADD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DADD v)"
unfolding dfn'DADD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DADDU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DADDU v)"
unfolding dfn'DADDU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSUB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSUB v)"
unfolding dfn'DSUB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSUBU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSUBU v)"
unfolding dfn'DSUBU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLT [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLT v)"
unfolding dfn'SLT_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLTU v)"
unfolding dfn'SLTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'AND [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'AND v)"
unfolding dfn'AND_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'OR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'OR v)"
unfolding dfn'OR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'XOR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'XOR v)"
unfolding dfn'XOR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'NOR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'NOR v)"
unfolding dfn'NOR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MOVN [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MOVN v)"
unfolding dfn'MOVN_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MOVZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MOVZ v)"
unfolding dfn'MOVZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MADD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MADD v)"
unfolding dfn'MADD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MADDU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MADDU v)"
unfolding dfn'MADDU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MSUB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MSUB v)"
unfolding dfn'MSUB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MSUBU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MSUBU v)"
unfolding dfn'MSUBU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MUL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MUL v)"
unfolding dfn'MUL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MULT [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MULT v)"
unfolding dfn'MULT_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MULTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MULTU v)"
unfolding dfn'MULTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DMULT [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DMULT v)"
unfolding dfn'DMULT_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DMULTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DMULTU v)"
unfolding dfn'DMULTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DIV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DIV v)"
unfolding dfn'DIV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DIVU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DIVU v)"
unfolding dfn'DIVU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DDIV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DDIV v)"
unfolding dfn'DDIV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DDIVU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DDIVU v)"
unfolding dfn'DDIVU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MFHI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MFHI v)"
unfolding dfn'MFHI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MFLO [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MFLO v)"
unfolding dfn'MFLO_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MTHI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MTHI v)"
unfolding dfn'MTHI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MTLO [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MTLO v)"
unfolding dfn'MTLO_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLL v)"
unfolding dfn'SLL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SRL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SRL v)"
unfolding dfn'SRL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SRA [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SRA v)"
unfolding dfn'SRA_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SLLV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SLLV v)"
unfolding dfn'SLLV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SRLV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SRLV v)"
unfolding dfn'SRLV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SRAV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SRAV v)"
unfolding dfn'SRAV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSLL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSLL v)"
unfolding dfn'DSLL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRL v)"
unfolding dfn'DSRL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRA [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRA v)"
unfolding dfn'DSRA_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSLLV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSLLV v)"
unfolding dfn'DSLLV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRLV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRLV v)"
unfolding dfn'DSRLV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRAV [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRAV v)"
unfolding dfn'DSRAV_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSLL32 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSLL32 v)"
unfolding dfn'DSLL32_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRL32 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRL32 v)"
unfolding dfn'DSRL32_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DSRA32 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DSRA32 v)"
unfolding dfn'DSRA32_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TGE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TGE v)"
unfolding dfn'TGE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TGEU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TGEU v)"
unfolding dfn'TGEU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLT [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TLT v)"
unfolding dfn'TLT_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TLTU v)"
unfolding dfn'TLTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TEQ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TEQ v)"
unfolding dfn'TEQ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TNE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TNE v)"
unfolding dfn'TNE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TGEI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TGEI v)"
unfolding dfn'TGEI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TGEIU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TGEIU v)"
unfolding dfn'TGEIU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLTI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TLTI v)"
unfolding dfn'TLTI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLTIU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TLTIU v)"
unfolding dfn'TLTIU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TEQI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TEQI v)"
unfolding dfn'TEQI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TNEI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'TNEI v)"
unfolding dfn'TNEI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_loadByte [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (loadByte v)"
unfolding loadByte_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_loadHalf [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (loadHalf v)"
unfolding loadHalf_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_loadWord [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (loadWord v)"
unfolding loadWord_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_loadDoubleword [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (loadDoubleword v)"
unfolding loadDoubleword_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LB v)"
unfolding dfn'LB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LBU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LBU v)"
unfolding dfn'LBU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LH [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LH v)"
unfolding dfn'LH_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LHU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LHU v)"
unfolding dfn'LHU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LW [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LW v)"
unfolding dfn'LW_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LWU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LWU v)"
unfolding dfn'LWU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LL v)"
unfolding dfn'LL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LD v)"
unfolding dfn'LD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LLD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LLD v)"
unfolding dfn'LLD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LWL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LWL v)"
unfolding dfn'LWL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LWR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LWR v)"
unfolding dfn'LWR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LDL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LDL v)"
unfolding dfn'LDL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'LDR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'LDR v)"
unfolding dfn'LDR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SB [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SB v)"
unfolding dfn'SB_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SH [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SH v)"
unfolding dfn'SH_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_storeWord [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (storeWord v)"
unfolding storeWord_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_storeDoubleword [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (storeDoubleword v)"
unfolding storeDoubleword_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SW [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SW v)"
unfolding dfn'SW_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SD v)"
unfolding dfn'SD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SC v)"
unfolding dfn'SC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SCD [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SCD v)"
unfolding dfn'SCD_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SWL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SWL v)"
unfolding dfn'SWL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SWR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SWR v)"
unfolding dfn'SWR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SDL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SDL v)"
unfolding dfn'SDL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SDR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'SDR v)"
unfolding dfn'SDR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BREAK [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'BREAK"
unfolding dfn'BREAK_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'SYSCALL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'SYSCALL"
unfolding dfn'SYSCALL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MTC0 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MTC0 v)"
unfolding dfn'MTC0_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DMTC0 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DMTC0 v)"
unfolding dfn'DMTC0_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'MFC0 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'MFC0 v)"
unfolding dfn'MFC0_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'DMFC0 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'DMFC0 v)"
unfolding dfn'DMFC0_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'J [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'J v)"
unfolding dfn'J_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'JAL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'JAL v)"
unfolding dfn'JAL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'JALR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'JALR v)"
unfolding dfn'JALR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'JR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'JR v)"
unfolding dfn'JR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BEQ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BEQ v)"
unfolding dfn'BEQ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BNE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BNE v)"
unfolding dfn'BNE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLEZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLEZ v)"
unfolding dfn'BLEZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGTZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGTZ v)"
unfolding dfn'BGTZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLTZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLTZ v)"
unfolding dfn'BLTZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGEZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGEZ v)"
unfolding dfn'BGEZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLTZAL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLTZAL v)"
unfolding dfn'BLTZAL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGEZAL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGEZAL v)"
unfolding dfn'BGEZAL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BEQL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BEQL v)"
unfolding dfn'BEQL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BNEL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BNEL v)"
unfolding dfn'BNEL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLEZL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLEZL v)"
unfolding dfn'BLEZL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGTZL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGTZL v)"
unfolding dfn'BGTZL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLTZL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLTZL v)"
unfolding dfn'BLTZL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGEZL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGEZL v)"
unfolding dfn'BGEZL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BLTZALL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BLTZALL v)"
unfolding dfn'BLTZALL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'BGEZALL [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'BGEZALL v)"
unfolding dfn'BGEZALL_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'RDHWR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'RDHWR v)"
unfolding dfn'RDHWR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CACHE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CACHE v)"
unfolding dfn'CACHE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ReservedInstruction [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'ReservedInstruction"
unfolding dfn'ReservedInstruction_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'Unpredictable [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'Unpredictable"
unfolding dfn'Unpredictable_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLBP [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'TLBP"
unfolding dfn'TLBP_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLBR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'TLBR"
unfolding dfn'TLBR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLBWI [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'TLBWI"
unfolding dfn'TLBWI_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'TLBWR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'TLBWR"
unfolding dfn'TLBWR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'COP1 [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'COP1 v)"
unfolding dfn'COP1_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetBase [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetBase v)"
unfolding dfn'CGetBase_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetOffset [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetOffset v)"
unfolding dfn'CGetOffset_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetLen [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetLen v)"
unfolding dfn'CGetLen_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetTag [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetTag v)"
unfolding dfn'CGetTag_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetSealed [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetSealed v)"
unfolding dfn'CGetSealed_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetPerm [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetPerm v)"
unfolding dfn'CGetPerm_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetType [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetType v)"
unfolding dfn'CGetType_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetAddr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetAddr v)"
unfolding dfn'CGetAddr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetPCC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetPCC v)"
unfolding dfn'CGetPCC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetPCCSetOffset [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetPCCSetOffset v)"
unfolding dfn'CGetPCCSetOffset_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CGetCause [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CGetCause v)"
unfolding dfn'CGetCause_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSetCause [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSetCause v)"
unfolding dfn'CSetCause_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CIncOffset [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CIncOffset v)"
unfolding dfn'CIncOffset_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CIncOffsetImmediate [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CIncOffsetImmediate v)"
unfolding dfn'CIncOffsetImmediate_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSetBounds [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSetBounds v)"
unfolding dfn'CSetBounds_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSetBoundsExact [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSetBoundsExact v)"
unfolding dfn'CSetBoundsExact_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSetBoundsImmediate [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSetBoundsImmediate v)"
unfolding dfn'CSetBoundsImmediate_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_ClearRegs [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (ClearRegs v)"
unfolding ClearRegs_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ClearLo [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ClearLo v)"
unfolding dfn'ClearLo_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'ClearHi [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'ClearHi v)"
unfolding dfn'ClearHi_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CClearLo [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CClearLo v)"
unfolding dfn'CClearLo_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CClearHi [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CClearHi v)"
unfolding dfn'CClearHi_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CClearTag [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CClearTag v)"
unfolding dfn'CClearTag_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CAndPerm [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CAndPerm v)"
unfolding dfn'CAndPerm_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSetOffset [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSetOffset v)"
unfolding dfn'CSetOffset_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSub [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSub v)"
unfolding dfn'CSub_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CCheckPerm [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CCheckPerm v)"
unfolding dfn'CCheckPerm_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CCheckType [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CCheckType v)"
unfolding dfn'CCheckType_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CFromPtr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CFromPtr v)"
unfolding dfn'CFromPtr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CToPtr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CToPtr v)"
unfolding dfn'CToPtr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_CPtrCmp [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (CPtrCmp v)"
unfolding CPtrCmp_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CEQ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CEQ v)"
unfolding dfn'CEQ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CNE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CNE v)"
unfolding dfn'CNE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLT [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLT v)"
unfolding dfn'CLT_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLE [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLE v)"
unfolding dfn'CLE_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLTU v)"
unfolding dfn'CLTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLEU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLEU v)"
unfolding dfn'CLEU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CEXEQ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CEXEQ v)"
unfolding dfn'CEXEQ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CNEXEQ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CNEXEQ v)"
unfolding dfn'CNEXEQ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CBTU [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CBTU v)"
unfolding dfn'CBTU_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CBTS [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CBTS v)"
unfolding dfn'CBTS_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CBEZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CBEZ v)"
unfolding dfn'CBEZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CBNZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CBNZ v)"
unfolding dfn'CBNZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSC v)"
unfolding dfn'CSC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLC v)"
unfolding dfn'CLC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLoad [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLoad v)"
unfolding dfn'CLoad_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_store [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (store v)"
unfolding store_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CStore [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CStore v)"
unfolding dfn'CStore_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLLC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLLC v)"
unfolding dfn'CLLC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CLLx [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CLLx v)"
unfolding dfn'CLLx_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSCC [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSCC v)"
unfolding dfn'CSCC_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSCx [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSCx v)"
unfolding dfn'CSCx_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CMOVN [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CMOVN v)"
unfolding dfn'CMOVN_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CMOVZ [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CMOVZ v)"
unfolding dfn'CMOVZ_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CMove [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CMove v)"
unfolding dfn'CMove_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CTestSubset [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CTestSubset v)"
unfolding dfn'CTestSubset_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CBuildCap [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CBuildCap v)"
unfolding dfn'CBuildCap_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CCopyType [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CCopyType v)"
unfolding dfn'CCopyType_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CJR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CJR v)"
unfolding dfn'CJR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CJALR [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CJALR v)"
unfolding dfn'CJALR_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CSeal [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CSeal v)"
unfolding dfn'CSeal_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CUnseal [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CUnseal v)"
unfolding dfn'CUnseal_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CCall [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CCall v)"
unfolding dfn'CCall_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CCallFast [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CCallFast v)"
unfolding dfn'CCallFast_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_special_register_accessible [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (special_register_accessible v)"
unfolding special_register_accessible_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CReadHwr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CReadHwr v)"
unfolding dfn'CReadHwr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CWriteHwr [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (dfn'CWriteHwr v)"
unfolding dfn'CWriteHwr_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'CReturn [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'CReturn"
unfolding dfn'CReturn_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_dfn'UnknownCapInstruction [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) dfn'UnknownCapInstruction"
unfolding dfn'UnknownCapInstruction_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_log_instruction [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (log_instruction v)"
unfolding log_instruction_alt_def
by (Invariant intro: ExceptionSignalledI)
lemma ExceptionSignalled_Run [ExceptionSignalledI]:
shows "IsInvariant (read_state getExceptionSignalled) (Run v)"
unfolding Run_alt_def
by (Invariant intro: ExceptionSignalledI)
(* Code generation - skip - Next *)
(* Code generation - end *)
(*<*)
end
(*>*)
|
Require Export List. Export ListNotations.
Require Export ZArith.
Local Open Scope Z_scope.
Require Export Integers.
Require Export floyd.sublist.
Definition Nk := 8. (* number of words in key *)
Definition Nr := 14. (* number of cipher rounds *)
Definition Nb := 4. (* number of words in a block (state) *)
(* arr: list of 4 bytes *)
Definition get_uint32_le (arr: list Z) (i: Z) : int :=
(Int.or (Int.or (Int.or
(Int.repr (Znth i arr 0))
(Int.shl (Int.repr (Znth (i+1) arr 0)) (Int.repr 8)))
(Int.shl (Int.repr (Znth (i+2) arr 0)) (Int.repr 16)))
(Int.shl (Int.repr (Znth (i+3) arr 0)) (Int.repr 24))).
(* outputs a list of 4 bytes *)
Definition put_uint32_le (x : int) : list int :=
[ (Int.and x (Int.repr 255));
(Int.and (Int.shru x (Int.repr 8)) (Int.repr 255));
(Int.and (Int.shru x (Int.repr 16)) (Int.repr 255));
(Int.and (Int.shru x (Int.repr 24)) (Int.repr 255)) ].
Definition byte0 (x : int) : Z :=
(Z.land (Int.unsigned x) (Int.unsigned (Int.repr 255))).
Definition byte1 (x : int) : Z :=
(Z.land (Int.unsigned (Int.shru x (Int.repr 8))) (Int.unsigned (Int.repr 255))).
Definition byte2 (x : int) : Z :=
(Z.land (Int.unsigned (Int.shru x (Int.repr 16))) (Int.unsigned (Int.repr 255))).
Definition byte3 (x : int) : Z :=
(Z.land (Int.unsigned (Int.shru x (Int.repr 24))) (Int.unsigned (Int.repr 255))).
|
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
! This file was ported from Lean 3 source module ring_theory.nilpotent
! leanprover-community/mathlib commit da420a8c6dd5bdfb85c4ced85c34388f633bc6ff
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.Nat.Choose.Sum
import Mathlib.Algebra.Algebra.Bilinear
import Mathlib.RingTheory.Ideal.Operations
/-!
# Nilpotent elements
## Main definitions
* `IsNilpotent`
* `isNilpotent_neg_iff`
* `Commute.isNilpotent_add`
* `Commute.isNilpotent_mul_left`
* `Commute.isNilpotent_mul_right`
* `Commute.isNilpotent_sub`
-/
universe u v
variable {R S : Type u} {x y : R}
/-- An element is said to be nilpotent if some natural-number-power of it equals zero.
Note that we require only the bare minimum assumptions for the definition to make sense. Even
`MonoidWithZero` is too strong since nilpotency is important in the study of rings that are only
power-associative. -/
def IsNilpotent [Zero R] [Pow R ℕ] (x : R) : Prop :=
∃ n : ℕ, x ^ n = 0
#align is_nilpotent IsNilpotent
theorem IsNilpotent.mk [Zero R] [Pow R ℕ] (x : R) (n : ℕ) (e : x ^ n = 0) : IsNilpotent x :=
⟨n, e⟩
#align is_nilpotent.mk IsNilpotent.mk
theorem IsNilpotent.zero [MonoidWithZero R] : IsNilpotent (0 : R) :=
⟨1, pow_one 0⟩
#align is_nilpotent.zero IsNilpotent.zero
theorem IsNilpotent.neg [Ring R] (h : IsNilpotent x) : IsNilpotent (-x) := by
obtain ⟨n, hn⟩ := h
use n
rw [neg_pow, hn, MulZeroClass.mul_zero]
#align is_nilpotent.neg IsNilpotent.neg
@[simp]
theorem isNilpotent_neg_iff [Ring R] : IsNilpotent (-x) ↔ IsNilpotent x :=
⟨fun h => neg_neg x ▸ h.neg, fun h => h.neg⟩
#align is_nilpotent_neg_iff isNilpotent_neg_iff
theorem IsNilpotent.map [MonoidWithZero R] [MonoidWithZero S] {r : R} {F : Type _}
[MonoidWithZeroHomClass F R S] (hr : IsNilpotent r) (f : F) : IsNilpotent (f r) := by
use hr.choose
rw [← map_pow, hr.choose_spec, map_zero]
#align is_nilpotent.map IsNilpotent.map
/-- A structure that has zero and pow is reduced if it has no nonzero nilpotent elements. -/
@[mk_iff isReduced_iff]
class IsReduced (R : Type _) [Zero R] [Pow R ℕ] : Prop where
/-- A reduced structure has no nonzero nilpotent elements. -/
eq_zero : ∀ x : R, IsNilpotent x → x = 0
#align is_reduced IsReduced
instance (priority := 900) isReduced_of_noZeroDivisors [MonoidWithZero R] [NoZeroDivisors R] :
IsReduced R :=
⟨fun _ ⟨_, hn⟩ => pow_eq_zero hn⟩
#align is_reduced_of_no_zero_divisors isReduced_of_noZeroDivisors
instance (priority := 900) isReduced_of_subsingleton [Zero R] [Pow R ℕ] [Subsingleton R] :
IsReduced R :=
⟨fun _ _ => Subsingleton.elim _ _⟩
#align is_reduced_of_subsingleton isReduced_of_subsingleton
theorem IsNilpotent.eq_zero [Zero R] [Pow R ℕ] [IsReduced R] (h : IsNilpotent x) : x = 0 :=
IsReduced.eq_zero x h
#align is_nilpotent.eq_zero IsNilpotent.eq_zero
@[simp]
theorem isNilpotent_iff_eq_zero [MonoidWithZero R] [IsReduced R] : IsNilpotent x ↔ x = 0 :=
⟨fun h => h.eq_zero, fun h => h.symm ▸ IsNilpotent.zero⟩
#align is_nilpotent_iff_eq_zero isNilpotent_iff_eq_zero
theorem isReduced_of_injective [MonoidWithZero R] [MonoidWithZero S] {F : Type _}
[MonoidWithZeroHomClass F R S] (f : F) (hf : Function.Injective f) [IsReduced S] :
IsReduced R := by
constructor
intro x hx
apply hf
rw [map_zero]
exact (hx.map f).eq_zero
#align is_reduced_of_injective isReduced_of_injective
-- Porting note: Added etaExperiment line to synthesize RingHomClass
set_option synthInstance.etaExperiment true
theorem RingHom.ker_isRadical_iff_reduced_of_surjective {S F} [CommSemiring R] [CommRing S]
[RingHomClass F R S] {f : F} (hf : Function.Surjective f) :
(RingHom.ker f).IsRadical ↔ IsReduced S := by
simp_rw [isReduced_iff, hf.forall, IsNilpotent, ← map_pow, ← RingHom.mem_ker]
rfl
#align ring_hom.ker_is_radical_iff_reduced_of_surjective RingHom.ker_isRadical_iff_reduced_of_surjective
set_option synthInstance.etaExperiment false
/-- An element `y` in a monoid is radical if for any element `x`, `y` divides `x` whenever it
divides a power of `x`. -/
def IsRadical [Dvd R] [Pow R ℕ] (y : R) : Prop :=
∀ (n : ℕ) (x), y ∣ x ^ n → y ∣ x
#align is_radical IsRadical
theorem zero_isRadical_iff [MonoidWithZero R] : IsRadical (0 : R) ↔ IsReduced R := by
simp_rw [isReduced_iff, IsNilpotent, exists_imp, ← zero_dvd_iff]
exact forall_swap
#align zero_is_radical_iff zero_isRadical_iff
theorem isRadical_iff_span_singleton [CommSemiring R] :
IsRadical y ↔ (Ideal.span ({y} : Set R)).IsRadical := by
simp_rw [IsRadical, ← Ideal.mem_span_singleton]
exact forall_swap.trans (forall_congr' fun r => exists_imp.symm)
#align is_radical_iff_span_singleton isRadical_iff_span_singleton
theorem isRadical_iff_pow_one_lt [MonoidWithZero R] (k : ℕ) (hk : 1 < k) :
IsRadical y ↔ ∀ x, y ∣ x ^ k → y ∣ x :=
⟨fun h x => h k x, fun h =>
k.cauchy_induction_mul (fun n h x hd => h x <| (pow_succ' x n).symm ▸ hd.mul_right x) 0 hk
(fun x hd => pow_one x ▸ hd) fun n _ hn x hd => h x <| hn _ <| (pow_mul x k n).subst hd⟩
#align is_radical_iff_pow_one_lt isRadical_iff_pow_one_lt
theorem isReduced_iff_pow_one_lt [MonoidWithZero R] (k : ℕ) (hk : 1 < k) :
IsReduced R ↔ ∀ x : R, x ^ k = 0 → x = 0 := by
simp_rw [← zero_isRadical_iff, isRadical_iff_pow_one_lt k hk, zero_dvd_iff]
#align is_reduced_iff_pow_one_lt isReduced_iff_pow_one_lt
namespace Commute
section Semiring
variable [Semiring R] (h_comm : Commute x y)
theorem isNilpotent_add (hx : IsNilpotent x) (hy : IsNilpotent y) : IsNilpotent (x + y) := by
obtain ⟨n, hn⟩ := hx
obtain ⟨m, hm⟩ := hy
use n + m - 1
rw [h_comm.add_pow']
apply Finset.sum_eq_zero
rintro ⟨i, j⟩ hij
suffices x ^ i * y ^ j = 0 by simp only [this, nsmul_eq_mul, MulZeroClass.mul_zero]
cases' Nat.le_or_le_of_add_eq_add_pred (Finset.Nat.mem_antidiagonal.mp hij) with hi hj
· rw [pow_eq_zero_of_le hi hn, MulZeroClass.zero_mul]
· rw [pow_eq_zero_of_le hj hm, MulZeroClass.mul_zero]
#align commute.is_nilpotent_add Commute.isNilpotent_add
theorem isNilpotent_mul_left (h : IsNilpotent x) : IsNilpotent (x * y) := by
obtain ⟨n, hn⟩ := h
use n
rw [h_comm.mul_pow, hn, MulZeroClass.zero_mul]
#align commute.is_nilpotent_mul_left Commute.isNilpotent_mul_left
theorem isNilpotent_mul_right (h : IsNilpotent y) : IsNilpotent (x * y) := by
rw [h_comm.eq]
exact h_comm.symm.isNilpotent_mul_left h
#align commute.is_nilpotent_mul_right Commute.isNilpotent_mul_right
end Semiring
section Ring
variable [Ring R] (h_comm : Commute x y)
theorem isNilpotent_sub (hx : IsNilpotent x) (hy : IsNilpotent y) : IsNilpotent (x - y) := by
rw [← neg_right_iff] at h_comm
rw [← isNilpotent_neg_iff] at hy
rw [sub_eq_add_neg]
exact h_comm.isNilpotent_add hx hy
#align commute.is_nilpotent_sub Commute.isNilpotent_sub
end Ring
end Commute
section CommSemiring
variable [CommSemiring R]
/-- The nilradical of a commutative semiring is the ideal of nilpotent elements. -/
def nilradical (R : Type _) [CommSemiring R] : Ideal R :=
(0 : Ideal R).radical
#align nilradical nilradical
theorem mem_nilradical : x ∈ nilradical R ↔ IsNilpotent x :=
Iff.rfl
#align mem_nilradical mem_nilradical
theorem nilradical_eq_infₛ (R : Type _) [CommSemiring R] :
nilradical R = infₛ { J : Ideal R | J.IsPrime } :=
(Ideal.radical_eq_infₛ ⊥).trans <| by simp_rw [and_iff_right bot_le]
#align nilradical_eq_Inf nilradical_eq_infₛ
theorem nilpotent_iff_mem_prime : IsNilpotent x ↔ ∀ J : Ideal R, J.IsPrime → x ∈ J := by
rw [← mem_nilradical, nilradical_eq_infₛ, Submodule.mem_infₛ]
rfl
#align nilpotent_iff_mem_prime nilpotent_iff_mem_prime
theorem nilradical_le_prime (J : Ideal R) [H : J.IsPrime] : nilradical R ≤ J :=
(nilradical_eq_infₛ R).symm ▸ infₛ_le H
#align nilradical_le_prime nilradical_le_prime
@[simp]
theorem nilradical_eq_zero (R : Type _) [CommSemiring R] [IsReduced R] : nilradical R = 0 :=
Ideal.ext fun _ => isNilpotent_iff_eq_zero
#align nilradical_eq_zero nilradical_eq_zero
end CommSemiring
namespace LinearMap
variable (R) {A : Type v} [CommSemiring R] [Semiring A] [Algebra R A]
@[simp]
theorem isNilpotent_mulLeft_iff (a : A) : IsNilpotent (mulLeft R a) ↔ IsNilpotent a := by
constructor <;> rintro ⟨n, hn⟩ <;> use n <;>
simp only [mulLeft_eq_zero_iff, pow_mulLeft] at hn⊢ <;>
exact hn
#align linear_map.is_nilpotent_mul_left_iff LinearMap.isNilpotent_mulLeft_iff
@[simp]
theorem isNilpotent_mulRight_iff (a : A) : IsNilpotent (mulRight R a) ↔ IsNilpotent a := by
constructor <;> rintro ⟨n, hn⟩ <;> use n <;>
simp only [mulRight_eq_zero_iff, pow_mulRight] at hn⊢ <;>
exact hn
#align linear_map.is_nilpotent_mul_right_iff LinearMap.isNilpotent_mulRight_iff
end LinearMap
namespace Module.End
variable {M : Type v} [Ring R] [AddCommGroup M] [Module R M]
variable {f : Module.End R M} {p : Submodule R M} (hp : p ≤ p.comap f)
theorem IsNilpotent.mapQ (hnp : IsNilpotent f) : IsNilpotent (p.mapQ p f hp) := by
obtain ⟨k, hk⟩ := hnp
use k
simp [← p.mapQ_pow, hk]
#align module.End.is_nilpotent.mapq Module.End.IsNilpotent.mapQ
end Module.End
|
------------------------------------------------------------------------
-- Parsing of mixfix operators
------------------------------------------------------------------------
-- This module defines a grammar for the precedence graph g.
open import RecursiveDescent.Hybrid.Mixfix.Expr
module RecursiveDescent.Hybrid.Mixfix (g : PrecedenceGraph) where
import Data.Vec as Vec
import Data.List as List
open List using (List; []; _∷_; foldr; foldl)
import Data.Vec1 as Vec1
open Vec1 using (Vec₁)
open import Data.Product renaming (_,_ to pair)
open import Data.Product.Record using (_,_)
open import Data.Bool
open import Data.Unit
open import Data.Nat
open import Data.Function hiding (_⟨_⟩_)
import Data.String as String
open import RecursiveDescent.Hybrid.Mixfix.Fixity
open import RecursiveDescent.Index
open import RecursiveDescent.Hybrid
open import RecursiveDescent.Hybrid.Simple
open import RecursiveDescent.Hybrid.Lib
open Token String.decSetoid
-- Note that, even though grammar below is not recursive, these
-- functions are (mutually). Fortunately the recursion is structural,
-- though. Note also that the reason for not using the implementation
--
-- grammar (nodes ts) = choiceMap (\t -> ! node t) ts
--
-- is that this would lead to a definition of node-corners which
-- was not structurally recursive.
nodes-corners : PrecedenceGraph -> Corners
nodes-corners [] = _
nodes-corners (p ∷ ps) = _
node-corners : PrecedenceTree -> Corners
node-corners (precedence ops ps) = _
-- Nonterminals.
data NT : ParserType where
-- Expressions.
expr : NT _ Expr
-- Expressions corresponding to zero or more nodes in the precedence
-- graph: operator applications where the outermost operator has one
-- of the precedences ps. The graph g is used for internal
-- expressions.
nodes : (ps : PrecedenceGraph) -> NT (false , nodes-corners ps) Expr
-- Expressions corresponding to one node in the precedence graph:
-- operator applications where the outermost operator has
-- precedence p. The graph g is used for internal expressions.
node : (p : PrecedenceTree) -> NT (false , node-corners p) Expr
-- The parser type used in this module.
P : Index -> Set -> Set1
P = Parser NamePart NT
-- A vector containing parsers recognising the name parts of the
-- operator.
nameParts : forall {fix arity} -> Operator fix arity ->
Vec₁ (P _ NamePart) (1 + arity)
nameParts (operator ns) = Vec1.map₀₁ sym ns
-- Internal parts (all name parts plus internal expressions) of
-- operators of the given precedence and fixity.
internal : forall {fix}
(ops : List (∃ (Operator fix))) -> P _ (Internal fix)
internal =
choiceMap (\op' -> let op = proj₂ op' in
_∙_ op <$> (! expr between nameParts op))
-- The grammar.
grammar : Grammar NamePart NT
grammar expr = ! nodes g
grammar (nodes []) = fail
grammar (nodes (p ∷ ps)) = ! node p ∣ ! nodes ps
grammar (node (precedence ops ps)) =
⟪_⟫ <$> ⟦ closed ⟧
∣ _⟨_⟩_ <$> ↑ ⊛ ⟦ infx non ⟧ ⊛ ↑
∣ flip (foldr _$_) <$> preRight + ⊛ ↑
∣ foldl (flip _$_) <$> ↑ ⊛ postLeft +
where
-- ⟦ fix ⟧ parses the internal parts of operators with the
-- current precedence level and fixity fix.
⟦_⟧ = \(fix : Fixity) -> internal (ops fix)
-- Operator applications where the outermost operator binds
-- tighter than the current precedence level.
↑ = ! nodes ps
-- Right associative and prefix operators.
preRight = ⟪_⟩_ <$> ⟦ prefx ⟧
∣ _⟨_⟩_ <$> ↑ ⊛ ⟦ infx right ⟧
-- Left associative and postfix operators.
postLeft = flip _⟨_⟫ <$> ⟦ postfx ⟧
∣ (\op e₂ e₁ -> e₁ ⟨ op ⟩ e₂) <$> ⟦ infx left ⟧ ⊛ ↑
-- An expression parser.
parseExpr : List NamePart -> List Expr
parseExpr = parse-complete (! expr) grammar
|
Like the best clinical tools, Bp Premier was created to extend and complement your own skills, knowledge and experience as a clinician.
Bp Premier’s power lies in the breadth and depth of relevant knowledge it brings to bear almost instantly, to support your actions or decisions as you prescribe appropriate medication, order pathology, and make and record a diagnosis. Bp’s intuitive functionality has grown out of the experience of literally thousands of your colleagues. We are committed to using that same source to keep Bp Premier at the cutting edge.
Simple and effective workflows designed by a doctor for doctors, including intuitive layouts with relevant patient information available at a glance.
Prescribe with confidence with the inclusion of MIMS© PI, CMI and Abridged Prescribing Information, including Product Identification images.
Access to actions, reminders and preventive health alerts to enhance patient care, including configurable pop-up prompts.
Customise and use ‘autofill’ features to provide more efficient and detailed patient consultation notes for individual users or across the team.
Editable templates automatically pull through patient and referral details for reduced typing and also integrate with Healthlink Smart Forms.
Inbuilt Health Tools include percentile charts, risk calculators, care plan and health assessment resources and many more!
Patient Education materials such as John Murtagh’s Patient Education, Healthshare fact sheets and Digital Health Media animations.
Inbuilt database search tool runs provided or original queries relating to patient information.
Travel Medicine Tool provides up to date travel vaccination advice and individualised vaccination scheduling.
SNOMED CT international clinical coding standard for accuracy and ease of use.
“As a Best Practice user since its early days, I could not imagine general practice without this essential tool. Bp’s continual evolution keeps it at the front of the pack, responding to the ever-changing demands that are part of today’s practice.
The Best Practice management software. Don’t settle for less. |
Tai Chi and Chi Kung Institute: What is Tai Chi?
New Beginners Term 2 - 2019 .
Courses are conducted during the state school terms.
Discount Coupon "2 for 1"
Why is Tai Chi used for relaxation and stress management?
Am I too old/young to learn Tai Chi?
What equipment do I need to practice Tai Chi?
Where does Tai Chi come from?
Where should I begin when learning Tai Chi?
What happens after I've learned the set?
How does Tai Chi compare to Chi Kung?
Available at classes or by mail.
Tai Chi is a major branch of the traditional Chinese sport of Wu Shu. As a means of keeping fit, preventing and curing diseases it has been practiced since the 16th century. Its prime purpose is to promote health in a slow relaxed manner, without jarring and hurting one's body. The movements are slow, with great emphasis on posture and balance.
The exercise requires a high degree of concentration, with the mind free of distractions. Breathing is natural, sometimes involving abdominal respiration, and its performance is in rhythmic harmony with body movements.
Originally developed as a martial art, the movements of Tai Chi were quickly recognized as being beneficial to the body. The major emphasis of Tai Chi today is on its health benefits, although it may still be used as a system of self-defense after years of training and practice.
Tai Chi makes an ideal complement to sport or other martial arts training as a warm up or warm down technique.
What are the health benefits of practicing Tai Chi?
Promote a general sense of well-being.
The Tai Chi practitioner concentrates on breathing and fluidity of form. During the exercise all outside thoughts are swept away and only the task on hand is deemed important. It is for this reason that in the West, Tai Chi is now highly regarded for relieving stress and tension.
Research by the Tai Chi & Chi Kung Institute however, has shown that those looking for stress management can gain more immediate relaxation benefits from Chi Kung classes, even at a very basic level.
Generally, relaxation gained from performing Tai Chi begins after the set has been learned.
There is generally no age limit with Tai Chi - both young and old can practice the art. However, we provide specially tailored classes for children in primary schools and older persons. As classes are conducted for the purpose of slow and relaxing exercise, which involves deep concentration, it is not appropriate to have anyone in a public class who may cause distractions (such as young, noisy children).
As no sports equipment, uniform or special grounds are required, Tai Chi can be done at any time and in any place. All you need is a small amount of open space, some loose, comfortable clothing and some flat-soled shoes that won't slip off during your practice. If possible, make sure that the sole of your shoe is flexible - some running shoes are too stiff for Tai Chi practice.
The term "Tai Chi" is an accepted English equivalent of the Chinese word "Taijiquan" (Tàijíquán), where "Tai" means "grand" or "supreme", "ji" means "ultimate" and "quan" means "fist" or "boxing" (the Chinese characters for this word are shown to the right).
It is accepted that the origin of Tai Chi was in the Chen Village in China. Today there are five main styles of Tai Chi: Chen, Yang, Wu, Sun and Woo (Hao). Each style is named for the family which traditionally created the style. Although each of the five styles has characteristics of its own, the essence of all are the same. The most popular style in China today is Yang style.
Beginning students at the Tai Chi & Chi Kung Institute are taught the Yang Tai Chi in 24 Forms (or Beijing 24) set. This set has been used in China for the mass promotion of Tai Chi and is taught in China by government institutions such as the Beijing University of Physical Education.
We believe that this set provides a good foundation for our students, which they can consolidate in their individual Tai Chi practice and build upon with intermediate and advanced sets.
Tai Chi is generally not easy for the beginning student. While it is not physically hard or strenuous, remembering the movements and co-ordinating the mind with the body can be challenging. Like most arts (such at painting or music), to do it well takes a lot of physical practice and intellectual study to understand the movements and gain the maximum health benefit from the exercise.
If you have little time to devote to your practice, but you are looking for relaxation and a pleasant, meditative feeling, we recommend Chi Kung - it is easier to learn and can provide relaxation benefits to the student immediately.
Once the set is learned, the student can continue to practice their Tai Chi for refinement and relaxation. Tai Chi learned well is a wonderful way to exercise!
The Institute offers Chi Kung (which you can learn at the same time as Tai Chi if you wish), or you can continue on to intermediate and advanced sets of Tai Chi, Weapon sets and Shaolin Arts.
Chi Kung is a health exercise based on Traditional Chinese Medicine theory. It emphasises the flow of Chi through the acupuncture meridians and is excellent for calming the mind and regulating the breath. On the other hand, Tai Chi emphasises the natural movement of the joints and muscles and increases circulation and is excellent for improving the focus of the mind.
For the beginning student, Tai Chi forms and movements are more complicated than Chi Kung forms and movements, therefore requiring more effort to learn them. You will need time to practice, patience with yourself and perseverance.
The classes are structured quite differently. Chi Kung students are guided through the exercises by the Instructor, while Tai Chi classes place a greater emphasis on the student, who first watches the Instructor, practices the movement and then tries out the movement on their own. |
printLength : IO ()
printLength = putStr "Input string: " >>= \_ =>
getLine >>= \input =>
let len = length input in
putStrLn (show len)
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(**************************************************************************)
(* *)
(* Omega: a solver of quantifier-free problems in Presburger Arithmetic *)
(* *)
(* Pierre Crégut (CNET, Lannion, France) *)
(* *)
(**************************************************************************)
(* $Id: Omega.v 14641 2011-11-06 11:59:10Z herbelin $ *)
(* We do not require [ZArith] anymore, but only what's necessary for Omega *)
Require Export ZArith_base.
Require Export OmegaLemmas.
Require Export PreOmega.
Declare ML Module "omega_plugin".
Hint Resolve Zle_refl Zplus_comm Zplus_assoc Zmult_comm Zmult_assoc Zplus_0_l
Zplus_0_r Zmult_1_l Zplus_opp_l Zplus_opp_r Zmult_plus_distr_l
Zmult_plus_distr_r: zarith.
Require Export Zhints.
(*
(* The constant minus is required in coq_omega.ml *)
Require Minus.
*)
Hint Extern 10 (_ = _ :>nat) => abstract omega: zarith.
Hint Extern 10 (_ <= _) => abstract omega: zarith.
Hint Extern 10 (_ < _) => abstract omega: zarith.
Hint Extern 10 (_ >= _) => abstract omega: zarith.
Hint Extern 10 (_ > _) => abstract omega: zarith.
Hint Extern 10 (_ <> _ :>nat) => abstract omega: zarith.
Hint Extern 10 (~ _ <= _) => abstract omega: zarith.
Hint Extern 10 (~ _ < _) => abstract omega: zarith.
Hint Extern 10 (~ _ >= _) => abstract omega: zarith.
Hint Extern 10 (~ _ > _) => abstract omega: zarith.
Hint Extern 10 (_ = _ :>Z) => abstract omega: zarith.
Hint Extern 10 (_ <= _)%Z => abstract omega: zarith.
Hint Extern 10 (_ < _)%Z => abstract omega: zarith.
Hint Extern 10 (_ >= _)%Z => abstract omega: zarith.
Hint Extern 10 (_ > _)%Z => abstract omega: zarith.
Hint Extern 10 (_ <> _ :>Z) => abstract omega: zarith.
Hint Extern 10 (~ (_ <= _)%Z) => abstract omega: zarith.
Hint Extern 10 (~ (_ < _)%Z) => abstract omega: zarith.
Hint Extern 10 (~ (_ >= _)%Z) => abstract omega: zarith.
Hint Extern 10 (~ (_ > _)%Z) => abstract omega: zarith.
Hint Extern 10 False => abstract omega: zarith. |
lemma analytic_on_linear [analytic_intros,simp]: "((*) c) analytic_on S" |
Interviewing for jobs can be grueling. But if you manage to drum up the right answers to trick interview questions and prove you're worth hiring, there's light at the end of the tunnel: a job offer.
Once that offer letter hits your inbox, you know what you're supposed to do next. Always negotiate. That's easier said than done, especially if you desperately want the job and it's already a pretty good offer. Is asking for more money or a better compensation package pushing it?
Fortunately, there are people who specialize in coaching candidates through this mission-critical moment. One of them, Karen Catlin, is a 25-year tech veteran who now advocates for women in tech. She's a speaker and coach who helps clients get better salaries, signing bonuses and higher-level roles.
The 12 magic words? "If you can get me X, I'll accept the offer right away."
Catlin recently encouraged a young woman to use this tactic who was deciding between three job offers. The one she was most excited about was also the highest offer. But Catlin thought she could get more. The candidate used that exact phrasing and asked for 5 percent more. Two days later, her counter offer was accepted. She accepted on the spot.
Recruiters and hiring managers expect candidates to counter. But there's a right and a wrong way to do it. There are a few reasons why this particular phrase is so effective in getting you more money.
Hiring managers look for more than competency and cultural fit. They want to hire people who are enthusiastic about the role and company. It's one reason why ending your interview with a candid statement could sway the hiring manager in your favor.
When it comes time to negotiate, using this phrase shows the hiring manager how excited you are about this job. They know you're likely considering other offers. But now you're telling them you're willing to forget the others because this is The One.
Catlin says there's often some wiggle room in the salary or the compensation package. If the hiring manager knows you're ready to sign on the dotted line, that gives her some leverage. She's more likely to be able to meet your request if she already knows you will say yes.
"Assuming it's a reasonable request, the recruiter has something tangible to bring back to the hiring committee," Catlin writes. "It's easier to make a case to dip into the reserves if the recruiter knows you'll say yes."
No one wants to hire a wishy washy candidate. They want people who take action. That's exactly what this negotiation tactic does. You're not just asking for more money, crossing your fingers that they'll say yes. You're laying out a clear course of action. One that involves a better offer to move forward.
"Recruiters also love this approach because it demonstrates a decisive leadership style," Catlin says. "Chances are, they want to hire people like that."
If you can get me one work-from-home day a week, I'll accept the offer right away.
If you can get me one more week of PTO, I'll accept the offer right away.
If you can get me a corner office, daily visits from a massage therapist and a personal chef, I'll accept the offer right away.
OK obviously kidding on the last one, but you get the point. There are a lot of things you can ask for beyond a higher salary. As long as the ask is reasonable, you have a pretty good chance at landing an awesome job that comes with an even awesomer offer. |
= = Exploration on hold = =
|
module TelescopingLet where
module Star where
★ : Set₁
★ = Set
★₁ : Set₂
★₁ = Set₁
module MEndo (open Star) (A : ★) where
Endo : ★
Endo = A → A
module Batch1 where
f : (let ★ = Set) (A : ★) → A → A
f A x = x
g : (let ★ = Set
Endo = λ A → A → A) (A : ★) → Endo A
g = f
h : (open Star) (A : ★) → A → A
h = g
module N (open Star) (A : ★) (open MEndo A) (f : Endo) where
B : ★
B = A
f' : Endo
f' = f
-- module N can be desugared as follows:
module _ where
open Star
module _ (A : ★) where
open MEndo A
module N' (f : Endo) where
B : ★
B = A
f' : Endo
f' = f
-- Here are instantiations of N and its desugaring:
f'1 = f'
where
postulate A : Set
f : A → A
open N A f
f'2 = f'
where
postulate A : Set
f : A → A
open N' A f
data ⊥ : Set where
module Batch2 where
f = λ (let ★ = Set) (A : ★) (x : A) → x
g = λ (open Star) (A : ★) (x : A) → x
h0 = let open Star in
λ (A : ★) →
let module MA = MEndo A in
let open MA in
λ (f : Endo) →
f
h1 = let open Star in
λ (A : ★) →
let open MEndo A in
λ (f : Endo) →
f
h = λ (open Star) (A : ★) (open MEndo A) (f : Endo) → f
module Batch3 where
e1 : (let ★ = Set) → ★
e1 = ⊥
e2 = λ (let ★ = Set) → ★
e3 = λ (open Star) → ★
-- "λ (open M es) → e" is an edge case which behaves like "let open M es in e"
|
export
run_simulation,
simulate_encounters,
simulate_encounter
#=
The main script that simulates encounters.
=#
#=
Description:
This method simulates a single encounter. Abstractly, this
entails initializing an encounter, simulating
each uav in the environment taking actions, and then
simulating the trajectories resulting from these actions.
Parameters:
- environment: the environment in which to simulate the encounter
Return Value:
- encounter: a single encounter object
=#
function simulate_encounter(environment::Environment)
# select a random start state
state = start_encounter(environment)
# create an encounter to track information
encounter = Encounter()
update!(encounter, state)
# simulate the actual encounter
for idx in 1:environment.max_steps
actions = get_uav_actions!(environment, state, encounter)
state = step!(environment, state, actions, encounter)
end
return encounter
end
#=
Description:
This method simulates a variable number of encounters using the
environment provided to it.
Parameters:
- environment: the environment in which to simulate encounters
- num_encounters: the number of encounters to simulate
Return Value:
- encounters: a list of encounter objects which contain all the
information needed to visualize each encounter
=#
function simulate_encounters(environment::Environment, num_encounters::Int64)
# simulate num_encounters, collecting encounter information
encounters = Array(Encounter, num_encounters)
for idx in 1:num_encounters
encounters[idx] = simulate_encounter(environment)
end
return encounters
end
#=
Description:
Main method that performs setup and then calls simulate_encounters
to actually simulate encounters.
=#
function run_simulation(;num_encounters = 1)
# get the environment to simulate encounters in
environment = build_environment()
# simulate the encounters
encounters = simulate_encounters(environment, num_encounters)
end
|
clean_price <- function(data_price, file_price) {
data_price <- data_price %>%
mutate(date = str_replace_all(date, "\u00C3\u00a4", "\u00e4")) %>%
mutate(date = str_replace(date, "Jan", "J\u00e4n")) %>%
mutate(date = as.Date(date, format = "%d.%b.%Y")) %>%
mutate(price = as.numeric(price))
if (file.exists(file_price)) {
data_price <- bind_rows(data_price, read_tsv(file_price)) %>%
unique() %>%
group_by(date) %>%
filter(row_number() == 1) %>%
ungroup() %>%
arrange(desc(date))
}
write_tsv(data_price, file_price)
}
|
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
module Main where
import Test.Hspec
import Test.QuickCheck
import Numeric.LinearAlgebra
import qualified Data.Vector.Storable as V
import Test.Gen
import Test.Utils
main = hspec $ do
describe "Corr Single" $ do
it "implements corr2 correct.0" $ do
forAll (pair (squared_real_matrices 3) (squared_real_matrices 4)) $
\(m1, m2) -> ioProperty $ do
r <- test_corr2 2 m1 m2
return $ good_corr2 2 m1 m2 `eqShowWhenFail` r
it "implements corr2 correct.1" $ do
forAll (pair (squared_real_matrices 9) (squared_real_matrices 9)) $
\(m1, m2) -> ioProperty $ do
r <- test_corr2 4 m1 m2
return $ good_corr2 4 m1 m2 `eq` r
it "implements corr2 correct.2" $ do
forAll (pair (squared_real_matrices 5) (squared_real_matrices 28)) $
\(m1, m2) -> ioProperty $ do
r <- test_corr2 2 m1 m2
return $ eqShowWhenFail (good_corr2 2 m1 m2) r
it "implements corr2 correct.3" $ do
forAll (pair (choose (2,30)) (pair small_matrices small_matrices)) $
\(p, (m1, m2)) -> ioProperty $ do
r <- test_corr2 p m1 m2
return $ good_corr2 p m1 m2 `eqShowWhenFail` r
describe "Corr Many" $ do
it "with 2 kernels" $ do
forAll (pair (sequence $ replicate 2 $ squared_real_matrices 3) (squared_real_matrices 7)) $
\(m1s, m2) -> ioProperty $ do
rs <- test_corr2_arr 2 m1s m2
return $ conjoin $ zipWith (\m r -> good_corr2 2 m m2 `eqShowWhenFail` r) m1s rs
it "with 5 kernels" $ do
forAll (pair (sequence $ replicate 4 $ squared_real_matrices 15) (squared_real_matrices 88)) $
\(m1s, m2) -> ioProperty $ do
rs <- test_corr2_arr 2 m1s m2
ss <- return $ map (\m -> good_corr2 2 m m2) m1s
return $ conjoin $ zipWith eq rs ss
eqShowWhenFail m1 m2 =
whenFail (do let va = flatten m1
let vb = flatten m2
let err x 0 = x
err x y = abs ((x - y) / y)
let ev = (V.zipWith err va vb)
ei = V.maxIndex ev
putStrLn $ "Max error ration: " ++ show (ev V.! ei, va V.! ei, vb V.! ei)
putStrLn $ show m1
putStrLn $ show m2)
(m1 `eq` m2)
|
module Oscar.Class.Reflexivity where
open import Oscar.Level
record Reflexivity {a} {A : Set a} {ℓ} (_≋_ : A → A → Set ℓ) : Set (a ⊔ ℓ) where
field
reflexivity : ∀ {x} → x ≋ x
open Reflexivity ⦃ … ⦄ public
|
If $P_i$ is a $\sigma$-algebra for each $i$, then $\{x \in \Omega \mid \forall i \in X, P_i(x)\}$ is a $\sigma$-algebra. |
library(dbscan)
cl <- dbscan(iris[,-5], eps = .5, minPts = 5)
plot(iris[,-5], col = cl$cluster)
|
-- Andreas, 2016-12-31, issue #2371 reported by subttle
-- Module parameter Nat shadowed by import
module Issue2371 (Nat : Set) where
open import Agda.Builtin.Nat
-- C-c C-n zero RET
-- ERROR WAS:
-- An internal error has occurred. Please report this as a bug.
-- Location of the error: src/full/Agda/Utils/List.hs:304
-- Should succeed.
-- C-c C-n Nat RET will report an ambiguous name
|
A set $S$ is closed if and only if its closure is a subset of $S$. |
Formal statement is: lemma metric_isCont_LIM_compose2: fixes f :: "'a :: metric_space \<Rightarrow> _" assumes f [unfolded isCont_def]: "isCont f a" and g: "g \<midarrow>f a\<rightarrow> l" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> dist x a < d \<longrightarrow> f x \<noteq> f a" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> l" Informal statement is: If $f$ is continuous at $a$ and $g$ is continuous at $f(a)$, then $g \circ f$ is continuous at $a$. |
\chapter{Results}\label{Chap:Results}
\begin{figure}
\centering
\subcaptionbox{$\nu_3=5\e{-15}$}
{\input{figures/visc1024_nu_hyper_5e-15_mag_spec.pgf}}
\subcaptionbox{$\nu_3=5\e{-15}$}
{\input{figures/visc1024_nu_hyper_2e-14_mag_spec.pgf}}\\
\subcaptionbox{$\nu=5\e{-6}$}
{\input{figures/visc1024_nu_5e-6_mag_spec.pgf}}
\subcaptionbox{$\nu=1\e{-5}$}
{\input{figures/visc1024_nu_1e-5_mag_spec.pgf}}\\
\subcaptionbox{$\nu=5\e{-5}$}
{\input{figures/visc1024_nu_5e-5_mag_spec.pgf}}
\subcaptionbox{$\nu=1\e{-4}$}
{\input{figures/visc1024_nu_1e-4_mag_spec.pgf}}
\caption{Compilation of the different runs with varying viscosities $\nu$}
\label{Fig:visc_grid}
\end{figure}
\begin{itemize}
\item Organize material and present results.
\item Use tables, figures (but prefer visual presentation):
\begin{itemize}
\item Tables and figures should supplement (and not duplicate) the
text.
\item Tables and figures should be provided with
legends.\\
\textit{ Figure \ref{Fig:visc_grid} shows how to include and reference
graphics. The graphic must be labelled before. Files must be in
\texttt{.eps} format.}
\begin{figure}[ht]
\centering
\subcaptionbox{helical at $t=0$}
{\includegraphics[width=0.49\textwidth]{helical_bb_slice_t0.pdf}}
\subcaptionbox{helical at $t=100$}
{\includegraphics[width=0.49\textwidth]{helical_bb_slice_t100.pdf}}
\label{Fig:helical}
\caption{Slices of the run with $\mathcal{H}=\mathcal{H}_\textrm{max}$}
\end{figure}
\item Tables and graphics may appear in the text or in
the appendix, especially if there are many simulation results
tabulated, but is also depends on the study and number of tables resp.
figures. The key graphs and tables must appear in
the text!
\end{itemize}
\item Latex is really good at rendering formulas:\\
\textit{Equation (\ref{Eq:SpecDens}) represents the ACs of a stationary
stochastic process:
\begin{equation}
f_y(\lambda) = (2\pi)^{-1} \sum_{j=-\infty}^{\infty}
\gamma_j e^{-i\lambda j}
=(2\pi)^{-1}\left(\gamma_0 + 2 \sum_{j=1}^{\infty}
\gamma_j \cos(\lambda j)\right)
\label{Eq:SpecDens}
\end{equation}
where $i=\sqrt{-1}$ is the imaginary unit, $\lambda \in [-\pi,
\pi]$ is the frequency and the $\gamma_j$ are the autocovariances
of $y_t$.}
\newpage
\item Discuss results:
\begin{itemize}
\item Do the results support or do they contradict economic theory ?
\item What does the reader learn from the results?
\item Try to give an intuition for your results.
\item Provide robustness checks.
\item Compare to previous research.
\end{itemize}
\end{itemize}
|
From iris.algebra Require Import cmra list.
Lemma replicate_op {A: ucmraT} (a b: A) n:
replicate n (a ⋅ b) = replicate n a ⋅ replicate n b.
Proof. apply list_eq. induction n; simpl. done. case; done. Qed.
Lemma included_None {A: cmraT} (a : option A):
(a ≼ None) -> a = None.
Proof.
rewrite option_included. case; first done.
intros (? & ? & _ & HContra & _). discriminate.
Qed.
Lemma None_least (A: cmraT) (a: option A): None ≼ a.
Proof. by apply option_included; left. Qed.
Theorem prod_included':
forall (A B: cmraT) (x y: (A * B)), x.1 ≼ y.1 ∧ x.2 ≼ y.2 -> x ≼ y.
Proof.
by intros; apply prod_included.
Qed.
Lemma None_op_left_id {A: cmraT} (a: option A): None ⋅ a = a.
Proof. rewrite /op /cmra_op /=. by destruct a. Qed.
Theorem prod_included'':
forall (A B: cmraT) (x y: (A * B)), x ≼ y -> x.1 ≼ y.1 ∧ x.2 ≼ y.2.
Proof.
by intros; apply prod_included.
Qed.
Theorem prod_included''':
forall (A B: cmraT) (x x' : A) (y y': B), (x, y) ≼ (x', y') -> x ≼ x' ∧ y ≼ y'.
Proof.
intros ? ? ? ? ? ? HEv.
apply prod_included'' in HEv.
by simpl in *.
Qed.
Lemma list_validN_app {A: ucmraT} (x y : list A) (n: nat):
✓{n} (x ++ y) <-> ✓{n} x ∧ ✓{n} y.
Proof. apply Forall_app. Qed.
|
theory Chapter12_5
imports "HOL-IMP.Hoare_Total"
begin
text\<open>
\exercise
Prove total correctness of the commands in exercises~\ref{exe:Hoare:sumeq} to
\ref{exe:Hoare:sqrt}.
\<close>
definition Eq :: "aexp \<Rightarrow> aexp \<Rightarrow> bexp" where
"Eq a1 a2 = (And (Not (Less a1 a2)) (Not (Less a2 a1)))"
lemma bval_Eq[simp]: "bval (Eq a1 a2) s = (aval a1 s = aval a2 s)"
unfolding Eq_def by auto
lemma
"\<turnstile>\<^sub>t {\<lambda>s. s ''x'' = i \<and> 0 \<le> i}
''y'' ::= N 0;;
WHILE Not(Eq (V ''x'') (N 0))
DO (''y'' ::= Plus (V ''y'') (V ''x'');;
''x'' ::= Plus (V ''x'') (N (-1)))
{\<lambda>s. s ''y'' = sum i}"
(is "\<turnstile>\<^sub>t {?HI} ''y'' ::= ?yi;; WHILE ?bx DO (''y'' ::= ?ay;; ''x'' ::= ?ax) {?HE}")
proof (intro Seq While_fun' allI impI; (elim conjE)?)
let ?ax = "Plus (V ''x'') (N (- 1))"
let ?ay = "Plus (V ''y'') (V ''x'')"
let ?P = "\<lambda>s. s ''y'' = sum i - sum (s ''x'') \<and> 0 \<le> s ''x''"
let ?f = "\<lambda>s::state. nat (s ''x'')"
let ?Pw' = "\<lambda>n s. ?P s \<and> ?f s < n"
let ?Q = "\<lambda>n s. ?Pw' n (s[?ax/''x''])"
let ?Pw = "\<lambda>n s. ?P s \<and> bval ?bx s \<and> n = ?f s"
let ?yi = "N 0"
{
have "\<forall>s. ?HI s \<longrightarrow> ?P (s[?yi/''y''])"
proof (intro allI impI, elim conjE)
fix s
assume Hxi: "s ''x'' = i"
then have "(s[?yi/''y'']) ''y'' = sum i - sum ((s[?yi/''y'']) ''x'')" (is ?H1) by simp
moreover assume Hi: "0 \<le> i"
with Hxi have "0 \<le> (s[?yi/''y'']) ''x''" (is ?H2) by simp
ultimately show "?H1 \<and> ?H2" by blast
qed
from Assign' [OF this] show "\<turnstile>\<^sub>t {?HI} ''y'' ::= ?yi {?P}" .
next
fix s
assume HP: "?P s"
assume "\<not>bval ?bx s"
then have "s ''x'' = 0" by simp
with HP show "s ''y'' = sum i" by simp
next
fix n
show "\<turnstile>\<^sub>t {?Q n} ''x'' ::= ?ax {?Pw' n}" by (rule Assign)
next
fix n
have "\<forall>s. ?Pw n s \<longrightarrow> ?Q n (s[?ay/''y''])"
proof (intro allI impI conjI; elim conjE)
fix s
assume assm: "s ''y'' = sum i - sum (s ''x'')" "0 \<le> s ''x''" "bval (bexp.Not (Eq (V ''x'') (N 0))) s" "n = nat (s ''x'')"
from assm(2, 3) have Hx0: "0 < s ''x''" by simp
from assm(1) have "((s[?ay/''y''])[?ax/''x'']) ''y'' = sum i - sum (s ''x'') + s ''x''" by simp
also from Hx0 have "\<dots> = sum i - sum (s ''x'' - 1)" by auto
also have "\<dots> = sum i - sum (((s[?ay/''y''])[?ax/''x'']) ''x'')" by simp
finally show "((s[?ay/''y''])[?ax/''x'']) ''y'' = sum i - sum (((s[?ay/''y''])[?ax/''x'']) ''x'')" .
from Hx0 show "0 \<le> ((s[?ay/''y''])[?ax/''x'']) ''x''" by simp
from Hx0 assm(4) show "?f ((s[?ay/''y''])[?ax/''x'']) < n" by auto
qed
from Assign' [OF this] show "\<turnstile>\<^sub>t {?Pw n} ''y'' ::= ?ay {?Q n}" .
}
qed
lemma
"\<turnstile>\<^sub>t {\<lambda>s. s ''x'' = x \<and> s ''y'' = y \<and> 0 \<le> x}
WHILE Less (N 0) (V ''x'')
DO (''x'' ::= Plus (V ''x'') (N (-1));; ''y'' ::= Plus (V ''y'') (N (-1)))
{\<lambda>t. t ''y'' = y - x}"
proof (rule strengthen_pre; intro While_fun' Seq allI impI; (elim conjE)?)
let ?b = "Less (N 0) (V ''x'')"
let ?P = "\<lambda>s. s ''y'' - s ''x'' = y - x \<and> 0 \<le> s ''x''"
let ?f = "\<lambda>s::state. nat(s ''x'')"
let ?Pw' = "\<lambda>n s. ?P s \<and> ?f s < n"
let ?Pw = "\<lambda>n s. ?P s \<and> bval ?b s \<and> n = ?f s"
let ?Qold = "\<lambda>s. s ''y'' - 1 - s ''x'' = y - x \<and> 0 \<le> s ''x''"
let ?ay = "Plus (V ''y'') (N (- 1))"
let ?ax = "Plus (V ''x'') (N (- 1))"
let ?Q = "\<lambda>n s. ?Pw' n (s[?ay/''y''])"
{
fix s
assume "s ''x'' = x" "s ''y'' = y" "0 \<le> x"
then show "?P s" by simp
next
fix s
assume "\<not> bval (Less (N 0) (V ''x'')) s"
then have "s ''x'' \<le> 0" by simp
moreover assume "?P s"
ultimately show "s ''y'' = y - x" by simp
next
fix n
show "\<turnstile>\<^sub>t {?Q n} ''y'' ::= ?ay {?Pw' n}" by (rule Assign)
next
fix n
have "\<forall>s. ?Pw n s \<longrightarrow> ?Q n (s[?ax/''x''])"
proof (intro allI impI conjI; elim conjE)
fix s
assume assm: "s ''y'' - s ''x'' = y - x" "bval (Less (N 0) (V ''x'')) s" "n = nat (s ''x'')"
from assm(2) have Hx0: "0 < s ''x''" by simp
from assm(1) show "((s[?ax/''x''])[?ay/''y'']) ''y'' - ((s[?ax/''x''])[?ay/''y'']) ''x'' = y - x" by simp
from Hx0 show "0 \<le> ((s[?ax/''x''])[?ay/''y'']) ''x''" by simp
from assm(3) Hx0 show "?f ((s[Plus (V ''x'') (N (- 1))/''x''])[Plus (V ''y'') (N (- 1))/''y'']) < n" by simp
qed
then show "\<turnstile>\<^sub>t {?Pw n} ''x'' ::= ?ax {?Q n}" by (rule Assign')
}
qed
lemma
"\<turnstile>\<^sub>t { \<lambda>s. s ''x'' = i \<and> 0 \<le> i}
''r'' ::= N 0;; ''r2'' ::= N 1;;
WHILE (Not (Less (V ''x'') (V ''r2'')))
DO (''r'' ::= Plus (V ''r'') (N 1);;
''r2'' ::= Plus (V ''r2'') (Plus (Plus (V ''r'') (V ''r'')) (N 1)))
{\<lambda>s. (s ''r'')^2 \<le> i \<and> i < (s ''r'' + 1)^2}"
proof (intro Seq While_fun' allI impI conjI; (elim conjE)?)
let ?b = "Not (Less (V ''x'') (V ''r2''))"
let ?ar = "Plus (V ''r'') (N 1)"
let ?ar2 = "Plus (V ''r2'') (Plus (Plus (V ''r'') (V ''r'')) (N 1))"
let ?I = "\<lambda>s. s ''x'' = i \<and> 0 \<le> i"
let ?II = "\<lambda>s. s ''x'' = i \<and> (s ''r'')\<^sup>2 \<le> s ''x'' \<and> 1 = (s ''r'' + 1)\<^sup>2 \<and> 0 \<le> s ''r''"
let ?P = "\<lambda>s. s ''x'' = i \<and> (s ''r'')\<^sup>2 \<le> s ''x'' \<and> s ''r2'' = (s ''r'' + 1)\<^sup>2 \<and> 0 \<le> s ''r''"
let ?f = "\<lambda>s::state. nat (s ''x'' + 1 - s ''r2'')"
let ?Qold = "\<lambda>s. s ''x'' = i \<and> (s ''r'')\<^sup>2 \<le> s ''x'' \<and> s ''r2'' = (s ''r'')\<^sup>2"
let ?Pw' = "\<lambda>n s. ?P s \<and> ?f s < n"
let ?Q = "\<lambda>n s. ?Pw' n (s[?ar2/''r2''])"
let ?Pw = "\<lambda>n s. ?P s \<and> bval ?b s \<and> n = ?f s"
{
have "\<forall>s. ?I s \<longrightarrow> ?II (s[N 0/''r''])" by auto
then show "\<turnstile>\<^sub>t {?I} ''r'' ::= N 0 {?II}" by (rule Assign')
next
have "\<turnstile>\<^sub>t {\<lambda>s. ?P (s[N 1/''r2''])} ''r2'' ::= N 1 {?P}" by (rule Assign)
then show "\<turnstile>\<^sub>t {?II} ''r2'' ::= N 1 {?P}" by simp
next
fix s
assume "?P s"
then have H: "s ''x'' = i" "(s ''r'')\<^sup>2 \<le> s ''x''" "s ''r2'' = (s ''r'' + 1)\<^sup>2" by blast+
moreover assume "\<not> bval ?b s"
then have "s ''x'' < s ''r2''" by auto
ultimately show "(s ''r'')\<^sup>2 \<le> i" "i < (s ''r'' + 1)\<^sup>2" by auto
next
fix n
have Heqv: "\<And>x::int. (x + 1)\<^sup>2 = x\<^sup>2 + x + x + 1" by (simp add: power2_sum)
show "\<turnstile>\<^sub>t {?Q n} ''r2'' ::= ?ar2 {?Pw' n}" by (rule Assign)
next
fix n
have "\<forall>s. ?Pw n s \<longrightarrow> ?Q n (s[?ar/''r''])"
proof auto
fix s :: state
let ?r = "s ''r''"
have "(?r + 1)\<^sup>2 + (3 + 2 * ?r) = ?r\<^sup>2 + 4 * ?r + 4" by (simp add: power2_sum)
also have "\<dots> = (2 + ?r)\<^sup>2" by (simp add: power2_sum)
finally show "(?r + 1)\<^sup>2 + (3 + 2 * ?r) = (2 + ?r)\<^sup>2" .
qed
then show "\<turnstile>\<^sub>t {?Pw n} ''r'' ::= ?ar {?Q n}" by (rule Assign')
}
qed
text\<open>
\endexercise
\exercise
Modify the VCG to take termination into account. First modify type @{text acom}
by annotating @{text WHILE} with a measure function in addition to an
invariant:
\<close>
datatype acom =
Askip ("SKIP") |
Aassign vname aexp ("(_ ::= _)" [1000, 61] 61) |
Aseq acom acom ("_;;/ _" [60, 61] 60) |
Aif bexp acom acom ("(IF _/ THEN _/ ELSE _)" [0, 0, 61] 61) |
Awhile assn "state \<Rightarrow> nat" bexp acom
("({_, _}/ WHILE _/ DO _)" [0, 0, 61] 61)
notation com.SKIP ("SKIP")
fun strip :: "acom \<Rightarrow> com" where
"strip SKIP = SKIP" |
"strip (x ::= a) = (x ::= a)" |
"strip (C\<^sub>1;; C\<^sub>2) = (strip C\<^sub>1;; strip C\<^sub>2)" |
"strip (IF b THEN C\<^sub>1 ELSE C\<^sub>2) = (IF b THEN strip C\<^sub>1 ELSE strip C\<^sub>2)" |
"strip ({_,_} WHILE b DO C) = (WHILE b DO strip C)"
fun pre :: "acom \<Rightarrow> assn \<Rightarrow> assn" where
"pre SKIP Q = Q" |
"pre (x ::= a) Q = (\<lambda>s. Q(s(x := aval a s)))" |
"pre (C\<^sub>1;; C\<^sub>2) Q = pre C\<^sub>1 (pre C\<^sub>2 Q)" |
"pre (IF b THEN C\<^sub>1 ELSE C\<^sub>2) Q =
(\<lambda>s. if bval b s then pre C\<^sub>1 Q s else pre C\<^sub>2 Q s)" |
"pre ({I,f} WHILE b DO C) Q = I"
fun vc :: "acom \<Rightarrow> assn \<Rightarrow> bool" where
"vc SKIP Q = True" |
"vc (x ::= a) Q = True" |
"vc (C\<^sub>1;; C\<^sub>2) Q = (vc C\<^sub>1 (pre C\<^sub>2 Q) \<and> vc C\<^sub>2 Q)" |
"vc (IF b THEN C\<^sub>1 ELSE C\<^sub>2) Q = (vc C\<^sub>1 Q \<and> vc C\<^sub>2 Q)" |
"vc ({I, f} WHILE b DO C) Q =
(\<forall>n. (\<forall>s. (I s \<and> bval b s \<and> n = f s \<longrightarrow> pre C (\<lambda>s. I s \<and> f s < n) s) \<and>
(I s \<and> \<not> bval b s \<longrightarrow> Q s)) \<and>
vc C (\<lambda>s. I s \<and> f s < n))"
text\<open>
Functions @{const strip} and @{const pre} remain almost unchanged.
The only significant change is in the @{text WHILE} case for @{const vc}.
Modify the old soundness proof to obtain
\<close>
lemmas [simp] = hoaret.Skip hoaret.Assign hoaret.Seq If
lemmas [intro!] = hoaret.Skip hoaret.Assign hoaret.Seq hoaret.If
lemma vc_sound: "vc C Q \<Longrightarrow> \<turnstile>\<^sub>t {pre C Q} strip C {Q}"
proof(induct C arbitrary: Q)
case (Awhile I f b C)
show ?case
proof (simp, rule While_fun')
from Awhile(2) show "\<forall>s. I s \<and> \<not> bval b s \<longrightarrow> Q s" by auto
fix n
from Awhile(2) have "\<forall>s. I s \<and> bval b s \<and> n = f s \<longrightarrow> pre C (\<lambda>s. I s \<and> f s < n) s" by auto
moreover from Awhile(2) have "vc C (\<lambda>s. I s \<and> f s < n)" by auto
with Awhile(1) have "\<turnstile>\<^sub>t {pre C (\<lambda>s. I s \<and> f s < n)} strip C {\<lambda>s. I s \<and> f s < n}" by auto
ultimately show "\<turnstile>\<^sub>t {\<lambda>s. I s \<and> bval b s \<and> n = f s} strip C {\<lambda>s. I s \<and> f s < n}" by (rule strengthen_pre)
qed
qed (auto intro: hoaret.conseq)
text\<open>
You may need the combined soundness and completeness of @{text"\<turnstile>\<^sub>t"}:
@{thm hoaret_sc}
\endexercise
\<close>
end
|
Here at Fireplace Installation Guys, we're ready to meet all your requirements when it comes to Fireplace Installation in Armada, MI. Our crew of experienced contractors can offer the expert services that you need with the most sophisticated technology available. Our products are of the highest quality and we can conserve your money. Give us a call by dialing 844-244-6166 to get started.
Lowering costs is a valuable part for your task. You still need excellent quality results with Fireplace Installation in Armada, MI, and you're able to put your confidence in our staff to conserve your funds while continually giving the very best quality work. We provide the best quality while still costing you less. Our ambition is to ensure you receive the highest quality materials and a finished project that lasts over time. As an example, we are very careful to keep clear of expensive complications, deliver the results efficiently to conserve time, and be sure you get the most effective prices on materials and work. Save time and funds by contacting Fireplace Installation Guys now. We'll be waiting to accept your call at 844-244-6166.
It is important to be knowledgeable with regards to Fireplace Installation in Armada, MI. We won't encourage you to come up with imprudent choices, since we understand exactly what we'll be doing, and we ensure you know exactly what to expect with the work. We will take the unexpected surprises from the situation through providing precise and complete info. Begin by calling 844-244-6166 to discuss your task. We'll explore your concerns once you call us and get you arranged with an appointment. We consistently appear at the arranged hour, all set to work together with you.
Many good reasons exist to consider Fireplace Installation Guys regarding Fireplace Installation in Armada, MI. Our equipment are of the very best quality, our cash saving solutions are realistic and powerful, and our client satisfaction scores will not be topped. We have the expertise you will want to meet all your objectives. If you need Fireplace Installation in Armada, call Fireplace Installation Guys by dialing 844-244-6166, and we are going to be beyond pleased to help. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.